Computer Programming 1
Constants, Input
and Output
Commands
Header files and symbolic constants
#include is an instruction to read the entire
contents of another file at that point.
Header files contain details of functions and types
used within the library.
They must be included before the program can
make use of the library functions.
Format: #include<filename>
Example: #include<stdio.h>
Introduction to C Programming Page 1 of 98
Constants, Input
and Output
Commands
#define preprocessor directive defines constants.
A C constant is really the same thing as a literal.
Note that a literal is a data value that doesn’t change, like
the number 4 or a string “STI”.
Format: #define CONSTANT Value
Example:
#define PI 3.1416
#define NAME “Julio Jose”
Constants, Input
and Output
Commands
Sample program on input and output
Create a C program that will let the user enter a
value for age, then increment the age by 5 and
print the result.
#include<stdio.h>
void main()
{ int age;
age = 0;
printf(“\nEnter a value for age: “);
scanf(“%d”,&age);
age = age + 5;
printf(“\nAge is %d”,age);
}
Constants, Input
and Output
Commands
#include<stdio.h>
void main()
int age;
Constants, Input
and Output
Commands
printf(“\nEnter a value for age:
scanf(“%d”,&age);
age = age +
printf(“\nAge is
Constants, Input
and Output
Commands
Format specifiers in
C
int age;
age = 5;
printf(“\nAge is %d”, age);
Age is
New line
Constants, Input
and Output
Commands
MORE ON THE CONVERSION OR FORMAT SPECIFIERS
%c for char variables or constants
%d for int variables or constants
%f for float variables or constants
%e similar to %f except that the output
is in scientific notation
%g same as %f or %e whichever is shorter
Constants, Input
and Output
Commands
SAMPLE PROGRAMS
1.) # include <stdio.h>
void main()
{
char sample;
sample = ‘B’;
printf (“The letter is %c.”, sample);
}
OUTPUT:
The letter is M.
2.) #include <stdio.h>
main()
{
float A, B, sum;
A = 14.75;
B = 5.30;
sum = x + y;
printf(“SUM: %f.\n”, sum);
}
OUTPUT:
SUM: 20.05
Constants, Input
and Output
Commands
SAMPLE PROGRAMS
#include <stdio.h>
void main()
{
int X;
int Y;
X = 2
Y = 5;
printf (“Result of 2 * 5 is %d.”, X *
Y);
OUTPUT:
Result of 2 * 5 is
Constants, Input
and Output
Commands
THE scanf() FUNCTION
The purpose of the scanf() function is to input
data to a program. If printf() is for printing
formatted output, then scanf() is for reading
formatted input.
Example:
scanf(“%d”, &num);
General Syntax:
scanf(“Format_specifier”,&variable);
Constants, Input
and Output
Commands
scanf(“Format_specifier”,&variable);
A valid variable that would
correspond with the format specifier.
The ampersand is a pointer to the
variable
These are the %d, %f, %c, %s, etc. Place
the proper format specifier that would
correspond to the variable’s data type.
Constants, Input
and Output
Commands
Program to convert dollars to pesos
#include
<stdio.h> void
main()
{
float dollars, pesos;
printf (“Enter the no. of dollars you want to
convert: ”);
scanf (“%f”, &dollars);
pesos = dollars *
26.95;
printf (“\n\n$ %.2f is equal to %.2f pesos.”,
dollars,pesos);
}
Constants, Input
and Output
Commands
Program to compute the area of a circle
#include <stdio.h>
void main()
{
float radius, area, pi = 3.14;
printf (“Enter the radius of the circle:
“); scanf (“%f”, &radius);
area = pi * radius * radius;
printf (“\n\nThe area of the circle is %.2f.”, area);
}
OUTPUT:
Enter the radius of the circle: 2.0
(enter)
The area of the circle is 12.56.
Constants, Input
and Output
Commands
Program to prompt the user to enter his initials and age
#include <stdio.h>
main()
{
char first, middle, last;
int age;
printf (“Enter your three initials and age: “);
scanf (“%c%c%c%d”, &first, &middle, &last, &age);
printf (“\n\nGreetings %c.%c.%c. Next year your age will
be %d.”, first, middle, last, age + 1);
}
OUTPUT:
Enter your three initials and age: JAJ23
Greetings J.A.J. Next year your age will be
24.
Constants, Input
and Output
Commands
scanf (“%c%c%c%d”, &first, &middle, &last, &age);
Logical and
Relational
Operators in C
RELATIONAL OPERATORS AND EXPRESSIONS
A relational expression compares two values. If the
relation or comparison is true, the expression has a value
of 1 (or any non-zero value in some implementation). If
false, the expression has a value of 0.
For example, the expression 5 < 1 is equal to 0 (false)
while
3 > 2 is equal to 1 (true).
The relational operators are:
< less than
> greater than
< = less than or equal
> = greater than or
equal
Logical and
Relational
Operators in C
RELATIONAL OPERATORS AND EXPRESSIONS
Relational operators have a lower precedence than the
arithmetic operators and their associativity is from left to
right.
Example:
x-y< 0 is equivalent to (x - y) < 0
z >= w + 1 is equivalent to z >= (w + 1)
a - b > c + d is equivalent to (a-b) > (c+d)
Logical and
Relational
Operators in C
RELATIONAL OPERATORS AND EXPRESSIONS
The following table reinforces the concept of how C uses 0
for false and 1 for true:
e1 - e2 e 1 <e e 1 >e e 1 <=e 2 e 1 >=e
2 2 2
+ 0 1 0 1
0 0 0 1 1
- 1 0 1 0
Examples:
Assume that x = 5, y = 3, z = 10
x+y<=z true
z/x>y false
x + y >= z - y true
y * z / x <= x + 1 true
z>x *y false
Logical and
Relational
Operators in C
EQUALITY OPERATORS AND EXPRESSIONS
An equality expression compares whether two values are
equal or not.
The equality operators are:
= = equal
! = not equal
If the comparison is true, the expression has a value
of 1 and 0 if the relation is false.
Examples:
2 = = 2 is 1 (true) while 2 != 2 is 0 (false)
3 != 5 is 1 (true) while 3 = = 5 is 0 (false)
Logical and
Relational
Operators in C
EQUALITY OPERATORS AND EXPRESSIONS
The equality operators have a lower precedence than the
relational operators and their associativity is from left to
right.
Examples:
p*q==0 is equivalent to (p * q) = =
0 m != n - 7 is equivalent to m != (n - 7)
a - b != c + d is equivalent to (a-b) != (c+d)
Logical and
Relational
Operators in C
LOGICAL OPERATORS AND EXPRESSIONS
Logical expressions involve Boolean operations.
The logical operations
&& and
| or (double
| pipe) not
Logical and
Relational
Operators in C
LOGICAL OPERATORS AND EXPRESSIONS
The operands of logical operators are usually relational
or equality expressions.
Examples:
(a < b) && (c > d)
checks if a is less than b AND if c
is greater than d
(w = = x) || (y <= z)
checks if w is equal to x OR if y
is less than or equal to z
! (p < = q)
checks if p is NOT less than or
equal to q. This expression is
actually equivalent to p > q.
Logical and
Relational
Operators in C
LOGICAL OPERATORS AND EXPRESSIONS
The logical operator semantics is given
exp1 exp2 !exp1 !exp2 exp1&&exp2 exp1||exp2
0 0 1 1 0 0
0 1 1 0 0 1
1 0 0 1 0 1
1 1 0 0 1 1
Logical and
Relational
Operators in C
LOGICAL OPERATORS AND EXPRESSIONS
Logical operators have a lower precedence
than relational and equality operators.
Example:
w <= x && y != z (w <= x) && (y != z)
a+1< b || c = = 1+ d ((a+1)< b) || (c = = (1+ d))
Logical and
Relational
Operators in C
LOGICAL OPERATORS AND EXPRESSIONS
Several logical operators can be used in one
expression. In this case, the not operator has the
highest precedence while the or operator has the
lowest.
Example:
w + x < = y - z && w*z || ! (x - y)
(((w + x) < = (y - z )) && (w*z )) || (! (x - y))
Logical and
Relational
Operators in C
LOGICAL OPERATORS AND EXPRESSIONS
Examples:
Assume that x = 6, y = 2, z = 20
x < = z && x < y false
y = = z || x ! = z tru
x + 15 > z && !(y > z) tru
!(x > y) || y > z - 10 false
x > y || x = = z && y < z true
!(x < z) && x >= y + 4 || z = = 19 false
Logical and
Relational
Operators in C
It is possible to assign the result of a relational, equality, or
logical expression to an integer variable.
Examples:
Assume that x = 6, y = 2, z = 20 and a, b, c, d, e, and f are
variables of type int.
a = x < = z && x < y
b = y = = z || x ! = z
c = x + 15 > z && !(y > z)
d = !(x > y) || y > z - 10
e = x > y || x = = z && y < z
f = !(x < z) && x >= y + 4 || z = = 19
Then:
a = 0 b = 1
c = 1 d = 0
e = 1 f=0
IF st at ement
The if statement allows the programmer to make decisions
within a program.
The general format of an if statement
is: if (expression)
statement
where expression represents a relational, equality, or
logical expression (conditional expression).
IF st at ement
Example:
if (final_grade > = 70)
printf (“You passed this course!\n”);
printf (“Your grade is %d.\n”, final_grade);
IF st at ement
If there is a need to execute several statements
(compound statement), then the left and right braces can
group these statements.
Example:
if (final_grade >= 70) {
printf (“You passed this
course!\n”); printf
(“Congratulations!\n”);
}
printf (“Your grade is %d.\n”, final_grade);
IF st at ement
THE if-else STATEMENT
In the if statement, if expression is true, then the
program executes a statement. However, if expression
is false, no action is taken and the program
executes the statement after the if statement. If a
certain action has to be taken if expression is false,
then programmers can use the if-else statement.
The general format of an if-else statement is:
if (expression)
statement1;
else
statement2;
IF st at ement
If expression is true, then the program executes
statement1and skips statement2. If expression is
false, then the program skips statement1 and
executesstatement2.
Example:
if (final_grade > = 70)
printf (“You passed this course!\n”);
else
printf (“You failed this course!\n”);
printf (“Your grade is %d.\n”, final_grade);
IF st at ement
As in the if statement, compound statements may also
be used in if-else statements (provided they are
grouped together by braces).
Example:
if (final_grade > = 70) {
printf (“You passed this
course!\n”); printf
(“Congratulations!\n”);
}
else {
printf (“You failed this
course!”); printf (“Sorry!\n”);
}
printf (“Your grade is %d.\n”, final_grade);
IF st at ement
Nested if
Example
if (x > 5)
if (x < 10)
printf (“x is between 5 and
IF st at ement
Nested if statement
A single if statement may replace several if
statements. The combined expression will be the
logical AND of the different expressions.
The following code is equivalent to the one
previously given:
if (x > 5 && x < 10)
printf (“x is between 5 and 10.”);
IF st at ement
Nested if statement
if statements used within another are said to be nested.
C allows nesting of if statements to any level (an if
inside an if inside an if, and so forth).
Example:
if (annual_gpa >= 3.4)
if (number_of_failures = = 0)
if (number_of_discipline_cases = = 0)
printf (“Congratulations! You are now
a scholar!”);
IF st at ement
DANGLING else
Consider the following
if (x = = 2)
if (y = = 3)
print
(“Julio\n”);
else
This code illustrates the “dangling else”
problem: it is not clear what the else part is
associated with.
IF st at ement
DANGLING else
As far C is concerned, the following code is the same:
if (x = = 2)
if (y = = 3)
print (“Julio\n”);
else
print (“Jose\n”);
The rule is that an else attaches itself to the nearest if.
Thus the first code follows proper indentation.
Computer Programming 1
IF st at ement
PROGRAMMING EXERCISE
Write a C program which prompts the user to
enter two real numbers and outputs the quotient
of the two numbers. However, the program
should make sure that a division by 0 should not
take place.
Page 39 of 98
Computer Programming 1
Introduction to C Programming
Page 40 of 98
IF st at ement
Solution:
void main()
{
float num1, num2, quotient;
printf (“Choose two real numbers.\n\n”);
printf (“First Number > “);
scanf (“%f”, &num1);
printf (“Second Number >
“); scanf (“%f”, &num2);
if (num2 != 0) {
quotient = num1 / num2;
printf(“\n%.2f divided by %.2f is %.2f.”, num1, num2,
quotient);
}
else {
printf (“\nThe division cannot take place!”);
printf (“\nThe divisor is 0.”);
}
printf (“\nEnd of program. Thank you!!!”);
}
Introduction to C Programming