0% found this document useful (0 votes)
2 views22 pages

C Operators and Control Structures

The document provides a comprehensive overview of operators in the C programming language, categorizing them into arithmetic, assignment, comparison, logical, and bitwise operators. It explains the usage and examples of each operator type, along with operator precedence and the concept of operands. Additionally, it covers the sizeof operator, conditional operators, unary operators, and relational operators, illustrating their application through various examples.

Uploaded by

Marley Joxef
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views22 pages

C Operators and Control Structures

The document provides a comprehensive overview of operators in the C programming language, categorizing them into arithmetic, assignment, comparison, logical, and bitwise operators. It explains the usage and examples of each operator type, along with operator precedence and the concept of operands. Additionally, it covers the sizeof operator, conditional operators, unary operators, and relational operators, illustrating their application through various examples.

Uploaded by

Marley Joxef
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

C OPERATORS

Operators are used to perform operations on variables and values.


In the example below, we use the + operator to add together two values:
Example
int myNum = 100 + 50;
C divides the operators into the following groups:
 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Bitwise operators

i. Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.

Operator Name Description Example

+ Addition Adds together two values x+y

- Subtraction Subtracts one value from another x-y

* Multiplication Multiplies two values x*y

/ Division Divides one value by another x/y

% Modulus Returns the division remainder x%y

++ Increment Increases the value of a variable by 1 ++x

-- Decrement Decreases the value of a variable by 1 --x

ii. Assignment Operators


Assignment operators are used to assign values to variables.
In the example below, we use the assignment operator (=) to assign the value 10 to a variable
called x:
Example
int x = 10;
The addition assignment operator (+=) adds a value to a variable:
Example

1|P a g e
int x = 10;
x += 5;
A list of all assignment operators:

Operator Example Same As

= 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

^= x ^= 3 x=x^3

>>= x >>= 3 x = x >> 3

<<= x <<= 3 x = x << 3

iii. Comparison Operators


Comparison operators are used to compare two values.
Note: The return value of a comparison is either true (1) or false (0).
In the following example, we use the greater than operator (>) to find out if 5 is greater than 3:
Example
int x = 5;
int y = 3;
printf("%d", x > y); // returns 1 (true) because 5 is greater than 3
A list of all comparison operators:

Operator Name Example

== Equal to x == y

!= Not equal x != y

2|P a g e
> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

iv. Logical Operators


Logical operators are used to determine the logic between variables or values:

Operator Name Description Example

&& Logical and Returns true if both statements are true x < 5 && x < 10

|| Logical or Returns true if one of the statements is true x < 5 || x < 4

! 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.

OPERATORS AND OPERANDS


An operator is a component of any expression that joins individual constants, variables, array
elements and function references.
An operand is a data item that is acted upon by an operator. Some operators act upon two
operands (binary operators) while others act upon only one operand (unary operators).
An operand can be a constant value, a variable name or a symbolic constant.
Note: An expression is a combination of operators and operands.
Examples
(i) x + y ; x, y are operands, + is an addition operator.
(ii) 3 * 5; 3, 5 are constant operands, * is a multiplication operator.
(iii)x % 2.5; x, 5 are operands, % is a modulus (remainder) operator.
(iv) sizeof (int); sizeof is an operator (unary), int is an operand.

TYPES OF OPERATORS
a) Arithmetic Operators
There are five arithmetic operators in C.
Operator Purpose
+ Addition
- Subtraction
* Multiplication
/ Division
% Remainder after integer division
Note:

(i) There exists no exponential operators in C.


(ii) The operands acted upon by arithmetic operators must represent numeric values,
that is operands may be integers, floating point quantities or characters (since
character constants represent integer values).
(iii) The % (remainder operator) requires that both operands be integers. Thus;
 5 % 3 the answer is 2.
 int x = 8; int y = 6 ; x %
y are valid while;
 8.5 % 2.0 and float p = 6.3, int w = 7 ; 5 %p , p % w are invalid.

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’.

Compute the result of the following expressions.


 a+b  letter
 valone * valtwo2  a/b
 a-b  letterone + lettertwo +5
 valone / valtwo  a%b
 a*b  letterone + lettertwo +’9’

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.

Examples of floating point arithmetic operators


r1 = -0.66, r2 = 4.50 (operands with different signs)
r1 + r2 = 3.84
r1 - r2 = -5.16
r1 * r2 = -2.97
r1 / r2 = -0.1466667
Note:

(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 =7, f = 5.5, c = ’w’. State the type of the result.

(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:

(data type) expression.


The data type must be enclosed in parenthesis (). For example the expression (i + f) above
evaluates to 12.5. To convert this to an integer, it will be necessary to write
(int) (i + f).

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.

Consider the statement;


butter = 25.0 + 60.0 * n / SCALE;
Where n = 6.0 and SCALE = 2.0.
The order of operations is as follows;

First: 60.0 * n = 360.0


(Since * and / are first before + but * and / share the operand n with * first)
Second: 360.0 / SCALE = 180
(Division follows)
Third: 25.0 + 180 = 205.0 (Result)

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.

Example: Use of operators and their precedence


/* Program to demonstrate use of operators and their precedence */
include<stdio.h >
main()
{
int score,max;
score = 90;
max = score - (9*2) + 3 * (8+6) + (4+2);
printf (“The maximum value is = %d \ n” , max);
return 0;

}
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:

x1 = √(-b + -(b2 - 4ac))/2a


x2 = √ (-b + -(b2 - 4ac))/2a
where a, b ,c are double type variables and b2 = b * b , 4ac = 4 * a * c, 2a = 2 * a.
Write a program that calculates the two roots x1 x2 with double precision, and displays the roots
on the screen.

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;
}

b) The sizeof operator


sizeof returns the size in bytes, of its operand. The operand can be a data type e.g.
sizeof (int), or a specific data object e.g. sizeof n.

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

(i) You cannot assign a variable to a constant such as 3 = a ;


(ii) The assignment operator = and equality operator (= =) are distinctively different. The
= operator assigns a value to an identifier. The equality operator (= =) tests whether
two expressions have the same value.
(iii) Multiple assignments are possible e.g. a =b = 5 ; assigns the integer value 5 to both a
and b.
(iv) Assignment can be combined with +, -, /, *, and %

d) The Conditional Operator


Conditional tests can be carried out with the conditional operator (?). A conditional expression
takes the form:
expression1 ? expression2 : expression3 and implies;
evaluate expression1. If expression1 evaluates to true ( value is 1 or non zero) then evaluate
expression 2, otherwise (i.e. if expression 1 is false or zero ) , evaluate expression3.

Consider the statement (i < 0) ? 0 :100

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

The above six operators form logical expressions.


A logical expression represents conditions that are either true (represented by integer 1) or false
(represented by 0).
Example
Consider a, b, c to be integers with values 1, 2,3 respectively. Note their results with relational
operators below.
Expression Result
a<b True
(a+ b) > = c True
(b + c) > (a+5) False
c:=3 False
b==2 True

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;

(i > = = 6 ) && ( C = = ‘w’ ) is (true)


( C’ > = 6 ) || (C = 119 ) is (true)
(f < 11 ) && (i > 100) is (false)
(C! = ‘ p’) || ((i + f) < = 10 ) is (true)

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.

Determine the value of each of the following expressions:


(i) a/b
(ii) 2 * b + 3 * (a – c)
(iii) (a * c) % b
(iv) (x / y) + z
(v) x%y
(vi) 2 * x / (3 * y)
(vii) c1 / c3
(viii) (c1 / c2) * c3

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.

This is selection. For example:


if (score >= 50)
printf(“Pass”);
else
printf(“Fail”);

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 the statement is a block (of statements), it must be marked off by braces.

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”);

Multiple Choice: else if


Used when two or more choices have to be made.
The general form is:
if (expression)
statement;
else if (expression)
statement;
else if (expression)
statement;
else
statement;

(Braces still apply for block statements)

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;
}

c) The ‘switch’ and ‘break’ statements


The switch - break statements can be used in place of the if - else statements when there are
several choices to be made.

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.

The structure of a switch is as follows:


switch (integer expression)
{
case constant 1:
statement; optional
case constant 2:
statement; optional
…………
default: (optional)
statement; (optional)
}
Note:
(i) The switch labels (case labels) must be type int (including char) constants or constant
expression.
(ii) You cannot use a variable for an expression for a label expression.
(iii) The expressions in the parenthesis should be one with an integer value.
(again including type char)

Example:Demonstrating the switch structure.

#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.

a) The ‘while’ loop


The while statement is used to carry out looping instructions where a group of instructions
executed repeatedly until some conditions are satisfied.
General form:
while (expression)
statement;

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
}

Example : Calculating the average of n numbers using a ‘while’ loop

Solution

/* To add numbers and compute the average */

#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++;
}

/* Calculate the average and display the answer


*/ average = sum/n;
printf(“\n The average is %f \n”, average);
return 0;

(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 */

/* Displays the digits 1 through 9 */

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

Example: Averaging a set of numbers using a ‘for’


loop /* average.c */

/* To add numbers and compute the average */


#include<stdio.h>
main()
{
int n, count;
float x, average, sum=0.0;.
/* initialise and read in a value of n */
printf(“How many numbers? “);
scanf(“%d”, &n);
/*Read in the number */
for(count=1;count<=n;count++)
{
printf(“x = “);
scanf(“%f”, &x);

sum+=x;
}
/* Calculate the average and display the answer */
average = sum/n;
printf(“\n The average is %f \n”, average);
return 0;
}

Example: Table of cubes

/ Using a loop to make a table of cubes */


#include<stdio.h>
main()
{
int number;
printf(“n n cubed “);
for(num=1; num<=6;num++)
printf(“%5d %5d \n”, num, num*num*num);
return 0;

21 | P a g e
}

Also note the following points about the for structure.


 You can count down using the decrement operator
 You can count by any number you wish; two’s threes, etc.
 You can test some condition other than the number of operators.
 A quantity can increase geometrically instead of arithmetically.

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

You might also like