0% found this document useful (0 votes)
66 views18 pages

IP NOTES - Unit - 2 - Student

Shjsjs

Uploaded by

bbgg9018
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)
66 views18 pages

IP NOTES - Unit - 2 - Student

Shjsjs

Uploaded by

bbgg9018
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/ 18

INTRODUCTION TO PROGRAMMING

Unit – II Control Structures

 Control Structures
 Simple sequential programs
 Conditional Statements
 If
 if-else
 if..else..if
 switch
 Looping Statements
 For
 While
 do- while
 Unconditional Statements
 Break and Continue

Y. Srinivasa Rao, Asst.Proressor, AIML & DS Dept., ACET Page 1


INTRODUCTION TO PROGRAMMING

Control Structures:
A program is nothing but the execution of sequence of one or more instructions.
Sometimes it is desirable to alter the execution of sequence of statements in the program
depending upon certain circumstances. This involves decision making through branching and
looping.

Conditional Statements
Conditional Statements require that the programmer specifies one or more conditions to be
evaluated or tested by the program, along with a statement (s) to be executed if the condition
is determined to be true, and optionally, other statements to be executed if the condition is
determined to be false.

The general form of a typical decision-making structure found in most of the programming
languages:

C programming language assumes

any non-zero and non-null values as true,

and if it is either zero or null, then it is assumed as false value.

C programming language provides the following types of decision-making statements.

Decision Making/
Selection/ Branching
statements

Conditional Statements Unconditional Statements

If If..else If..esle if Switch Break Continue Go to

Y. Srinivasa Rao, Asst.Proressor, AIML & DS Dept., ACET Page 2


INTRODUCTION TO PROGRAMMING
Control statements specify the order in which the various instructions in a program are to be
executed by the computer. i.e. ,they determine the „flow of control‟ in a program. Various
control statements in C are:
 One way Selection statement
 Two way Selection statement
 Multi way Selection statement
 Repetition or Loop control statements

One way Selection statement: The statement is executed if the value of the expression
is true. One way Selection is implemented using simple “if statement”.

IF STATEMENT:
The if statement is a powerful decision making statement and is used to control the flow of
execution of statements. C uses the keyword “if” to execute a set of statements or one
statements when the logical condition is true.
Syntax: If (condition or expression)
{
Statements-block;
}
Next statement;
 In above syntax, the condition is checked first which allows the computer to evaluate
the expression first and then depending on the value of expression, the control
transfers to the particular statement.
 If the expression is true (non- zero value) then the statement-block is executed and
next statement is executed.
 If the expression is false (zero), directly next statement is executed without executing
the statement- block.
Note: Statement-block may be one or more statements. If more than one statement, then keep
all those statements in compound block ({ }).
Flow Chart:

Test False
Expression

True
Statement (s) of
Conditional Code

Statement x

Y. Srinivasa Rao, Asst.Proressor, AIML & DS Dept., ACET Page 3


INTRODUCTION TO PROGRAMMING
Example: write a C Program to find a given number is greater than or equal to 4

#include <stdio.h>
Void main()
{
int a=5;
if(a>4)
{
printf("\nValue of „a‟ is greater than 4!");
}
if(a==4)
{
printf("\n\nValue of „a‟ equal to 4!");
}
}
Output: Value of „a‟ is greater than 4!

Rules for IF/IF-ELSE/IF-ELSEIF Statements:

Rule1: The expression must be placed between parenthesis ().

Rule2: The semi colon ; must not placed after the test-expression; it will place only end of
statement or block of statements.

Rule3: The open/close braces are placed more than one statement.

TWO WAY SELECTION STATEMENT: Selection statements allow the computer to take
a decision as to which statement is to be executed next based on the answer either true or
false. Two way selection is implemented using

 if–else
 nested if

IF – ELSE STATEMENT:
 It is an extension of simple if. It has two statement blocks.
 One is for if and it is executed when the condition is true.
 The other block is for else and it is executed when the condition is false.
 No multiple else statements are allowed with one if.

Syntax:

if(condition)
{
True statements; //if code
}
else
{

Y. Srinivasa Rao, Asst.Proressor, AIML & DS Dept., ACET Page 4


INTRODUCTION TO PROGRAMMING
False statements; //else code
}
 In above syntax, the condition is checked first.
 If it is true, then the program control flow goes inside the braces and executes the
block of true statements associated with it.
 If it returns false, then it executes the else part of a program.

Flow Chart:

True Test False


Expression

Statement Block 1 Statement Block 2

Statement x

Example: C program to check whether the given year is leap or not using if..else statement.

#include<stdio.h>

void main()

int year;

printf("enter any year:");

scanf("%d",&year);

if(year%4==0)

printf("\n %d is leap year ",year);

else

printf("\n %d is non leap year ",year);

Output: Enter any year: 1996


1996 is leap year.

Y. Srinivasa Rao, Asst.Proressor, AIML & DS Dept., ACET Page 5


INTRODUCTION TO PROGRAMMING
NESTED IF STATEMENTS
Defining if block within another if block is called Nested if. we can place an if statement
inside another if statement.
Syntax
The syntax for a nested if statement is as follows:
if(condition – 1)
{
if(condition – 2)
statement – 1;
else
statement – 2;
}
else
{
if(condition – 3)
statement – 3; next statement;
}

Flowchart:

False Test True


Expression-1

Test
False Test True
Expression-3 Expression-1

Statement Block 2
Statement Block 1
Statement Block 3

Statement y

Example:
Write a C program to find the biggest of three numbers.
Program:
#include<stdio.h>
main()
{
int a,b,c;
scanf(“%d%d%d”,&a,&b,&c);
if(a>b)
{

Y. Srinivasa Rao, Asst.Proressor, AIML & DS Dept., ACET Page 6


INTRODUCTION TO PROGRAMMING
if(a>c)
{
printf(“the biggest no. is %d”,a);
}
else
{
printf(“the biggest no.is %d”,c);
}
}
else
{
if(b>c)
{
printf(“the biggest no is %d”,b);
}
else
{
printf(“the biggest no is %d”,c);
}
}

MULTI-WAYSELECTION: Multiway selection chooses among several alternatives. The


decision logic for multi way selection is shown below.

Multi way selection is implemented using

 if–elseif /else if ladder


 Switch
Y. Srinivasa Rao, Asst.Proressor, AIML & DS Dept., ACET Page 7
INTRODUCTION TO PROGRAMMING

IF-ELSEIF STATEMENT: (Else if Ladder)


 If else if is used to check multiple conditions.
 If one among the multiple conditions is true then the statement related to that
particular condition is executed and all other conditions are ignored.
 If none of the condition are true then the final else statement is executed.

Syntax: if (condition1)

{
// Statements block 1 to be executed if condition1 is true
}
else if (condition2)
{
// Statements block 2 to be executed if condition2 is true
}
// Additional else if blocks as needed
else
{
// Statements block 3 to be executed if none of the conditions are true
}

Flow chart:

If condition-1 True
Statement Block 1

False

Elseif True
condition-2 Statement Block 2

False

Elseif True
condition-3 Statement Block3

False
Else Block

Statement x

Example:
//C Program to find whether input year is leap year or not

Y. Srinivasa Rao, Asst.Proressor, AIML & DS Dept., ACET Page 8


INTRODUCTION TO PROGRAMMING
#include <stdio.h>
main()
{
Int year;
printf("Enter the year:");
scanf("%d",&year);
if(year%400==0)
{
printf("It is a leap year");
}
elseif(year%100==0)
{
printf("It is not a leap year");
}
elseif(year%4==0)
{
printf("It is a leap year");
}
else
{
printf("It is not a leap year");
}
}
Output: Enter the year: 2020 It is a leap year
Enter the year: 2021 It is not a leap year

Dangling else problem:


 Nested if and if else if statement encounter a problem known as
dangling else problem.
 It is created when there is no matching else for every if statement.
 In this case „c‟ compiler always match an else statement to the most
recent if statement.
Ex:
If(a>b)
If(a>c)
Printf(“a is greater than b and c\n”);
Else
Printf(“a is not greater than b and c\n”);

SWITCH STATEMENT:
A switch statement allows a variable to be tested for equality against a list of values. Each
value is called a case, and the variable being switched on is checked for each switch case.

Syntax

Y. Srinivasa Rao, Asst.Proressor, AIML & DS Dept., ACET Page 9


INTRODUCTION TO PROGRAMMING
The syntax for a switch statement in C programming language is as follows:

switch(expression}
{
case label – 1: block – 1;
break;
case label – 2: block – 2;
break;
-----------------
-----------------
case label – n: block – n;
break;
default : default block;
break;
}
next statement;

 It displays only integer constants, character constants and expression. We cannot give
floating point values as case labels.
 First the expression will be evaluated. label – 1 ,label – 2, …. label – n are called case
labels.
 The value of the expression is compared with all the case labels one by one. If it is equal
to one of the case label, the block associated with that case will be evaluated and the
break statement will indicate the end of the switch statement. If it is not equal to any of
the case labels the default block will be evaluated and this default is optional.
Break:
 The break statement must be used at the end of each case because if it is not used,
then the case that matched and all the following cases will be executed.
 For example, if the value of switch statement matched with that of case 2, then all the
statements in case 2 as well as the rest of the cases including default will be executed.
 The break statement tells the compiler to jump out of the switch case statement and
execute the statement following the switch–case construct. Thus, the keyword break is
used to break out of the case statements.
Flow Diagram:

Y. Srinivasa Rao, Asst.Proressor, AIML & DS Dept., ACET Page 10


INTRODUCTION TO PROGRAMMING

Example:

Write a C Program to make a simple Calculator to Add, Subtract, Multiply or Divide Using
switch-case.

Program: #include<stdio.h> main()

float a,b,res; int ch;

printf("Enter two numbers: ");

scanf("%f%f",&a,&b);

printf("(1) ADDITION\n”);

printf("(2) SUBTRACTION\n");

printf("(3) MULTIPLICATION\n");

printf("(4) DIVISION\n");

printf("(5) REMAINDER\n");

printf("(0) EXIT\n");

printf("Enter your choice: ");

scanf("%d",&ch);

switch(ch)

Y. Srinivasa Rao, Asst.Proressor, AIML & DS Dept., ACET Page 11


INTRODUCTION TO PROGRAMMING
{

case 1: res=a+b;

printf("Addition: %.2f\n\n",res);

break;

case 2: res=a-b;

printf("Subtraction: %.2f \n\n",res);

break;

case 3: res=a*b;

printf("Multiplication: %.2f \n\n",res);

break;

case 4: res=a/b;

printf("Division: %.2f \n\n",res);

break;

case 5: res=(int)a%(int)b;

printf("Remainder: %d\n\n",res);

break;

case 0: printf("Choice Terminated\n\n");

break;

default: printf("Invalid Choice\n\n");

break;

Output:

Enter two numbers: 10 20

(1) ADDITION

(2) SUBTRACTION

(3) MULTIPLICATION

Y. Srinivasa Rao, Asst.Proressor, AIML & DS Dept., ACET Page 12


INTRODUCTION TO PROGRAMMING
(4) DIVISION

(5) REMAINDER

(0) EXIT

Enter your choice: 1 Addition: 30.00

LOOPING STATEMENTS (REPETITIVE / ITERATIVE):


Looping statements are used to repeat the execution of a sequence of statements until the
specified expression becomes false.

Loop in a Program consists of 2 parts:


1.Body – Block of Statements
2.Control Statement – used to test the condition and directs the repeated execution of the
statements.

Any Looping statement includes:


1.Initialization of a condition variable
2.Test the control statement
3.Executing the body according to condition
4.updating the condition variable

Types of Loops:
 C supports three types of iterative statements. They are
o while loop
o do–while loop
o for loop

 Depending upon the position of a control statement in a program, a loop is classified


into two types:
1. Entry controlled loop: (Pre-Test)
o In an entry controlled loop, a condition is checked before executing the body
of a loop. It is also called as a pre-checking loop.
o Ex: while, for

2. Exit controlled loop:


o In an exit controlled loop, a condition is checked after executing the body of
a loop. It is also called as a post-checking loop
o Ex:do-while

Y. Srinivasa Rao, Asst.Proressor, AIML & DS Dept., ACET Page 13


INTRODUCTION TO PROGRAMMING
WHILE LOOP:
 The while loop provides a mechanism to repeat one or more statements while a
particular condition is true.
Syntax:
While (condition )
{
Statements block;
}
Flowchart:

 In the while loop, the condition is tested before any of the statements in the statement
block is executed. (pre test – entry controlled loop).
 If the condition is true, only then the statements will be executed, otherwise if the
condition is false, the control will jump to next statement.
Example program to calculate the sum of n natural numbers using while loop:
#include<stdio.h>
#include<conio.h>
main()
{
int i=1, sum=0, n;
clrscr();
printf(“enter the value of n:”);
scanf(“%d”,&n);
while(i<=n)
{
sum=sum+i;
i++;
}
printf(“\n sum is %d”,sum);
getch();
}
Output: enter the value of n:10
Sum is 55

Y. Srinivasa Rao, Asst.Proressor, AIML & DS Dept., ACET Page 14


INTRODUCTION TO PROGRAMMING
DO-WHILE LOOP:
 The do–while loop is similar to the while loop.
 The only difference is that in a do–while loop, the test condition is tested at the end of
the loop.(Post test – Exit controlled Loop).
 As the test condition is evaluated at the end, this means that the body of the loop gets
executed at least one time (even if the condition is false).
Syntax:
do
{
\\Statements block;
}
while (expression);
Flowchart:

 The do–while loop continues to execute while the condition is true and when the
condition becomes false, the control jumps to the statement following the do–while
loop.
 The major disadvantage of using a do–while loop is that it always executes at least
once, so even if the user enters some invalid data, the loop will execute.

Example program to calculate the sum of n natural numbers using do-while loop:
#include<stdio.h>
#include<conio.h>
main()
{
int i=1,sum=0;n;
clrscr();
printf(“enter the value of n:”);
scanf(“%d”,&n);
do
{
sum=sum+i;
i++;
}
Y. Srinivasa Rao, Asst.Proressor, AIML & DS Dept., ACET Page 15
INTRODUCTION TO PROGRAMMING
while(i<=n);
printf(“\nsum is %d”,sum);
getch();
}
Output: enter the value of n:10
Sum is 55

FOR LOOP:
 Like the while and do–while loops, the for loop provides a mechanism to repeat a task
till a particular condition is true.
 For loop is usually known as a determinate or definite loop because the programmer
knows exactly how many times the loop will repeat.

Synax:

for(initialization; condition; incrementation/decrementation)


{
Statement block;
}
Flowchart:

 The initialization step is executed first.


 Next, the condition is evaluated. if true, the loop body is executed. If false, the body
of the loop doesn‟t execute and the flow jumps to the next statement.
 After the loop executes the flow of control jump back to the increment/decrement
operation.

Example program to calculate the sum of n natural numbers using for loop:
#include<stdio.h>
#include<conio.h>
main()
{
int i,sum=0;n;

Y. Srinivasa Rao, Asst.Proressor, AIML & DS Dept., ACET Page 16


INTRODUCTION TO PROGRAMMING
clrscr();
printf(“enter the value of n:”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
sum=sum+i;
}
printf(“\nsum is %d”,sum);
getch();
}
Output: enter the value of n:10
Sum is 55

CONTINUE Statement:
 When the compiler encounter a continue statement then the rest of the statements in
the loop are skipped and the control is unconditionally transferred to the beginning of
loop.

Syntax/general form:
Continue;

Example program using continue keyword:


#include<stdio.h>
#include<conio.h>
main()
{
int i;
clrscr();
for(i=1;i<=10;i++)
{
if(i==5)
continue;
printf("the value of i is %d\n",i);
}
getch();
}

Y. Srinivasa Rao, Asst.Proressor, AIML & DS Dept., ACET Page 17


INTRODUCTION TO PROGRAMMING
break Statement continue Statement
Terminates the loop Skips the rest of the loop for the
prematurely. current iteration and moves to the
next iteration.
Immediately exits the loop. Skips the remaining code in the loop
for the current iteration.
Used when a certain condition Used when you want to skip specific
is met, and you want to exit iterations based on a condition
the loop. without exiting the loop.
Control passes to the next Control passes to the Beginning of the
statement out of Block or loop current loop (Inside loop).

Goto statement: (Unconditional Jump)


 The goto statement is used to transfer control to a specified label.
 However,the label must reside in the same function and can appear only before one
statement in the same function.
 The goto statement requires a label to identify the place to move the execution. A
label is a valid name and must be ended with colon(:).
Syntax:
Goto label;
…………….
……………. Forward jump
Label:
Statements;

Label:
Statements;
…………….. backward jump
……………..
Goto label;

Y. Srinivasa Rao, Asst.Proressor, AIML & DS Dept., ACET Page 18

You might also like