0% found this document useful (0 votes)
30 views32 pages

ELET104 Module 3 (1) 2

Uploaded by

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

ELET104 Module 3 (1) 2

Uploaded by

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

EEET 104

COMPUTER PROGRAMMING

MODULE 3

SECTION 1: OPERATORS AND STATEMENTS

SECTION 2: CONDITIONAL STATEMENTS

SECTION 3: ITRATIVE STATEMENTS

39 | P a g e
SECTION 1:

OPERATORS
AND
STATEMENTS

40 | P a g e
OPERATORS AND STATEMENTS

Operators

‘C’ language has many operators. Some of these include arithmetic, unary, relational,
logical, bitwise, conditional and assignment operators.
◆ Arithmetic operator

There are five arithmetic operators in ‘C’. They are

Operator Purpose

+ addition
- subtraction
* multiplication
/ division
% remainder after division (modulus operator)

Example 3.1

Suppose a = 10 and b = 3, are two integer variables, then values of following


expressions are

Expression Value

a+b 13
a-b 7
a*b 30
a/b 3
a%b 1

In a / b, both a & b are integer. Therefore integer division will be carried out i.e.,
exponent part will be ignored.

Example 3.2

If r 1 = 12.5 and r 2 = 2.0 are two real variable, then values of the following
expressions are

Expression Values

r1 + r2 14.5
r1 - r2 10.5

41 | P a g e
r 1 * r2 25.0
r1 / r2 6.25

◆ Assignment operator (=)

An assignment operator assigns value of an expression on the right hand side to an


identifier on the left hand side. Assignment expression can be formed as follows:

Identifier = expression;

Example 3.3

a=3 assigns value 3 to a


b=a assigns value of a to b i.e. b = 3
sum =a + b assigns value of a+b to sum i.e. sum = 6
i=k=4 both i & k are assigned a value 4
i = (k = 4) + 3 k is assigned value 4 then i = 4+3 i.e. i = 7

‘C’ contains five additional assignment operators +=,*=, /=, -= and %=.

Example 3.4

Consider the following expressions if a = 5

Expression Meaning Value


a+=5
a- = 5
a = a+5
a = a-5
10
0
important
a* = 5 a=a*5 25
a/=5 a =a/5 1
a%=5 a =a%5 0

◆ Unary Operator

Operators that act upon a single operand are called unary operator. Some unary
operators are – (unary minus), ++ (increment operator), and -- (decrement operator).

42 | P a g e
Example 3.5

If x = 5, y = 3, i = 1, then

Expression Description Example


++i Value of i is first increased e.g. z= x+y-(++i) ⇒z=6 and
then used in expression i=2
--i Value of i is first decreased e.g. z= x+y-(--i) ⇒z=8 and
then used in expression i=0
i++ Value of i will be increased e.g. z= x+y-(i++) ⇒z=7 and
after it is used in expression i=2
i-- Value of i will be decreased e.g. z= x+y-(i--) ⇒z=7 and
after it is used in expression i=0
-5 - is operated on 5 -
Note: In the above example, all expressions are evaluated on the basis of original
values of x, y and i.

◆ Relational & logical operator

There are six relational operators in ‘C’. They are

Operator Meaning

< Less than


<= Less than or equal to
> greater than
>= greater than or equal to
== equal to
!= not equal to

‘C’ also contains three logical operators. They are

Operator Meaning

&& AND

OR
! NOT

43 | P a g e
Suppose x and y are two logical expressions with values 0(false) or 1(true) then
the expression with logical operators (&&, || and !) will be evaluated by the
following table:

&& (AND) || (OR) ! (NOT)


x Y x && y x y x || y x !x
0 0 0 0 0 0
1 0
0 1 0 0 1 1
1 0 0 1 0 1
0 1
1 1 1 1 1 1

^ (XOR)
x Y x && y
0 0 0
0 1 1
1 0 1
1 1 0

Example 3.6

Suppose i = 1, j = 2, k = 3 then the values of following expressions are;


Expression Value
i<j 1 (true)
(i+j)>=k 1(true)
(j+k)>(i+5) 0 (false)
k!= 3 0 (false)
j==2 1 (true)
(i<j)&&(j==2) 1 (true)
(i>j)||(j==2) 1 (true)
! (i>j) 1 (true)

Note: The result of a relational or a logical expressions will always be either 0(false) or 1(true).

44 | P a g e
◆ Bitwise Operator

Bitwise operator permit programmer to access and manipulate of data at bit level.
Various bitwise operator enlisted are
one's complement (~)

bitwise AND (&)

bitwise OR (|)

bitwise XOR (^)

left shift (<<)

right shift (>>)

p q p&q p|q p^q

0 0 0 0 0

0 1 0 1 1

1 1 1 1 0

1 0 0 1 1

Example 3.7

Assume A = 60 and B = 13 in binary format, they will be as follows − vers important


A= 0011 1100 (AND)
B= 0000 1101
-------------------------
A&B = 0000 1100
--------------------------

A= 0011 1100 (OR)


B= 0000 1101
-------------------------
A|B = 0011 1101
--------------------------

45 | P a g e
A= 0011 1100 (XOR)
B= 0000 1101
-------------------------
A^B = 0011 0001
--------------------------

A= 0011 1100 (NOT)


-------------------------
~A = 1100 0011
--------------------------
A= 0011 1100 (SHIFT LEFT)
-------------------------
A<< 2 = 11110000
--------------------------
A= 0011 1100 (SHIFT RIGHT)
-------------------------
A>> 2 = 00001111
--------------------------

These operator can operate on integer and character value but not on float and double.
In bitwise operator the function showbits( ) function is used to display the binary
representation of any integer or character value.

In one's complement all 0 changes to 1 and all 1 changes to 0. In the bitwise OR its
value would obtaining by 0 to 2 bits.

As the bitwise OR operator is used to set on a particular bit in a number. Bitwise AND
the logical AND.

It operate on 2 operands and operands are compared on bit by bit basic. And hence
both the operands are of same type.

◆ Conditional operator (?:) or Ternary operator Veryimportant


Conditional operator is shorthand way of selecting one of two values based on a
condition.

A conditional expression is written in the form

expression1? expression2: expression3;

If expression 1 is true then result is expression 2 otherwise result is expression 3.

46 | P a g e
Example 3.8 Vert important
Suppose a = 5, b= 3 then the value of c in the expressions will be

c= (a < 0) ? 0 : 100 c= 100


c= (a%3 == 2) ? 10 : a+b c= 10
c= (a+b > a*b) ? a+b : a-b c= 2

Example 3.9

void main()
{
int a=10, b=2;
int s= (a>b) ? a : b;
printf(“value is:%d”,s);
}
Output:
Value is:10
◆ Hierarchy of operators in ‘C’

The hierarchy of operator precedence in an expression is as follows:

Precedence Operator category Operations


Unary operator - ++ -- !
Arithmetic Multiply, divide, remainder * / %
Arithmetic add & subtract + -
Relational operator < <= > >=
Equality == !=
Logical and &&
Logical or

Conditional operator ?:
Assignment operator = * = /= +=
- = %-

Note:-
◆ For operators having equal precedence in arithmetic expression, evaluation of
expression is done from left to right.
◆ An expression within parentheses is always evaluated first.

47 | P a g e
Example 3.10
Evaluate the following expression
K = 3/2 * 4 + (3-2) / 8 + 3
= 3/2 * 4 + 1/8 + 3
= 1 * 4 + 0+ 3
=4+0+3
=7

STATEMENTS

A statement causes the computer to carry out some action. There are three types of
statements in ‘C’ language. They are expression or simple statement, compound
statement and control statement.

◆ Expression statement (simple statement): it consists of an expression followed by


a semicolon.

Example 3.11

a = 3; assigns value 3 to a
b = 5; assigns value 5 to b
c = a+b; evaluate a+b & assign 8 to c
++a; value of a increase by 1.
; a null statement, does nothing
◆ Compound statement: It consists of several individual statements enclosed within
a pair of braces { and }. The individual statement may be expression statement,
compound statement or control statement.

Example 3.12

{
pi = 3.141;
radius = 5.0;
area = pi * radius * radius;
}

48 | P a g e
◆ Control statement: It is used to create special program features, such as logical
tests, loops and branches.

Example 3.13

x=1;
while (x <= 10)
{
printf (“%d “,x);
x = x+1;
}

Above example displays values of x from 1 to 10 using while loop.

49 | P a g e
SECTION 2:

CONDITIONAL STATEMENTS

50 | P a g e
CONTROL STATEMENTS

Control Statements are used to create special program features, such as logical tests,
loops and branches. Control statement can be divided into TWO categories:

1. Conditional statements
2. Iterative statements

CONDITIONAL STATEMENTS

Conditional Statements are used to make decisions when two or more alternative
actions are to be computed. There are three types of conditional statements:

i) if-statement
ii) if-else statement
iii) switch-statement

i) The if-statement

The if statement is used to carry out a logical test and then take an action if the
outcome of the test is true

The general form of if-statement is

if (expression)
statement;

Where the expression is logical expression and statement may be simple or


compound.

When if-statement is executed, the logical expression is evaluated and if it returns


a value true then statement is executed otherwise statement is not executed.

51 | P a g e
Flow diagram of if-statement

is True
(expression) statement
?

False

Example 3.14

Following program displays square root of a positive number.

#include <stdio.h>
#include <math.h>

main ( )

{
float num, x;
printf (“\n Enter a number:”);
scanf (“%f”, &num);
if (num>0) {
x = sqrt (num);
printf (“\n Square root is %f”, x);
}
}

Execution of the above program will generate the following input and output (the input is
underlined)

Enter a number: 2.0

Square root is 1.414214

This program reads a real number 2.0 and assign it to num then the logical expression
(num>0) is evaluated which returns a value true. Finally the square root is computed
and output is displayed.

52 | P a g e
ii)The if-else-statement

The if-else statement is used to carry out a logical test and then take one of the two
possible actions, depending on the outcome of the test which may be true or false.

The general form of if is

if (expression)
statement 1;
else
statement 2;
Where the expression is logical expression and statements may be simple or
compound. When if-else statement is evaluated and if expression returns a value true
then statement 1 is executed otherwise statement 2 is executed.

Flow diagram of if-else-statement

False is True
(expression)
?

statement 2 statement 1

Example 3.15

Following program read an integer number and then display a message “number is
even” or “number is odd”.

#include <stdio.h>

main ( )
{
int num;
printf (“\n Enter a number”);
scanf (“%d”, &num);
if (num%2==0)
printf (“\n Number is even”);

53 | P a g e
else
printf (“\n Number is odd”);
}

Execution of the above program will generate the following input and output (the input is
underlined)

Enter a number: 4

Number is even

The above program reads the value of num as 4 and evaluates the expression
(num%2==0) which returns value true then displays “number is even”.

Nested if statement

Statements are said to be nested when one appears within another. The nesting of if-
statement looks like as follows:

i) if (expression 1)
if (expression 2)
statement;

ii) if (expression 1)
statement 1;
else
if (expression 2)
statement 2;
else
if (expression 3)
statement 3;
else
statement 4;

54 | P a g e
Following program uses nesting of if-else statement.

Example 3.16

Following program reads Cum_GPA of a student then compute and display graduation
Grade of the student. Grades will be computed from the following table:

Cum_GPA Grade
3.75 and above Excellent with hounours
3.50 – 3.74 Excellent
3.00 – 3.49 Very good
2.00 – 2.99 Good

#include<stdio.h>
main( )
{

float Cum_GPA;
printf (“Enter the Cumulative GPA of the student:”);
scanf (“%f”, & Cum_GPA);
if(Cum_GPA>=2.00 && Cum_GPA<=2.99)
printf (“Graduation grade = GOOD”);
else
if(Cum_GPA>=3.00 && Cum_GPA<=3.49)
printf (“Graduation grade = VERY GOOD”);
else
if(Cum_GPA>=3.50 && Cum_GPA<=3.74)
printf (“Graduation grade = EXCELLENT”);
else
printf (“Graduation grade = EXCELLENT with HOUNORS”);
}

Execution of the above program will generate the following input and output (the input is
underlined)

Enter the Cumulative GPA of the student: 3.4

Graduation grade = VERY GOOD

55 | P a g e
iii) switch-statement: (Multi-way Branching)

The switch statement is used to evaluate an expression and then take one of the many
possible actions, depending on the value of the expression.

The general form of switch statement is

switch (expression){

case label 1:
statement 1;
break;
case label 2:
statement 2;
break;
case label 3:
statement 3;
break;
.
.
.

default:
statement N;
}
Where expression can be an integer or character expression. Labels can be integer or
character constant. Statements can be simple or compound. The break statement is
used to exit from the switch statement

Example 3.17

Following is a program using switch statement that accepts an integer from 1 to 4 and
displays it in words. (e.g. ONE will be displayed If 1 is entered. Similarly, TWO, THREE
and FOUR will be displayed if 2, 3 and 4 are entered respectively.)

#include<stdio.h>
main ( )
{
int a;
printf (“\n Enter an integer (1 to 4):”);
scanf (“%d”, &a);

switch (a) {

case 1: printf (“\nONE”);


break;

56 | P a g e
case 2: printf (“\nTWO”);
break;
case 3: printf (“\nTHREE”);
break;
case 4: printf (“\nFOUR”);
break;
default: printf (“\nYou didn’t enter a value FROM 1 TO 4”);

}
}

Execution of the above program will generate the following input and output (the input is
underlined)

Enter an integer (1 to 4): 4

FOUR

In the above program, the control is transferred to case 4 based on the input as 4, and it
displays the output as “Entered value is four”. If suppose the values doesn’t match, then
it will execute default.

In switch statement expression can also be a character. Following program uses a


character as expression.

Example 3.18

Following is a program using switch statement that accepts first character of a color
and displays it in words. e.g. ( RED for R, BLUE for B and GREEN for G).

#include <stdio.h>
main ( )
{
char c;
printf (“Enter first character of a color (R, B, G)”);
c = getchar ( );

switch ( c ) {

case ‘R’: printf (“\nRED”);

57 | P a g e
break;
case ‘B’: printf (“\nBLUE”);
break;
case ‘G’: printf (“\nGREEN”);

Execution of the above program will generate the following input and output (the input is
underlined)

Enter first character of a color (R, B, G): B

BLUE

58 | P a g e
SECTION 3:

ITRATIVE STATEMENTS

59 | P a g e
Iterative statement

A group of statements in a program which are executed repeatedly until some logical
condition is satisfied is called an iterative statement. C contains three iterative
statements. They are as follows:

i) do-while statement
ii) while-statement
iii) for-statement

i) The do-while statement

The do-while statement is used to repeatedly execute a sequence of statements


(simple or compound) until some value of an expression is true. The general form of
do-while statement is

do
statement;

while (expression) ;

Where statement can be simple or compound and expression must be logical


expression.

60 | P a g e
Notice the statement will always be executed at least once, since the test of expression
is done at the end of do-while.

Flow diagram for the do-while statement

statement

is True
(expression)
?

False

To next statement

Example 3.19

Following program displays numbers from 1 to 5.

#include <stdio.h>
main ( )
{
int num = 1;
do{
printf (“%d\n”, num);
num=num+1;
}while (num<=5);
}

When the program is executed the output may be as follows:

1
2
3
4
5

When the program is executed, num is initially assigned a value 1. The do-while
displays the current value of num then increases its value by 1, and finally tests that the

61 | P a g e
value of num exceeds 5 or not. The statements within the do-while is executed
repeatedly until the value of num exceeds 5.

ii) The while statement

The while statement is an iterative statement which tests the value of an expression
to be true and then executes a sequence of statement repeatedly as long as the
value of the expression is true. The general form of the statement is

while (expression)
statement;

Where statement can be a simple or compound and expression must be a logical


expression.

Flow diagram for the While statement

is True
(expression) statement
?

False

To next statement

Notice the statement may not be executed even once, since test of the expression is
done at the beginning of while statement.

Example 3.20

Following program displays numbers from 1 to 5.

#include <stdio.h>
main ( )
{
int num = 1;
while (num <=5)
{
printf (“%d\n”, num);
num=num+1;
}
}

62 | P a g e
When the program is executed the output may be as follows:

1
2
3
4
5

When the program is executed, num is initially assigned a value 1. The while statement
tests that whether the value of num exceeds 5 or not. If it is true then it displays the
current value of num and increases it by 1. The while loop is terminated when the value
of num exceeds 5.

Example 3.21

Following program prints the sum of all odd numbers from 1 to 50.

i.e. calculate sum = 1 + 3+ 5 + 7 + ….. + 49

#include <stdio.h>
main ( )
{
int num=1, sum=0;
while (num<= 49)
{
sum = sum + num;
num = num + 2;
}
printf (“ Sum = %d”, sum);
}

When the program is executed the output may be as follows:

Sum = 625

The above program initially assigns a value 1 to num. The while statement adds the value
of num to sum and then increases num by 2. This process continues until value of num
becomes equal to 49.

63 | P a g e
iii) The for Statement

The for Statement is used to repeatedly execute a statement (simple or compound)


until value of a logical expression is true.

The general form of the for statement is

for (expression 1; expression 2; expression 3)


statement;

Where expression 1 - initialize the index (assignment expression)


expression 2 - condition to be satisfied for the loop to continue execution
(logical expression)
expression 3 - changes the value of index of expression1
(unary or assignment expression)

for statement is equivalent to the following:

expression 1;
while (expression 2) {
statement;
expression 3;
}

The looping action will continue as long as the value of expression 2 is true.

Flow diagram of for-loop

expression 1

expression 3

is True
expression 2 statement
?

False

64 | P a g e
Example 3.22

Following program displays numbers from 1 to 5.

#include <stdio.h>
main ( )
{
int num;

for (num =1; num <=5; ++ num)

printf (“%d\n”, num);


}

When the program is executed the output may be as follows:

1
2
3
4
5

In the for statement of the above program, 1st expression (num=1) assigns initial value
of 1 to num, the 2nd expression (num <=5) tests the condition that whether value of num
exceeds 5 or not and 3rd expression (++num) increases value of num by 1. Thus it
prints values from 1 to 5.

Nesting of for-statement

The statements are said to be nested if one appears within another. The nesting of for-
statement is as follows:

for (exp1; exp2; exp3)


{
for (exp4; exp5; exp6)
{
statement 1;
statement 2;
.
.
.
}
}

65 | P a g e
In this case two for-statements are nested to each other. An Example using nesting of
for statement is given below:

Example 3.23

Following program displays the output as follows.

*****
*****
*****

# include <stdio.h>
main ()

{
int i, j;

for (i = 0; i <=2; ++i)


{
for (j = 0; j <=4; ++j)
printf ("*");
printf ("\n");
}
}

When the program is executed the output may be as follows:

*****
*****
*****

66 | P a g e
REVIEW QUESTIONS

1. Suppose a, b and c are integer variables that have been assigned the values a = 8,
b = 3 and c = -5. Determine the value of each of the following arithmetic
expressions.

(a) a+b+c
(b) 2 * b + 3 * (a – c)
(c) a/b
(d) a%b
(e) a/c
(f) a * (c % b)

2. Suppose x, y and z are floating-point variables that have been assigned the
values x = 8.88, y = 3.5 and z = -5.2. Determine the value of each of the
following arithmetic expressions.

(a) x/y
(b) x*y
(c) 2*x/3*y
3. A C program contains the following declarations and initial assignments:

int I = 8, j = 5;
float x = 0.005, y = -0.01;

Determine the value of each of the following expressions. Use the values initially
assigned to the variables for each expression.

(a) (3 * i – 2 * j) % (2 * 3 – 1)
(b) (i – 3 * j) % (i + 2 * 2) / (x – y)
(c) y––
(d) x>=0
(e) y == 99
(f) 5 * (i + j) > x
(g) ! (i < = j)
(h) (i > 0) && (j < 5)
(i) (x > y) && (i > 0) || (j < 5)
(j) (x > y) && (I > 0) && (j < 5)

4. A C program contains the following declarations and initial assignments:

67 | P a g e
int i = 8, j = 5, k;
float x = 0.005, y = -0.01, z;

Determine the value of each of the following assignment expressions. Use the
values originally assigned to the variables for each expression.

(a) k = (i + j)
(b) z=i/j
(c) k=i%j
(d) z=k=x
(e) i+=2
(f) x*=2
(g) i%=j
(h) k = (j == 5) ? i : j
(i) z = (y >= 0) ? y : 0
(j) i - = (j > 0) ? j : 0

5. Identify whether each of the following statements is an expression statement, a


compound statement or a control statement.

(a) a * (b + c);

(b) while (a < 100) {


d = a * (b + c);
++a;
}

(c) if (x > 0)
y = 2.0;
else
y = 3.0;
(d) {
++x;
if (x > 0)
y = 2.0;
else
y = 3.0;
printf (“%f”, y);

6. Write an iterative statement that will calculate the sum of every third integer,
beginning with i = 2 (i.e., calculate the sum 2+5+8+11+…) for all values of i that
are less than 100. Write your program in three different ways.

68 | P a g e
a) Using a while statement
b) Using a do-while statement
c) Using a for statement

7. Write a switch statement that accepts a number for the integer variable x and will
display one of the following corresponding messages:

a) VOLTS, if 1 is entered
b) OHMS, if 2 is entered
c) AMPERES, if 3 is entered
d) ERROR, if any other value is entered

8. Write a switch statement that will examine the value of a character type variable
called color and print one of the following messages, depending on the character
assigned to color.

a) RED, if R is assigned to color


b) GREEN, if G is assigned to color
c) BLUE, if B is assigned to color
d) BLACK, if color is assigned any other character

9. Describe the output that will be generated by each of the following C programs.

a.

#include <stdio.h>
main ( )
{
int i = 10, x = 0;

if (i %5==0) {
x + = i;
printf (“%d”, x);
}
++i;
printf (“\ni=%d”, i);
}

69 | P a g e
b.

#include <stdio.h>
main ( )
{
int i = 0, x = 5;

do {
printf (“%d”, ++x);

++i;
} while (i < 10);
printf (“\ni=%d”, i);
}

10. Write a C program to input an integer number then compute and display sum of
digits of the number.

70 | P a g e

You might also like