0% found this document useful (0 votes)
15 views33 pages

1 ICS 2175 Lecture 7 Control Structures

Uploaded by

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

1 ICS 2175 Lecture 7 Control Structures

Uploaded by

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

Programming

Methodology

ICS 2175

Lesson 4- Control Structures


 Represent the forms by which statements in a
program are executed.
 The kinds of control statements supported by
different languages vary, but can be
categorized by their effect:
◦ Continuation at a different statement (jump),
◦ Executing a set of statements only if some condition
is met (choice),
◦ Executing a set of statements zero or more times,
until some condition is met (loop),
◦ Executing a set of distant statements, after which the
flow of control may possibly return (subroutines, co-
routines and continuations),
◦ Stopping the program, preventing any further
execution (halt)

11/18/24
 Basically, program statements are executed
in the sequence in which they appear in the
program
 However, we can control the execution of C
program by using any control mechanism by
which we can compare things and come to a
decision.
 This involves using some operations called
Relational Operators, logical operators,
conditional statements called if-else and
loops..
 These relational operators compare two
values and return true or false after
comparison.

Control Structures
11/18/24
 These may determine which actions to take
(subsequent statements to be executed)
depending on the outcome of the test
 We can use the relational operators to
compare values of any basic data type, so all
we need is to modify the behavior of the
program.
 A group of statements in a program may also
have to be executed repeatedly until some
condition is satisfied. This is called looping

Control Structures
11/18/24
< Less than
> Greater than
== Equal to
<= Less than or equal to
>= Greater than or equal to
!= Not equal to

Conditional Operators
11/18/24
Selection
11/18/24
 The decision control structure in C can
be implemented using;
1. The if statement
2. The if - else statement
3. Multiple choice: else if statement
4. The switch and break statements
5. The continue statement
6. The goto statement

Selection
11/18/24
 The if statement by itself provides a junction
at which the program has to select which
path to follow. The general form is;
if(expression)
statement;
 If the 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 (e.g. x > y or c==6)
 Examples:

The If Statement
11/18/24
(i) If (x < y)
printf (“x is less than y”);
(ii) if (salary > 500)
tax-amount = salary * 1.5;
(iii) if (balance < 1000 || status = ‘R’)
printf(“Balance = %f”, balance);
 The statement in the if structure can be a single
statement or a block (compound statement). If it is
a block it must be marked off by braces.
 Example:
if(salary>5000)
{
tax_amt = salary * 1.5;
printf(“Tax charged is %f”, tax_amt);
}

The If Statement
11/18/24
 Allows the programmer to choose between two
statements as opposed to the simple if
statement that gives the choice of executing a
statement or skipping it.
 The general form is;
if (expression)
statement1;
else
statement2;
 If the expression is true, statement1 is executed,
if false, the single statement following the else
(statement2) is executed. The statements can
be simple or compound
 N/B: the indentation is not compulsory but is a
standard style of programming

The If-else Statement


11/18/24
Example
if (x >= 0)
{
printf(“Let us increment x:\n”);
x++;
}
else
printf(“x < 0 \n”);

The If-else Statement


11/18/24
Used when more than two choice have to
be made
The general form is
if (expression)
statement;
else if (expression)
statement;
else if (expression)
statement;
else
statement;
Example

Multiple Choice: else if


11/18/24
if (sal_amt>=10000)
Disc = sal_amt * 0.10; /*ten
percent*/
else if (sal_amt >= 5000 && sal_amt <10000)
printf (“The discount is %f”, sal_amt * 0.07);
else if (sal_amt >= 3000 && sal_amt <5000)
{
Disc = sal_amt * 0.05; /*five percent*/
printf(“The amount is %f”, Disc);
}
else
printf(“The discount is 0”);

Multiple Choice: else if


11/18/24
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 of
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
The ‘Switch’ Structure
the one with the integer value (again
including the char)
11/18/24
 Can be used in the place of the else-if
statements when there are several
choices to be made.
 Example
#include<stdio.h>
{
int choice;
printf(“Enter a number of your choice”);
scanf(“%d”, choice);
if (choice >=1 && choice <=9 /*Range of choice
values*/
switch (choice)
{
case 1:
printf (“You typed 1”);
break;

The ‘Switch’ and ‘break’


statements
11/18/24
case 2:
printf (“You typed 2”);
break;
case 3:
printf (“You typed 3”);
break;
case 4:
printf (“You typed 4”);
break;
default:
printf(“There is no match in your choice”);
}
else
printf(“Your choice is out of range”);
return (0);
}

‘Switch’ and ‘break’ Example


11/18/24
 The expression in the parenthesis following the
switch is evaluated. In the example 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 it proceeds to the
statements following the switch.
 The break statement causes the program to
break out of the switch and skip to the next
statement after the switch. Without the break,
every statement from the matched label to the
end of the switch will be processed.
 The structure of a switch is as follows;

Explanation
11/18/24
#include<stdio.h>
main()
{
int m1,m2,m3,m4,m5;
float total, average;
char grade;
printf("Enter marks for Database systems, computer Maths,
chemistry, biology, and physics\n");
printf("Press enter after each mark\n");
scanf("\n%d%d%d%d%d",&m1, &m2,&m3,&m4,&m5);
total =(float)(m1+m2+m3+m4+m5);
average=(float)(m1+m2+m3+m4+m5)/5;
printf("The total marks for the student is %.2f\n",total);
printf("The average mark is %.2f\n",average);
//Computation of grades
if (average>70)
grade='A';
else if (average>60)
grade='B';
else if (average>50)
grade='C';
else if (average>40)
grade='D';
else
grade='F';
printf("The student's grade is %c\n", grade);
}

11/18/24
#include<stdio.h>
main()
{
int m1,m2,m3,m4,m5;
float total, avg;
char grade;
int av;
printf("Enter the marks for Database systems->");
scanf("%d",&m1);
printf("Enter the marks for Computer Mathematics->");
scanf("%d",&m2);
printf("Enter the marks for Networking Essentials->");
scanf("%d",&m3);
printf("Enter the marks for Principles of Computer support and Maintenance->");
scanf("%d",&m4);
printf("Enter the marks for Programming Methodology->");
scanf("%d",&m5);
total =(float)(m1+m2+m3+m4+m5);
avg=(float)(m1+m2+m3+m4+m5)/5;
printf("The total marks for the student is %.2f\n",total);
printf("The average mark is %.2f\n",avg);
av=(avg/10);
switch (av)
case 5:
{
case 0: case 1: case 2: case 3: grade='C';
grade='F'; break;
break; case 6:
case 4: grade='B';
grade='D'; break;
break; default:
} grade='A';
printf("The student's grade is %c\n", grade); break;
return 0;
} 11/18/24
Like the break statement, this statement
is a jump that interrupts the flow of a
program. It is used in loops to cause the
rest of an iteration to be skipped and the
next iteration to be started
If a break is used in a loop it quits the
entire loop

The Continue Statement


11/18/24
This takes the form goto labelname
Example;
goto part2;
part2: printf (“Programming in C”);

In C the if construct can be used in place


of the goto statement
Alternative 1 Alternative 1
If (a > 14) if (a > 14)
Goto a; sheds = 3;
Sheds = 2; else
Goto b; sheds = 2;
a: sheds = 3; k = 2 * sheds;
b: k = 2 * sheds;

The ‘goto’ Statement


11/18/24
 These are three methods by way of
which we can repeat a part of a program
in C programming
1. Using a while loop
2. Using a do-while loop
3. Using a for loop

Repetition/ Iteration/ Looping


11/18/24
 Used to carry out looping instructions
where a group of instructions are executed
repeatedly until some conditions are
satisfied
 The general form is
While (expression)
statement;
 The statement will be executed as long as
the expression is true. The statement can
be simple or compound
 Example

The While Loop


11/18/24
/*counter.c*/
/* Displays the digits 1 to 9*/
main()
{
int digit = 0; /*initialization*/
while (digit<=9)
{
printf(“%d \n”, digit);
digit++;
}
return 0;
}
N/B: In the while loop, the loop test is carried
out at the beginning of each loop pass
The while loop
11/18/24
 Calculating the Average of n numbers
using a while loop
 Algorithm
(i) Initialize an integer count variable to 1. this will be
used as a loop counter
(ii) Assign a value of 0 to the floating-point sum
(iii) Read in the variable for n (number of values)
(iv) Carry out the following repeatedly (as long as the
count is less or equal to n)
(v) Read in a number, e.g. x
(vi) Add the value of x to current value of sum
(vii) Increase the value of count by 1
(viii) Calculate the average: divide the value of sum by n
(ix) Write out the calculated value of average

while loop- Algorithm


11/18/24
/*to add numbers and compute the average*/
#include<stdio.h>
Main()
{
int n, count = 1;
float x, average, sum = 0.0;
/*initialize and read in a value of n*/
printf(“How many numbers? ”);
scanf(“%d”, &n);
/*Read in the number*/
while (count<=n)
{
printf(“x = ”);
scanf(“%f”, &x);
sum+=x;
count++;
}
/* Calculate the average and display the answer*/
average = sum/n;
Solution printf(“\n The average is %f \n”, average);
return 0;
} 11/18/24
Used when the loop condition is executed
at the end of each loop pass
The general form is;
do
statement;
while (expression);
The statement (simple or compound) is
executed repeatedly as long as the value of
the expression is true
Since the text comes at the end, the loop
body (statement) must be executed at
least once

The ‘do.. While’ loop


11/18/24
 Rewriting the program that counts from 0
to 9 using the do while loop
/*counter1.c*/
/* Displays the digits 1 to 9*/
main()
{
int digit = 0; /*initialization*/
do
{
printf(“%d \n”, digit);
digit++;
} while (digit < = 9);
return 0;
}

The ‘do.. While’ loop -


Example
11/18/24
Rewritethe program that computes the
average of n numbers using the do while
loop

Exercise
11/18/24
 The most common statement used for looping in C
 The general form is;
for (expression1; expression2; expression3)
statement;
 Expression1 is used to initialize a parameter
(called an index). This index controls the loop
action. It is usually an assignment operator
 expression2 is a test expression, comparing the
initialized index in expression1 to some maximum
or minimum value
 Expression3 is used to alter the value of the
parameter index initially assigned by expression
and is usually a unary expression or assignment
operator

The ‘for’ Loop


11/18/24
for (int k = 0; k<= 5; k++)
printf(k= %d \n”, k);
 Counting 0 to 9 using a ‘for’ loop
/*counter2.c*/
/* Displays the digits 1 to 9*/
main()
{
int digit;
for (digit = 0; digit<= 9; digit++)
printf(“%d \n”, digit);
return 0;
}

The ‘for’ Loop - Example


11/18/24
A program to display numbers in ascending
and descending order;
#include<stdio.h>
void main()
{
int i = 0;
printf("Numbers in ascending order");
for (;++i<=10;)
printf("%3d",i);
printf("\n\n");

printf("Numbers in descending order");


for (;i-->1;)
printf("%3d",i);
The ‘for’ Loop – Example 2
printf("\n\n");
return 0;
} 11/18/24
A program to display numbers in
ascending and descending order;
#include<stdio.h>
void main()
{
int i;
printf("Numbers in ascending order");
for (i=1;i<=10;i++)
printf("%3d",i);
printf("\n\n");

printf("Numbers in descending order");

for (i=10;i>=1;i--)
printf("%3d",i);
printf("\n\n");
The ‘for’ Loop – Example 2
return 0;
}
11/18/24

You might also like