Control Statements
Control Structures
A control structure refers to the way in which the programmer
specifies the order of execution of the statements.
The control structures are classified into
Sequential: In this approach, all the statements are
executed in the same order as it is written.
Selectional: In this approach, based on some conditions,
different set of statements are executed.
Iterational or Repetition: In this approach, a set of
statements are executed repeatedly.
Selectional Control Structures
There are two categories of selectional control structures
Conditional control statements
if statement
switch statement
Unconditional control statements
goto statement
Simple if statement
In a simple if statement, a condition is tested.
If the condition is true, a set of statements are executed
If the condition is false, control goes to the next statement that
immediately follows the if block.
Syntax:
if (condition){
Statement(s);
}
Next statement;
#include <stdio.h>
main()
{
int number;
printf("Enter an integer: ");
scanf("%d", &number);
if (number < 0)
{
printf("You entered %d \n", number);
}
printf(“Next Statement.”);
}
else statement
In a simple if statement, when the condition is true, a set of
statements are executed. But when it is false, there is no
alternate set of statement.
The statement else provides the same.
Syntax:
if(condition) {
Statement-set1;
}
else {
Statement-set2;
}
Next statement;
#include <stdio.h>
main()
{
int number;
printf("Enter an integer: ");
scanf("%d",&number);
if( number%2 == 0 )
printf("%d is an even integer.",number);
else
printf("%d is an odd integer.",number);
}
else if statement
The ’else if’ statement is to check for a sequence of conditions
When one condition is false, it checks for the other condition and so on
When all the conditions are false, else block is executed
The statements in that conditional block are executed and other if
statements are skipped
Syntax:
if(condition-1) {
Statement-Set 1 ;
else if (condition-2) {
Statement-Set 2;
else {
Statement-Set n;
};
Next Statement;
#include <stdio.h>
main()
{
int number1, number2;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);
if(number1 == number2)
{
printf("Result: %d = %d",number1,number2);
}
else if (number1 > number2)
{
printf("Result: %d > %d", number1, number2);
}
else
{
printf("Result: %d < %d",number1, number2);
}
}
Assignment operator (=) Vs Equality operator (==)
The operator ’=’ is used for assignment purpose whereas the operator
’==’ is used to check for equality.
It is a common mistake to use ’=’ instead of ’==’ to check for equality.
The compiler does not generate any error message
To overcome the problem, when constraints are compared with
variables for equality, write the constant on the left hand side of the
equality symbol.
Nested if statement
An if statement embedded within another if statement is called as
nested if statement.
#include <stdio.h>
#include <conio.h>
main()
{ char username;
int password;
printf("Username:"); scanf("%c",&username);
printf("Password:"); scanf("%d",&password);
if(username=='a')
{
if(password==12345)
printf("Login successful");
else
printf("Password is incorrect, Try again.");
}
else
{
printf("Username is incorrect, Try again.");
}
}
Logical Conditions In IF
• The NOT operator is often used to reverse the logical
value of a single variable, as in the expression
– if ( ! flag )
• This is another way of saying
– if ( flag == 0 )
The Conditional Operators
• The conditional operators ? and : are sometimes
called ternary operators since they take three
arguments
– expression 1 ? expression 2 : expression 3
• What this expression says is: “if expression 1 is true
(that is, if its value is non-zero), then the value
returned will be expression 2, otherwise the value
returned will be expression 3”.
The Conditional Operators
int x, y ;
scanf ( "%d", &x ) ;
y=(x>5?3:4);
• This statement will store 3 in y if x is greater than 5,
otherwise it will store 4 in y.
• The equivalent if statement will be,
if ( x > 5 )
y=3;
else
y=4;
Conditional Operator (Ternary Operator)
Example:
char a ;
int y ;
scanf ( "%c", &a ) ;
y = ( a >= 65 && a <= 90 ? 1 : 0 ) ;
Here 1 would be assigned to y if a >=65 && a <=90 evaluates to
true, otherwise 0 would be assigned
Conditional Operator (Ternary Operator)
• Not necessary that conditional operators should be used
only in arithmetic statements
Eg1:
int i ;
scanf ( "%d", &i ) ;
( i == 1 ? printf ( “hello" ) : printf ( “hi" ) )
Eg2:
char a = 'z' ;
printf ( "%c" , ( a >= 'a' ? a : '!' ) ) ;
Nested
• Conditional operators can be nested :
int big, a, b, c ;
big = ( a > b ? ( a > c ? 3: 4 ) : ( b > c ? 6: 8 ) ) ;
Goto Statement
The syntax for a goto statement in C is as follows −
goto label;
.. .
label: statement;
#include <stdio.h>
int main ()
{ int a = 10;
LOOP:do
{ if( a == 15)
{ a = a + 1;
goto LOOP;
}
printf("value of a: %d\n", a);
a++;
}while( a < 20 );
return 0;
}
Switch Case statement
The Switch statement is a selectional control structure that selects a
choice from the set of available choices.
It is similar to if statement but not a replacement for if statement.
Syntax:
Switch(expression){
case integer or character constant-1: Statement(s) ;
break;
case integer or character constant-2: Statement(s) ;
break;
case integer or character constant-n: Statement(s) ;
break;
default: Statement(s) ;
break;
}
int main()
{
int i=3;
switch (i)
{
case 1:
printf("Case1 ");
case 2:
printf("Case2 ");
case 3:
printf("Case3 ");
case 4:
printf("Case4 ");
default:
printf("Default ");
}
return 0;
}
int main()
{ int i=2;
switch (i)
{
case 1:
printf("Case1 ");
break;
case 2:
printf("Case2 ");
break;
case 3:
printf("Case3 ");
break;
case 4:
printf("Case4 ");
break;
default:
printf("Default ");
}
return 0; }
Iterative Control Structures
Iterative or repetitive control structures are used to repeat certain
statements for a specified number of times
The statements are executed as long as the condition is true
They are also called as loop control structures
The three looping structures are
while
do while
for
while loop control structure
A while loop is used to repeat certain statements as long as the
condition is true
When the condition becomes false, the control jumps to the next
statement of the while loop
This loop is called as an entry controlled loop because only when the
condition is true, are the statements executed
Syntax:
while(condition){
Set of statements;
}
Next statement;
#include <stdio.h>
int main ()
{
int a = 10;
while( a < 20 )
{
printf("value of a: %d\n", a);
a++;
}
return 0;
}
do while loop control structure
The do while loop is similar to while loop
In this loop, the condition is tested at the end of the loop
Due to this reason, the statements of the do while loop are executed at
least once
This is also called exit controlled loop
Syntax:
do {
Set of statement(s) ;
} while(condition) ;
Next statement;
#include <stdio.h>
int main () {
int a = 10;
do {
printf("value of a: %d\n", a);
a = a + 1;
}while( a < 20 );
return 0;
}
Differences between while and do while loops
while loop do while loop
condition is tested condition is tested
before entering into loop at the end of the loop
statements will not execute at all at least once the statements are
when the condition is false executed even when the condition is false
for loop control structure
for loop is similar to the other loop control structures
It is generally used when certain statements have to be executed a
specific number of times
all the three parts of the loop i.e., initialization, condition checking and
increment or decrement can be given in a single statement
Syntax:
for(initialization; condition; increment/decrement){
Set of statement(s);
} Next statement;
#include <stdio.h>
int main () {
int a;
for( a = 10; a < 20; a = a + 1 )
{
printf("value of a: %d\n", a);
}
return 0;
}
Find the prime numbers from 2 to 20
#include <stdio.h>
int main () {
int i, j, k;
for(i = 2; i<=20; i++)
{
k=0;
for(j = 2; j < i; j++)
{
int r=i%j;
if(r==0)
{
k=1;
break;
}
}
if(k==0)
printf("%d is prime\n", i);
}
return 0;
}
Quitting the loops - break statement
break statement is used to
force the termination of loop
when a break statement is encountered in a loop, the loop
terminates immediately and the execution resumes the next
statement following the loop
Note:
break statement can be used in an if statement only when the if
statement is written in a loop
just an if statement without a loop leads to a compilation error
#include <stdio.h>
int main ()
{
int a = 10;
while( a < 20 )
{
printf("value of a: %d\n", a);
a++;
if( a > 15)
{
break;
}
}
return 0;
}
Continuing the loops - continue statement
continue statement forces the next iteration of the loop to take place
and skips the code between continue statement and the end of the loop
in case of for loop, the continue statement makes the execution of the
increment/decrement portion of the statement and then evaluates the
condition part
in case of while and do while loops, the continue statement makes the
conditional statement to be executed
#include <stdio.h>
int main ()
{
int a = 10;
do
{
if( a == 15)
{
a = a + 3;
continue;
}
printf("value of a: %d\n", a);
a++;
}
while( a < 20 );
return 0;
}
Defining Constants
• Similar like a variable declaration except the
value cannot be changed
• In declaration, const keyword is used before or
after type
• int const a = 1; const int a =2;
• It is usual to initialise a const with a value as it
cannot get a value any other way.
Preprocessor definition
• #define is another more flexible method to
define constants in a program
• #define TRUE 1
• #define FALSE 0
• #define NAME_SIZE 20
• Here TRUE, FALSE and NAME_SIZE are constant
Relational and Equality Operators
• Variable relational-operator variable
• Variable relational-operator constant
• Variable equality-operator variable
• Variable equality-operator constant
Relational and Equality Operators
Examples
Memory with Values
Logical Operators
• To form more complicated conditions or logical
expressions
• Three operators:
– And (&&)
– Or (||)
– Not(!)
Logical And
Logical Or
Logical Not
True/False Values
• For numbers all values except 0 is true
• For characters all values except ‘/0’ (Null
Character) is true
!flag
1 (true)
x + y / z <= 3.5
5.0 <= 3.5 is 0 (False)
!flag ||(y + z >= x-z)
1 ||1 = 1
Short Circuit Evaluation
• Stopping evaluation of a logical expression as
soon as its value can be determined is called
short-circuit evaluation
• Second part of ‘&&’ does not gets evaluated
when first part is evaluated as False
• Second part of ‘||’ does not gets evaluated when
first part is evaluated as true
Short Circuit Evaluation
• (num % div == 0) – Runtime error if div = 0
• But prevented when written as
• (div != 0 && (num % div == 0))
Comparing Characters
• We can also compare characters in C using the
relational and equality operators
Logical Assignment
• even = (n % 2 == 0);
• in_range = (n > -10 && n < 10);
• is_letter = ('A' <= ch && ch <= 'Z') || ('a' <= ch && ch <= 'z');
• Variable in_range gets 1 (true) if the value of n is
between −10 and 10 excluding the endpoints;
• is_letter gets 1 (true) if ch is an uppercase or a
lowercase letter.
When 'A‘ = 60 and 'B' =13
Example 1
• #include<stdio.h>
void main()
{
float i=0.0;
if(i)
printf("Yes");
else
printf(“No”);
}
Output 1
• No
Example 2
• #include<stdio.h>
void main()
{
int i=-3;
if(i)
printf("Yes");
else
printf(“No”);
}
Output 2
• Yes
Example 3
• #include<stdio.h>
void main()
{
char i =‘a’;
if(i)
printf("Yes");
else
printf(“No”);
}
Output 3
• Yes
Example 4
• #include<stdio.h>
void main()
{
int a = 2 , b=5;
if ((a==0)&&(b==1))
printf(“Hi”);
printf(“a is %d and b is %d”, a, b);
}
Output 4
• a is 2 and b is 5
Library Functions
• Predefined Functions and Code Reuse
• Code reuse - reusing program fragments that
have already been written and tested
whenever possible, is one way to accomplish
this goal.
Scanf and printf
• scanf and printf are also predefined functions
that are defined in the header file stdio.h
• scanf - returns the number of items
successfully read
• printf() - returns the number
of characters successfully written on the output
#include<stdio.h>
Example
main()
{
int a,b,c,d;
printf("Enter the values for a and b\n");
c=scanf("%d%d",&a,&b);
printf("Scanf ret value %d\n",c );
d=printf("Hello\n\t1\n");
printf("Printf ret value %d\n", d);
On giving inputs as:
10
20
Output:
Enter the values for a and b
10
20
Scanf ret value 2
Hello
1
Printf ret value 9
Formatting Output
• Additional arguments in printf to format as
requested by user:
• %[flags][width][.precision][length]specifier
Formatting Output
Flags Description
- Left-justify within the given field width; Right
justification is the default
+ Forces to precede the result with a plus or
minus sign (+ or -) even for positive numbers.
By default, only negative numbers are
preceded with a -ve sign.
(space) If no sign is going to be written, a blank space
is inserted before the value
0 Left-pads the number with zeroes (0) instead
of spaces, where padding is specified
Formatting Output
Width Description
(number) Minimum number of characters to be printed. If
the value to be printed is shorter than this number,
the result is padded with blank spaces.
.precision Description
.number precision specifies the minimum number of digits
to be written. If the value to be written is shorter
than this number, the result is padded with leading
zeros.
Formatting Output
length Description
h Argument is interpreted as a short int or unsigned
short int (only applies to integer specifiers: i, d, o,
u, x and X).
l argument is interpreted as a long int or unsigned
long int for integer specifiers (i, d, o, u, x and X),
and as a wide character or wide character string
for specifiers c and s.
L argument is interpreted as a long double (only
applies to floating point specifiers: e, E, f, g and G)
Example for Formatting
#include<stdio.h>
main()
{ int a,b;
float c,d;
a=15;
b=a/2;
printf("%d\n", b );
printf("%3d\n", b );
printf("%03d\n", b );
c=15.3;
d=c/3;
printf("%3.2f\n",d);
printf("%7.2f\n",d); }
Output
7
7
007
5.10
5.10
Example for Formatting
Output
:Hello, world!:
Example for Formatting : Hello, world!:
:Hello, wor:
:Hello, world!:
#include<stdio.h> :Hello, world! :
main() :Hello, world!:
{ : Hello, wor:
printf(":%s:\n", "Hello, world!"); :Hello, wor :
printf(":%15s:\n", "Hello, world!");
printf(":%.10s:\n", "Hello, world!");
printf(":%-10s:\n", "Hello, world!");
printf(":%-15s:\n", "Hello, world!");
printf(":%.15s:\n", "Hello, world!");
printf(":%15.10s:\n", "Hello, world!");
printf(":%-15.10s:\n", "Hello, world!");
}
printf(“:%s:\n”, “Hello, world!”); - nothing special happens
printf(“:%15s:\n”, “Hello, world!”); print 15 characters. If
string is smaller then “empty” positions will be filled with
“whitespace.”
printf(“:%.10s:\n”, “Hello, world!”); statement prints the
string, but print only 10 characters of the string.
printf(“:%-10s:\n”, “Hello, world!”); statement prints the
string, but prints at least 10 characters. If the string is
smaller “whitespace” is added at the end.
printf(“:%-15s:\n”, “Hello, world!”); statement prints
the string, but prints at least 15 characters. The string
in this case is shorter than the defined 15 character,
thus “whitespace” is added at the end (defined by the
minus sign.)
printf(“:%.15s:\n”, “Hello, world!”); statement prints
the string, but print only 15 characters of the string. In
this case the string is shorter than 15, thus the whole
string is printed.
Car Loan Problem
• Write a program to help you figure out what your monthly
payment will be, given the car’s purchase price, down
payment, the monthly interest rate, and the time period
over which you will pay back the loan. The formula for
calculating your payment is
payment = iP / (1 - (1 + i)-n )
where P = principal (the amount you borrow)
i = monthly interest rate (1/12 of the annual rate)
n = total number of payments
Total number of payments is usually 36, 48, or 60
(months). Program should then display the amount
borrowed and the monthly payment rounded to two
decimal places.
Car Loan problem
Input Output Logic Involved
Purchase price, Amount Compute Monthly
down payment, borrowed and payment
annual interest EMI = i*P / (1 - (1 + i)-n )
rate and total
number of
payments
Algorithm for Car Loan Problem
• Read input such as Purchase price, down
payment, annual interest rate and total number
of payments from user
• amount_Borrowed = purchase_Price –
down_Payment
• EMI = i*P / (1 - (1 + i)-n )
• Print amount_Borrowed and EMI rounded to
two decimal places
When input is:
400000
100000
10
36
Output is:
Loan Amount 300000.00
Monthly installment 9680.16
Nature of a Solution
• A solution may be classified into acidic, very
acidic, neutral, alkaline or very alkaline based
on its pH value. The nature of the solution is
given by the following table and determined
as shown in the figure:
pH value Nature of Solution
0 to 2 Very acidic
Greater than 2 and less than 7 Acidic
Equal to 7 Neutral
Greater than 7 and less than 12 Alkaline
Greater than 12 Very Alkaline
Nature of a Solution
pH problem
Input Output Alternate Ways
for Solution
pH value of Nature of Compare value
solution solution and make
decision
Key Steps
• Get the pH value of the solution from the user
• Write instructions that will make decision for
nature of solution as per details in the table
• Print the nature of the solution
Partial C code
#include<stdio.h>
void main()
{
float ph_Value; // Declare necessary variables
//Get the ph_Value from the user
scanf(“%d”,&ph_Value);
// Based on ph_Value make decision and print
}
#define statements
• These are preprocessor directives that are used
define constants
• When a value is defined using #define, if there is a
change in value it is easier to make modification
Class of the Ship
• Each ship serial number begins with a letter
indicating the class of the ship. Write a program
that reads a ship’s first character of serial number
and displays the class of the ship.
Nested if Statements
Output
BattleshipCruiserDestroyerFrigateNo match
When input is b
In Lab Practice Problem
The table below shows the normal boiling points of
several substances. Write a program that prompts the
user for the observed boiling point of a substance in °C
and identifies the substance if the observed boiling
point is within 5% of the expected boiling point. If the
data input is more than 5% higher or lower than any of
the boiling points in the table, the program should
output the message Substance unknown.
Substance Normal boiling point
(°C)
Water 100
Mercury 357
Copper 1187
Silver 2193
Gold 2660