Lecture III

You might also like

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 49

Lecture III

Structured Program in C
Introduction

Before writing a program to solve a particular problem, it’s essential

to have a thorough understanding of the problem and a carefully


planned approach to solving the problem. The next two chapters
discuss techniques that facilitate the development of structured
computer programs.
Algorithms

 The solution to any computing problem involves executing a series


of actions in a specific order.

A procedure for solving a problem in terms of

 1. the actions to be executed, and

 2. the order in which these actions are to be executed

is called an algorithm. The following example demonstrates that


correctly specifying the order in which the actions are to be
executed is important.
Example 1

 Consider an algorithm called “Wake up algorithm” followed by one


junior executive for getting out of bed and going to work:

 (1) Get out of bed,


 (2) take off pajamas,
 (3) take a shower,
 (4) get dressed,
 (5) eat breakfast,
 (6) drive to work. This routine gets the executive to work well
prepared to make critical decision
Example 2

 Suppose that the same steps are performed in a slightly different


order:

 (1) Get out of bed,


 (2) take off pajamas,
 (3) get dressed,
 (4) take a shower,
 (5) eat breakfast,
 (6) drive to work. In this case, our junior executive shows up for work
soaking wet.
Pseudocode

 Pseudocode is an artificial and informal language that helps you


develop algorithms. The pseudocode we present here is particularly
useful for developing algorithms that will be converted to structured
C programs. Pseudocode is similar to everyday English; it’s
convenient and user friendly although it’s not an actual computer
programming language.
 Pseudocode programs are not executed on computers. Rather, they
merely help you “think out” a program before attempting to write it in
a programming language such as C. In this chapter, we give several
examples of how pseudocode may be used effectively in developing
structured C programs.
The Decision Control Structure

 Normally, statements in a program are executed one after the other


in the order in which they’re written. This is called sequential
execution. There are various C statements, we’ll soon discuss other
statements that will enable you to specify the next statement to be
executed other than the one in sequence. This is called transfer of
control.
Decision control Statement

 In decision control statements (if-else and nested if), group of


statements are executed when condition is true. If condition is
false, then else part statements are executed.

 There are 3 types of decision making control statements in C


language. They are,

9
 if statements
 if else statements
 nested if statements

10
The if Selection Statement
 Selection structures are used to choose among alternative courses
of action. For example, suppose the passing grade on an exam is
60. The pseudocode statement
If student’s grade is greater than or equal to 60
Print “Passed”
 determines if the condition “student’s grade is greater
than or equal to 60” is true or false.If the condition is
true, then “Passed” is printed, and the next pseudocode
statement in order is “performed” (remember that
pseudocode is not a real programming language). If
the condition is false, the printing is ignored
the if statement

12
Example

int main()
{
int m=40,
int n=40;
if (m == n)
{
printf("m and n are equal");
}
}

13
The if else statement

14
Example

#include <stdio.h>
int main()
{
int m=40,n=20;
if (m == n)
{
printf("m and n are equal");
}
else
{
printf("m and n are not equal");
}
}
15
The nested if

16
Example

#include <stdio.h>
int main()
{
int m=40,n=20;
if (m>n) {
printf("m is greater than n");
}
else if(m<n) {
printf("m is less than n");
}
else {
printf("m is equal to n");
}}

17
Exercise 1: what would be the output of the
following programs

(a) main( )
{
int x = 10, y = 20 ;
if ( x == y ) ;
printf ( "\n%d %d", x, y ) ;
}

(b) main( )
{
int x = 3, y = 5 ;
if ( x == 3 )
printf ( "\n%d", x ) ;
else ;
printf ( "\n%d", y ) ;
}
18
(c) main( )
{
int x = 3 ;
float y = 3.0 ;
if ( x == y )
printf ( "\nx and y are equal" ) ;
else
printf ( "\nx and y are not equal" ) ;
}

19
 (d)main( )
{
int i = 65 ;
char j = ‘A’ ;
if ( i == j )
printf ( “C is WOW” ) ;
else
printf( "C is a headache" ) ;
}

20
Exercise 2

 Any integer is input through the keyboard. Write a program to find


out whether it is an odd number or even number.

21
Exercise 3

 Write a program in C that uses double variables to compute the


area of a circle. The user will enter the radius and pi from the
keyboard.

22
Exercise 4

 If the ages of Mr.X, Mr.Y and Mr.Z are input through the keyboard,
write a program to determine the youngest of the three.

23
Exercise 5

 The marks obtained by a student in 5 different


subjects are input through the keyboard. The student gets a
division as per the following rules:
Percentage above or equal to 60 - First division
Percentage between 50 and 59 - Second division
Percentage between 40 and 49 - Third division
Percentage less than 40 – Fail
 Note: use your know of if-else condition

24
Exercise 6

 While purchasing certain items, a discount of 10% is


offered if the quantity purchased is more than 1000. If
quantity and price per item are input through the
keyboard, write a program to calculate the total
expenses.
Execise 7

 The current year and the year in which the employee joined the
organization are entered through the keyboard. If the number of
years for which the employee has served the organization is greater
than 3 then a bonus of $2500 is given to the employee. If the years
of service are not greater than 3, then the program should do
nothing.
Exercise 8

A- If cost price and selling price of an item is input through the


keyboard, write a program to determine whether the seller has made
profit or incurred loss. Also determine how much profit he made or
loss he incurred.

B - Any integer is input through the keyboard. Write a program to find


out whether it is an odd number or even number.
C- Any year is input through the keyboard. Write a program to
determine whether the year is a leap year or not.

Note: A leap year has 366 days, as opposed to a common year, which
has 365. Nearly every 4 years is a Leap Year, and we add a Leap
Day, an extra – or intercalary – day on February 29
Loops

The versatility of the computer lies in its ability to perform


a set of instructions repeatedly. This involves repeating
some portion of the program either a specified number of
times or until a particular condition is being satisfied.This
repetitive operation is done through a loop control
instruction.
There are three methods by way of which
we can repeat a part of a program

 (a) Using a for loop


 (b) Using a while loop
 (c) Using a do-while loop
The while loop

 A repetition statement allows you to specify that an


action is to be repeated while some condition remains
true.

 The pseudocode statement


While there are more items on my shopping list
Purchase next item and cross it off my list
Example to print numbers 1 to 10

int i=1;
while(i<=10)
{
printf("%d\n",i);
i++;
}
Formulating Algorithms: Counter-
Controlled Repetition

 A class of ten students took a quiz. The grades


(integers in the range 0 to 100) for this quiz are
available to you. Determine the class average
on the quiz.
Understanding The Problem

 The class average is equal to the sum of the grades


divided by the number of students. The algorithm for
solving this problem on a computer must input each of
the grades, perform the averaging calculation, and print
the result.
Pseudocode to solve the problem
 1 Set total to zero
 2 Set grade counter to one
 3While grade counter is less than or equal to ten
 4 Input the next grade
 5 Add the grade into the total
 6 Add one to the grade counter
 7 Set the class average to the total divided by
ten
 8 Print the class average
Code in C language

total=0; // intialize total


counter=1; // initialize counter
while(counter<=10) // loop 10 times
{
printf("Enter Grade:"); //prompt for input
scanf("%d",&grade); // read grades from user
total=total+grade; // add grade to total
counter=counter+1; // increment counter
}
average=total/10; // integer division
printf("class average is %d\n",average); // display the average
The For loop

 The general form of for statement is as under:


for(initialise counter; test counter; increment counter)
{
do this;
and this;
a this;
}
Structure of for loop
Example

 main()
{
inti;
for(i=1;i<=10;i++)
printf(“%d\n”,i);
}
All the following increment can be used:
i=i+1
i++
i+=1
Do- while loop

do
statement
while ( condition );
Example

main()
{
int counter=1;
do{
printf(“%d”,counter);
} while(++counter<=10);

Note: The code is tested at the end


The Break statement

 We often come across situations where we want to jump out of a


loop instantly, without waiting to get back to the conditional test. The
keyword break allows us to do this. When break is encountered
inside any loop, control automatically passes to the first statement
after the loop. A break is usually associated with an if. As an
example, let’s consider the following example.
Example Break statement

for(x=1;x<=10;x++)
{

if(i==5)
{
break;
}
printf ("%d\n",x);

}
The continue Statement

 In some programming situations we want to take the control to the


beginning of the loop, bypassing the statements inside the loop,
which have not yet been executed. The keyword continue allows us
to do this. When continue is encountered inside any loop, control
automatically passes to the beginning of the loop.

 A continue is usually associated with an if. As an example, let's


consider the following program.
How works

Exercise 1

Write a C statement to accomplish each of the following tasks.


a) Define variables sum and x to be of type int.
b) Initialize variable x to 1.
c) Initialize variable sum to 0.
d) Add variable x to variable sum and assign the result to variable sum.
e) Print "The sum is: " followed by the value of variable sum
Exercise 2

What is wrong with the following while repetition statement (assume z


has value 100),which is supposed to calculate the sum of the integers
from 100 down to 1:
while ( z >= 0 )
sum += z;
Exercise 3
 Formulate a pseudocode algorithm for each of the following:

a) Obtain two numbers from the keyboard, compute their sum and
display the result.
b) Obtain two numbers from the keyboard, and determine and display
which (if either) is the larger of the two numbers.
c) Obtain a series of positive numbers from the keyboard, and
determine and display their sum. Assume that the user types the
sentinel value -1 to indicate “end of data entry.”
Q &A

You might also like