0% found this document useful (0 votes)
23 views26 pages

Unit Ii-Control Structures

The document provides an introduction to programming in C, focusing on control structures such as conditional statements (if, if-else, switch) and loops (for, while, do-while). It explains the syntax and usage of these control statements, including examples and flowcharts for better understanding. Additionally, it covers standard functions and the concept of loops, detailing their types and how they operate in C programming.

Uploaded by

Dinesh Naidu
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)
23 views26 pages

Unit Ii-Control Structures

The document provides an introduction to programming in C, focusing on control structures such as conditional statements (if, if-else, switch) and loops (for, while, do-while). It explains the syntax and usage of these control statements, including examples and flowcharts for better understanding. Additionally, it covers standard functions and the concept of loops, detailing their types and how they operate in C programming.

Uploaded by

Dinesh Naidu
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/ 26

INTRODUCTION TO PROGRAMMING

UNIT II- Control Structures: Simple sequential programs ,Conditional


Statements (if, if-else, switch), Loops (for, while, do-while) Break and Continue.

Control Statements in C
Control Flow
 In C program, statements are normally executed sequentially in order in which they
appear. But sometimes, we have to change the order of execution of statements based on
certain conditions or repeat a group of statements until certain specified conditions are
satisfied
 For this, C language provides control statements(or decision making ) statements which
alter the flow of execution and provide better control to the programmer on the flow of
execution. They are two types
o Selection/branching/decision making statement
o Repetition/ looping/iterative
Selection & Decision making
 Selection is also called as branching statement (or) decision statement.
 In these statements one group of statement depending on the result of decisions. The
result is in the form of two expressions true or false.
 Selection is performed in 2 ways
o One way selection
o Two way selection
o Multi way selection
One way selection
 One way selection is if statement.
 This if statement checks whether the condition inside the parenthesis( ) is true or not, if
the condition is true the statement inside the if body will be executed but if the
condition is false then the if body is ignored.
Syntax:
if(condition)
{
Statement1;
……
Statement n;
INTRODUCTION TO PROGRAMMING

}
Statement x;

Flow chart for if

C program to print or to check the greatest number from the given numbers
#include<stdio.h>
main( )
{
int a,b;
printf(“enter a and b values:”);
scanf(“%d%d”,&a,&b);
if(a>b)
{
printf(“a is bigger”);
}
printf(“This is a simplest if statement”);
}
Output:
Enter a and b values: 10 20
This is a simplest if statement
INTRODUCTION TO PROGRAMMING

Two way selection


 Two way selection is if else statement.
 An if…else statement is a paired statement used to selectively execute code based on
condition.
Syntax:
if(condition)
{
Statement block 1;
}
else
{
Statement block 2;
}
Statement x;
 If the value of condition is true, then statement block 1 statements will be executed. If the
value of condition is false, then statement block 2 statements will be executed.
 In any case, after the execution, the control will be automatically transferred to the
statements appearing outside the block of if.
Flow chart for if else
INTRODUCTION TO PROGRAMMING

C program to print or to check the greatest number from the given numbers
#include<stdio.h>
int main( )
{
int num;
printf("Enter a number:\n”);
scanf("%d",&num)

if(num%2==0)
{
printf("%d is even number",num);
}
else
{
printf("%d is odd number",num);
}
return 0;
}
Output: Enter a number:4
4 is even number.
Nested-if Statements
 When an if-else is included within an if-else, it is known as nested if statement.
Syntax:
if (condition 1)
{
if(condition 2)
{
Statement block 1;
}
else
{
Statement block 2;
}
}
else
{
if(condition 3)
{
Statement block 3;
}
else
{
Statement block 4;
INTRODUCTION TO PROGRAMMING

}
}
Statement x;
 There is no limit to how many levels can be nested, but if there are more than three, it
can be difficult to read.
 The statement block may contain single statement or multiple statements.
 Initially the condition 1 is evaluated, if the condition is true again condition 2 is
evaluated, if the condition 2 is true again the statement block 1 is executed followed by a
next statement.
 Otherwise condition 1 is false then condition 3 is evaluated, if the condition 3 is true
statement block 3 is executed followed by the next statement.
 Otherwise statement block 4 is executed followed by next statement
Flowchart:
INTRODUCTION TO PROGRAMMING

Program using Nested-if program


#include<stdio.h>
int main()
{
int a, b;
printf(“Enter any two integers”);
scanf(“%d%d”, &a, &b);
if(a<=b)
{
if (a<b)
printf(“ %d is less than %d”, a,b);
else
printf(“ %d is equal to %d”, a,b);
}
else
prinf(“ %d is greater than %d”, a,b );
return 0;
}
else-if ladder (or) if-else-is (or) if-else chain
 If we are having different-different test conditions with different-different statements then
for these kind of programming we need else if ladder.
 else if ladder is not interdependent to any other statements or any other test conditions.
Syntax:
if(condition 1)
{
Statement block 1;
}
. else if(condition 2)
{
Statement block 2;
}
else if(condition 3)
{
Statement block 3;
}
………..
………..
else
{
Statement block x;
}
Statement y;
INTRODUCTION TO PROGRAMMING

 This constructor is known as else-if ladder. This condition is evaluated from top to
bottom.
 The condition is true the statement blocks is executed the control is transferred to the next
statement when all the ‘n’ conditions become false then the final else containing the
default statement will be executed.
Program to calculate the average of student marks and print the class using else if
#include<stdio.h>
int main( )
{
int a,b,c,sum;
float avg;
printf(“enter the marks”);
scanf(“%d%d%d”,&a,&b,&c);
sum=a+b+c;
avg=sum/3;
printf(“avg=%f\n”,avg);
if(avg>=70)
printf(“first class with distinction”);
else if(avg>=60&&avg<=69)
printf(“first class”);
INTRODUCTION TO PROGRAMMING

else if(avg>=50&&avg<=59)
printf(“second class”);
else if(avg>=35&&avg<=49)
printf(“pass”);
else
printf(“fail”);
return 0;
}
Multi-way Selection (switch)
 Decision making are needed when the program encounters the situation to choose a
particular statement among many statements, if a program has to choose one block of
statement among many alternative, nested-if-else can be used but this makes
programming logic complex
 Instead of else-if ladder C has a built-in multi-way decision statement known as a switch.
Syntax: switch(expression)
{
case 1: statement block 1;
break;
case 2: statement block 2;
break;
…………………………
default :statement block x;
}
Statement y;
 The case label end with a semi colon
 When the expression of the switch and the case statement matches, then the statement
block of that particular case executed.
 default is also a case that is executed when the value of the variable does not match with
any of the values of the case statement.
INTRODUCTION TO PROGRAMMING

Simple program using switch


#include <stdio.h>
int main()
{
int day;
printf(“Enter weekday number(1:7)“);
scanf(“%d“&day);
switch(day)
{
case 1: printf(“Sunday“);
case 2: printf(“Monday“);
case 3: printf(“Tuesday“);
case 4: printf(“Wednesday“);
case 5: printf(“Thursday“);
case 6: printf(“Friday“);
case 7: printf(“Saturday“);
default : printf(“Invalid number\n“);
}
return 0;

}
INTRODUCTION TO PROGRAMMING

More Standard Functions


 The standard functions are built-in functions. In C programming language, the standard
functions are declared in header files and defined in .dll files.
 The standard functions can be defined as "the readymade functions defined by the system
to make coding more easy".
 The standard functions are also called as library functions or pre-defined functions.
 In C when we use standard functions, we must include the respective header file
using #include statement.
 For example, the function printf() is defined in header file stdio.h (Standard Input
Output header file). When we use printf() in our program, we must include
stdio.h header file using #include<stdio.h> statement.
 C Programming Language provides the following header files with standard functions.
Header file Purpose Example function
stdio.h Provides function to perform standard I/O operations printf(),scanf()
conio.h Provides function to perform consol I/O operations clrscr(),getch()
math.h Provides function to perform mathematical operations sqrt(),pow()
string.h Provides function to handle string data values strlen(),strcpy()
stdlib.h Provides function to perform general functions calloc(), malloc()
time.h Provides functions to perform operations on time and time(), localtime()
date
ctype.h Provides functions to perform - testing and mapping of isalpha(), islower()
character data values
setjmp.h Provides functions that are used in function calls setjump(), longjump()
signal.h Provides functions to handle signals during program signal(), raise()
execution
assert.h Provides Macro that is used to verify assumptions assert()
made by the program
locale.h Defines the location specific settings such as date setlocale()
formats and currency symbols
INTRODUCTION TO PROGRAMMING

stdarg.h Used to get the arguments in a function if the va_start(), va_end(),


arguments are not specified by the function va_arg()
errno.h Provides macros to handle the system calls Error, errno
graphics.h Provides functions to draw graphics. circle(), rectangle()
float.h Provides constants related to floating point data values
stddef.h Defines various variable types
limits.h Defines the maximum and minimum values of various
variable types like char, int and long
INTRODUCTION TO PROGRAMMING

Repetition
Concept of Loop
Loop
 Loop causes program to execute the certain block of code repeatedly until some
conditions are satisfied.
 Each repetition is also referred as an iteration or pass through the loop.
 For example if we want to execute some code for 10 times. We can perform it by writing
that codes only one time and repeat the execution 10 times using loop.

Concept of a Loop
Pre-test and Post-test Loops
 To check the loop control expression either before or after each iteration of the loop.
 In a pre-test loop, the condition is checked before the beginning of each iteration.
 If the condition is true, the code is executed, else the loop is terminated.
 In a post-test loop the actions are executed. Then the control expression is tested(Last).
 If it is true, a new iteration is started; otherwise, the loop terminates. Here the actions are
executed atleast once.
INTRODUCTION TO PROGRAMMING

Initialization and Updating


 In loop control expression, two other process, initialization and updating are associated
with almost all loops.
Loop initialization
 Before a loop start initialization must be done. It sets the stage for the loop action.
 Initialization may be implicit or explicit.
Loop update
 It is necessary to change the condition true to false, otherwise the loop will be executed
indefinitely.
 The actions that cause these changes are known as loop update. Updating is done in each
iteration.
 If the body of the loop is repeated ‘n’ times, the updating is also done ‘n’ times.
INTRODUCTION TO PROGRAMMING

Event and Counter Controlled Loops


Event Controlled Loops:
 In an event-controlled an event that happens in the loops execution block that changes the
loops control expression from true to false.
 The program can update the loop control expression explicitly or implicitly.
 In an event-controlled loop pre-test loop, the condition is tested first.If the condition is
true, then the action and iterations takes place. If the condition is false, the loop
terminates.

Counter-controlled Loops
 In a counter- controlled loop, the number of loop iterations can be controlled.
 In such a loop, we use a counter, which we must initialize, update and test.
 The number the loop assigned to the counter does not need to be a constant value, to
INTRODUCTION TO PROGRAMMING

update, we can increment or decrements the counter.

Loops in C
 Loops are divided into 3 types:
o While /top testes/ entry loop
o Do-while/bottom tested/post-tested loop/exit loop
o For loop
While Loop
 A while loop is the most straightforward looping structure. The basic format of while
loop is as follows:
Syntax:
while(condition)
{
Body of the while loop;
Update expressions;
}
Statement z;
 It is an entry-controlled loop/top checking loop. In while loop, a condition is evaluated
before processing a body of the loop
 If a condition is true, then the body of a loop is executed. After the body of a loop is
executed then control again goes back at the beginning, and the condition is checked if it
is true, the same process is executed until the condition becomes false.
INTRODUCTION TO PROGRAMMING

 Once the condition becomes false, the control goes out of the loop. After exiting the loop,
the control goes to the statements which are immediately after the loop.
 The body of a loop can contain more than one statement. If it contains only one
statement, then the curly braces are not compulsory.

Ex1 Program to print series from 1 to 10


#include<stdio.h>
int main()
{
int i=1; //initializing the variable
while(i<=10) //while loop with condition
{
printf("%d\t",i);
i++; //incrementing operation
}
return 0;
}
Output:
1 2 3 4 5 6 7 8 9 10

Ex2 Write a C program to Check whether the given number is Armstrong or not.
#include<stdio.h>
INTRODUCTION TO PROGRAMMING

main( )
{
int n,rem,sum=0,temp;
printf("Enter a Number:");
scanf("%d",&n);
temp=n;
while(n!=0)
{
rem=n%10;
sum=sum+(rem*rem*rem);
n=n/10;
}
if(sum==temp)
printf("%d is Armstrong\n",temp);
}
Output:
Enter a Number:153
153 is Armstrong
INTRODUCTION TO PROGRAMMING

Do-While loop
 A do-while loop is similar to the while loop except that the condition is always executed
after the body of a loop.
 It is also called an exit-controlled loop. The basic format of do-while loop is as follows:
Syntax:
do
{
Body of the loop;
Update expressions;
} while(condition);
Statement z;
 In the do-while loop, the body of a loop is always executed at least once.
 After the body executed, then it checks the condition. If the condition is true, then it will
again execute the body of a loop; otherwise control is transferred out of the loop.
 Once the control goes out of the loop the statements which are immediately after the loop
is executed.
INTRODUCTION TO PROGRAMMING

Disadvantage
 The using of do-while loop is that it always executes at least once, even if the user enters
some invalid data.
Program to print a table of number 5using do while loop.
#include<stdio.h>
int main()
{
int i=1; //initializing the variable do
//do-while loop
{
printf("%d\t",5*i);
i++; //incrementing operation
}while(i<=10);
return 0;
}
Output:
5 10 15 20 25 30 35 40 45 50
INTRODUCTION TO PROGRAMMING

For loop
 A for loop is a more efficient loop structure in 'C' programming. The general structure of
for loop is as follows:
Syntax:
for(initialization; condition, increment/decrement)
{
Code to be executed;
}
Statement z;
 The initialization statement of the for loop is performed only once, at the beginning.
 The condition is a Boolean expression that tests and compares the counter to a fixed
value after each iteration, terminates the for loop when false is returned.
 The incrementation/decrementation increases (or decreases) the counter by a set value.
Flow Chart:
INTRODUCTION TO PROGRAMMING

Program to illustrate the use of a simple for loop:


#include<stdio.h>
int main()
{
int i;
for(i=10;i>=1;i--) //for loop to print numbers in reverse order
{
printf("%d\t",i); //to print the number
}
return 0;
}
Output:
10 9 8 7 6 5 4 3 2 1
Write a C Program to print the Factorial of a given number
#include<stdio.h>
main( )
{
int n,i;
int fact=1;
printf("Enter a number");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
fact=fact*i;
}
printf("Factorial of %d is %d\n",n,fact);
}
Output:
Enter a number5
Factorial of 5 is 120
INTRODUCTION TO PROGRAMMING

Comma Expression
The for loop can have multiple expressions separated by commas in each part.

For example:
for (x = 0, y = num; x < y; i++, y--)
{
statements;
}
Also, we can skip the initial value expression, condition and/or increment by adding a semicolon.
For example:
int i=0;
int max=10;
for ( ; i < max; i++)
{
Printf(“%d\n”,i);
}
Nested for loop
 Loops can also be nested where there is an outer loop and an inner loop.
 For each iteration of the outer loop, the inner loop repeats its entire cycle.
INTRODUCTION TO PROGRAMMING

Program to illustrate the use of a simple for loop:


#include<stdio.h>
int main()
{
int rows,i,j;
printf("Enter the rows:");
scanf("%d",&rows);
for (i=1;i<=rows;i++)
{
for(j=1;j<=i;j++)
printf("*");
printf("\n");
}
return 0;
}
Output:
Enter the rows:7
*
**
***
****
*****
******
*******
Other Statements Related to Looping
Break Statement
 The break statement is used mainly in the switch statement.
 It is also useful for immediately stopping a loop.
Syntax: break;
INTRODUCTION TO PROGRAMMING

Program to illustrate the use of break statement


#include <stdio.h>
int main()
{
int num = 5;
while (num> 0)
{
if (num == 3)
break;
printf("%d\n", num);
num--;
}
}
Output:
5
4
Continue Statement
 When you want to skip to the next iteration but remain in the loop, we should use the
continue statement.
Syntax: continue;
INTRODUCTION TO PROGRAMMING

Program to illustrate the use of continue statement


#include <stdio.h>
int main()
{
int num = 7;
while (num> 0)
{
num--;
if (num== 5)
continue;
printf("%d\n", num);
}
}
Output:
6
4
3
2
1
So, the value 5 is skipped.
goto Statement
 goto statement is used to jump from one line to another line in the program.
 Using goto statement we can jump from top to bottom or bottom to top.
 To jump from one line to another line, the goto statement requires a label. Label is a
name given to the instruction or line in the program followed by colon.
 When we use a goto statement in the program, the execution control directly jumps to
INTRODUCTION TO PROGRAMMING

the line with the specified label.


Syntax: goto label;
goto label;
…………..
…………..
Label:
statements;
Program to illustrate the use of goto statement
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf("We are at first printf statement!!!\n");
goto last;
printf("We are at second printf statement!!!\n");
printf("We are at third printf statement!!!\n");
last:
printf("We are at last printf statement!!!\n");
getch() ;
}

You might also like