C Operators and Control Structures
C Operators and Control Structures
i. Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.
1|P a g e
int x = 10;
x += 5;
A list of all assignment operators:
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
== Equal to x == y
!= Not equal x != y
2|P a g e
> Greater than x>y
&& Logical and Returns true if both statements are true x < 5 && x < 10
! Logical not Reverse the result, returns false if the result is !(x < 5 && x < 10)
true
v. Sizeof Operator
The memory size (in bytes) of a data type or a variable can be found with the sizeof operator:
Example
int myInt;
float myFloat;
double myDouble;
char myChar;
printf("%lu\n", sizeof(myInt));
printf("%lu\n", sizeof(myFloat));
printf("%lu\n", sizeof(myDouble));
printf("%lu\n", sizeof(myChar));
Note that we use the %lu format specifer to print the result, instead of %d. It is because the
compiler expects the sizeof operator to return a long unsigned int (%lu), instead of int (%d).
On some computers it might work with %d, but it is safer to use %lu.
3|P a g e
CHAPTER THREE: OPERATORS IN C LANGUAGE
Chapter objectives
Describe Operators and operands.
Use operators in a program
Types of operators.
Understand Operator Precedence.
TYPES OF OPERATORS
a) Arithmetic Operators
There are five arithmetic operators in C.
Operator Purpose
+ Addition
- Subtraction
* Multiplication
/ Division
% Remainder after integer division
Note:
4|P a g e
(iv) Division of one integer quantity by another is known as an integer division. If the
quotient (result of division) has a decimal part, it is truncated.
(v) Dividing a floating point number with another floating point number, or a floating
point number with an integer results to a floating point quotient.
Examples
Suppose a =13, b = 4, valone = 9.5, valtwo = 5.0, letter =’n’.
Note:
(i) letterone and lettertwo are character constants
If one or both operands represent negative values, then the addition, subtraction, multiplication,
and division operators will result in values whose signs are determined by their usual rules of
algebra.
(i) If both operands are floating point types whose precision differ (e.g. a float and a double) the
lower precision operand will be converted to the precision of the other
operand, and the result will be expressed in this higher precision. (Thus if an expression has a
float and a double operand, the result will be a double).
(ii) If one operand is a floating-point type (e.g. float, double or long double) and the other is a
character or integer (including short or long integer), the character or integer will be
converted to the floating point type and the result will be expressed as such.
(iii) If neither operand is a floating-point type but one is long integer, the other will be converted
to long integer and the result is expressed as such. (Thus between an int and a long int, the
long int will be taken).
(iv)If neither operand is a floating type or long int, then both operands will be converted to int (if
necessary) and the result will be int (compare short int and long int)
5|P a g e
From the above, evaluate the following expressions given:
(i) i+f
(ii) i+c
(iii) i + c-‘w’
(iv) ( i + c) - ( 2 * f / 5)
(‘w” has ASCII decimal value of 119)
Note: Whichever type of result an expression evaluates to, a programmer can convert the result
to a different data type if desired. The general syntax of doing this is:
OPERATOR PRECEDENCE
The order of executing the various operations makes a significant difference in the result. C
assigns each operator a precedence level. The rules are;
(i) Multiplication and division have a higher precedence than addition and subtraction, so they
are performed first.
(ii) If operators of equal precedence; (*, /), (+, -) share an operand, they are executed
in the order in which they occur in the statement. For most operators, the order
(associativity) is from left to right with the exception of the assignment ( = ) operator.
6|P a g e
Summary of Operator precedence.
Operator(s) Operation(s) Order of evaluation (precedence)
() Parentheses Evaluated first. If the parentheses are
nested, the expression in the innermost
pair is evaluated first. If there are
several pairs of parentheses “on the
same level” (i.e., not nested), they are
evaluated left to right.
*, /, or % Multiplication Evaluated second. If there are several,
Division they re
Modulus evaluated left to right.
+ or - Addition Evaluated last. If there are several, they
Subtraction are
evaluated left to right.
}
Try changing the order of evaluation by shifting the parenthesis and note the change in the
maximum score.
Exercise
The roots of a quadratic equation ax2 + bx + c = 0 can be evaluated as:
7|P a g e
Example: Converting seconds to minutes and seconds using the % operator
#include<stdio.h >
#define Sec_in_min 60
main()
{
int seco, minute, seco_rem;
printf(“ Converting seconds to minute and seconds \n “) ; printf( “Enter number of seconds
you wish to convert \n “) ; scanf(“% d” , & seco ) ; /* Read in number of seconds */
minute = seco / Sec_in_min; / * Truncate number of seconds */
sec_rem = seco % Sec_in_min;
printf(“% d seconds is % d minutes,% seconds\n “ ,seco,minutes,sec_rem); return
0;
}
If it is a name type such as int, float etc. The operand should be enclosed in parenthesis.
An example of ‘sizeof’ operator
#include <stdio.h>
main()
{
int n;
printf(“n has % d bytes; all ints have % d bytes \n”,
sizeof n, sizeof(int)) ;
return 0;
}
c) The Assignment Operator
The Assignment operator ( = ) is a value assigning operator. There are several other assignment
operators in C. All of them assign the value of an expression to an identifier.
Assignment expressions that make use of the assignment operator (=) take the form;
identifier = expression;
where identifier generally represents a variable, constant or a larger expression.
8|P a g e
Examples of assignment;
a=3;
x=y;
pi = 3.14;
sum = a + b ;
area_circle = pi * radius * radius;
Note
Assuming i is an integer, the expression (i < 0) is evaluated and if it is true, then the result of the
entire conditional expression is zero (0), otherwise, the result will be 100.
e) Unary Operators
These are operators that act on a singe operand to produce a value. The operators may precede
the operand or are after an operand.
Examples
(i) Unary minus e.g. - 700 or –x
(ii) Incrementation operator e.g. c++
(iii) Decrementation operator e.g. f - -
(iv) sizeof operator e.g. sizeof( float)
f) Relational operators
There are four relational operators in C.
< Less than
<= Less than or equal to
9|P a g e
> Greater than
>= Greater than or Equal to
== Equal to
!= Not Equal to
g) Logical operators
&& Logical AND
|| Logical OR
! NOT
The two operators act upon operands that are themselves logical expressions to produce more
complex conditions that are either true or false.
Example
Suppose i is an integer whose value is 7, f is a floating point variable whose value is 5.5 and C is
a character that represents the character ‘w’, then;
Revision Exercises
1. Describe with examples, four relational operators.
2. What is ‘operator precedence’? Give the relative precedence of arithmetic operators.
10 | P a g e
3. Suppose a, b, c are integer variables that have been assigned the values a =8, b = 3 and c = -
5, x, y, z are floating point variables with values x =8.8, y = 3.5, z = -5.2. Further suppose that
c1, c2, c3 are character-type variables assigned the values E, 5 and ? respectively.
11 | P a g e
CHAPTER FOUR: CONTROL STRUCTURES
Chapter objective.
Understand control structures.
Describe different Types of control structures.
Be able to utilize the control structures in a program.
Introduction
Control structures these are programming constructs or elements that are used to alter the follow
of the program execution.
Three structures control program execution:
Sequence
Selection or decision structure
Iteration or looping structure
Basically, program statements are executed in the sequence in which they appear in the program.
In addition, a group of statements in a program may have to be executed repeatedly until some
condition is satisfied. This is known as looping. For example, the following code prints digits
from 1 to 5.
for(digit = 1; digit < = 5; digit++)
printf(“\n %d”, digit)
SELECTION STRUCTURE
a) The if statement
The if statement provides a junction at which the program has to select which path to follow. The
general form is :
if(expression)
statement;
If expression is true (i.e. non zero) , the statement is executed, otherwise it is skipped. Normally
the expression is a relational expression that compares the magnitude of two quantities ( For
example x > y or c = = 6)
Examples
12 | P a g e
(i) if (x<y)
printf(“x is less that y”);
(ii) if (age>18)
Printf(“You are and adult”)
The statement in the if structure can be a single statement or a block (compound statement).
if(expression)
{
block of statements;
}
Example
if(age>18)
{
printf(“You are an adult”);
printf(“You should have the national Identity Card”)
}
b) if - else statement
The if else statement lets the programmer choose between two statements as opposed to the
simple if statement which gives you the choice of executing a statement (possibly compound) or
skipping it.
The general form is:
if (expression)
statement;1
else
statement2;
If expression is true, statement1 is executed. If expression is false, the single statement following
the else (statement2) is executed. The statements can be simple or compound.
Note: Indentation is not required but it is a standard style of programming.
13 | P a g e
Example:
if(x >=0)
{
printf(“let us increment x:\n”);
x++;
}
else
printf(“x < 0 \n”);
Example
if(sale_amount>=10000)
Disc= sal_amt* 0.10; /*ten percent/
else if (sal_amt >= 5000 && sal_amt < 1000 )
printf (“The discount is %f “,sal_amt*0.07 ); /*seven percent */
else if (sal_amt = 3000 && sal_amt < 5000)
{
Disc = sal_amt * 0.05; /* five percent */
printf ( “ The discount is %f “ , Disc ) ;
}
else
printf ( “ The discount is 0”) ;
14 | P a g e
Example
Determining grade category
#include<stdio.h >
#include<string.h >
main()
{
int mks;
char grd [10];
printf (“ Enter the students marks \n”);
scanf( “%d “,&mks ) ;
if ( mks > =75 && mks <=100)
{
strcpy(grd, “Distinction”); /* Copy the string to the grade */
printf(“The grade is %s” , grd);
}
else if( mks > = 60 && mks < 75 )
{
strcpy(grd, “Credit”);
printf(“The grade is % s” , grd );
}
else if(mks>=50 && mks <60)
{
strcpy( mks, “Pass”);
printf(“The grade is % s” , grd );
}
else if (mks >=0 && mks <50)
{
strcpy(grd, “Fail”);
printf (“The grade is % s” , grd) ;
}
else
printf(“The mark is in valid!” );
return 0;
}
15 | P a g e
Example
Demonstrating the ‘switch’ structure
#include<stdio.h>
main()
{
int choice;
printf(“Enter a number of your choice ”);
scanf(“ %d”, &choice);
if (choice >=1 && choice <=9) /* Range of choice values */
switch (choice)
{ /* Begin of switch* /
case 1: /* label 1* /
printf(“\n You typed 1”);
break;
case 2: /* label 2* /
printf(“\n You typed 2”);
break;
case 3: /* label 3* /
printf(“\n You typed 3”);
break;
case 4: /* label 4* /
printf( “ \n You typed 4”);
break;
default:
printf(“There is no match in your choice”);
} /* End of switch*/
else
printf(“Your choice is out of range”);
return (0);
} /* End of main*/
Explanation
The expression in the parenthesis following the switch is evaluated. In the example
above, it has whatever value we entered as our choice.
Then the program scans a list of labels (case 1, case 2,…. case 4) until it finds one that
matches the one that is in parenthesis following the switch statement.
If there is no match, the program moves to the line labeled default, otherwise the program
proceeds to the statements following the switch.
16 | P a g e
The break statement causes the program to break out of the switch and skip to the next
statement after the switch. Without the break statement, every statement from the
matched label to the end of the switch will be processed.
#include<stdio.h>
main()
{
char ch;
printf(“Give me a letter of the alphabet \n”);
printf(“An animal beginning with letter”);
printf (“is displayed \n “);
scanf(“%c”, &ch);
if (ch>=’a’ && ch<=’z’) /*lowercase letters only */
switch (ch)
{ /*begin of switch*/
case `a`:
printf(“Alligator , Australian aquatic animal \n”):
break;
case ‘b’:
printf(“Barbirusa, a wild pig of Malaysia \n”);
break;
17 | P a g e
case ‘c’:
printf(“Coati, baboon like animal \n”);
break;
case ‘d’:
printf(“Desman, aquatic mole-like creature \n”);
break;
default:
printf(“ That is a stumper! \n”)
}
else
printf(“I only recognize lowercase letters.\n”);
return 0;
} /* End of main */
LOOPING
C supports three loop versions:
a) while loop
b) do while loop
c) for loop.
The statement will be executed as long as the expression is true, the statement can be a single or
compound
/* counter.c */
/* Displays the numbers 1 through 9 */
main()
{
int num=0; /* Initialisation */
while (num<10)
{
printf(“%d \n”, digit);
num++;
}
return 0;
18 | P a g e
}
Solution
#include<stdio.h>
main()
{
int n, count = 1;
float fnum, average, sum=0.0;
/* initialise and read in a value of n */
printf(“How many numbers do you want to work
with? “); scanf(“%d”, &n);
/*Read in the number */
while (count<=n)
{
printf(“fnum = “);
scanf(“%f”, &fnum);
sum+=fnum;
count++;
}
(Note that using the while loop, the loop test is carried out at the beginning of each loop
pass).
b) do .. while loop
It is used when the loop condition is executed at the end of each loop pass.
General form:
do
statement;
19 | P a g e
while (expression);
The statement (simple or compound) will be executed repeatedly as long as the value of the
expression is true. (i.e. non zero).
Notice that since the test comes at the end, the loop body (statement) must be executed at least
once.
Rewriting the program that counts from 0 to 9, using the do while loop:
/* counter1.c */
main()
{
int num=0; /* Initialisation */
do
{
printf(“%d \n”, num);
num++;
} while
(num<10);
return 0;
Exercise : Rewrite the program that computes the average of n numbers using the do..while
loop.
c) For loop
This is the most commonly used looping statement in C.
General form:
for (expression1;expression2;expression3)
statement;
where:
expression1 is used to initialize some parameter (initial).
expression2 is a test expression,or just the condition.
expression3 is used to alter the value of the initial parameter either increasing or
decreasing.
Example
for (int i=0 i<5; i++)
printf(i = %d”, i);
20 | P a g e
Output
01234
sum+=x;
}
/* Calculate the average and display the answer */
average = sum/n;
printf(“\n The average is %f \n”, average);
return 0;
}
21 | P a g e
}
Nesting statements
It is possible to embed (place one inside another) control structures, particularly the if and for
statements.
Revision Exercises
1. A retail shop offers discounts to its customers according to the following rules:
Purchase Amount >= Ksh. 10,000 - Give 10% discount on the amount.
Ksh. 5, 000 <= Purchase Amount < Ksh. 10,000 - Give 5% discount on the amount. Ksh. 3,
000 <= Purchase Amount < Ksh. 5,000 - Give 3% discount on the amount.
0 > Purchase Amount < Ksh. 3,000 - Pay full amount.
Write a program that asks for the customer’s purchase amount, then uses if statements to
recommend the appropriate payable amount. The program should cater for negative purchase
amounts and display the payable amount in each case.
2. Using a nested if statement, write a program that prompts the user for a number and then
reports if the number is positive, zero or negative.
3. Write a while loop that will calculate the sum of every fourth integer, beginning with
the integer 3 (that is calculate the sum 3 + 7 +11 + 15 + ...) for all integers that are
less than 30.
22 | P a g e