0% found this document useful (0 votes)
7 views69 pages

Unit 2

The document covers control statements in C programming, including input/output operations, decision-making statements (if, switch), and looping constructs (for, while, do-while). It explains the syntax and usage of formatted input/output functions like scanf() and printf(), as well as various control flow mechanisms such as break, continue, goto, and return statements. Additionally, it includes examples and flow charts to illustrate the concepts.

Uploaded by

Swapnabit Das
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)
7 views69 pages

Unit 2

The document covers control statements in C programming, including input/output operations, decision-making statements (if, switch), and looping constructs (for, while, do-while). It explains the syntax and usage of formatted input/output functions like scanf() and printf(), as well as various control flow mechanisms such as break, continue, goto, and return statements. Additionally, it includes examples and flow charts to illustrate the concepts.

Uploaded by

Swapnabit Das
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/ 69

CSE234P: COMPUTER PROGRAMMING

Unit-2: Control Statements

Prof. Athulya S
Department of Computer Science and Engineering

Mission Vision Core Values


Christ University is a nurturing ground for an individual’s Excellence and Service Faith in God | Moral Uprightness
holistic development to make effective contribution Love of Fellow Beings | Social Responsibility
to the society in a dynamic environment Pursuit of Excellence
● Managing input and output operations: Reading a
character, writing a character, Formatted Input,
Formatted Output and Decision making and branching:
Decision making with if statement, The if…else
statement, Nesting of if…else statements, The else … if
ladder, The switch statement, The ?: operator, The
Goto statement Looping: The while statement, The do
statement, The for statement, Jumps in Loops
Formatted Input-Output Functions

• scanf() and printf() are the functions used for


performing formatted input and output
• These functions accept a format specification string as
parameters and a list of variables.
• The format specification string is a character
string that specifies the data type of each variable to be
input or output and the size or width of the input and
output.
Formatted Input
Format Data
Description
● For formatted input, scanf() function Specifier Type

is used %d int
used for I/O signed integer
value
Syntax:
%c char Used for I/O character value
scanf (“format”, &num1, &num2,….);
● Here, format is the format %f float
Used for I/O decimal floating-
point value
specification string.
● The function scanf() reads %s string
Used for I/O string/group of
characters
and converts characters from the
standards input depending on the
Used for I/O long signed
format specification string and stores %ld long int
integer value
the input in memory locations
represented by the other arguments unsigned Used for I/O unsigned integer
%u
int value
(num1, num2,….).
Used for I/O fractional or
Example: %lf double
floating data
scanf(“%c%d”, &Grade, &Roll No);
Formatted Output (Continued…)
Format Data
Description
Specifier Type
● For formatted output, printf() function is
used. used for I/O signed integer
%d int
value
Syntax:
%c char Used for I/O character value
printf (“format”, data1, data2,……..);
● Here, format is the format %f float
Used for I/O decimal floating-
point value
specification string.
● String contains a specification beginning Used for I/O string/group of
with the symbol % followed by a %s string characters

character called the conversion character.


Example: Used for I/O long signed
%ld long int
integer value
printf (“%c”, data1);
unsigned Used for I/O unsigned integer
%u
int value
Example:
printf (“Character is:%c\n”, data1); %lf double
Used for I/O fractional or
floating data
Formatted Output

Between the character % and the conversion character, there may be:
• A minus sign: Denoting left adjustment of the data.
• A digit: Specifying the minimum width in which the data is to be output, if the data has
a larger number of characters then the specified width occupied by the output is larger.
If the data consists of fewer characters then the specified width, it is padded to the right
or to the left (if minus sign is not specified) with blanks. If the digit is prefixed with a
zero, the padding is done with zeros instead of blanks.
• A period: Separating the width from the next digit.
• A digit following the period: specifying the precision (number of decimal places for
numeric data) or the maximum number of characters to be output.
• Letter L: To indicate that the data item is a long integer and not an int.
Control Statements

Control Statements

Selection
Iterative Statements Transfer Statements
Statements
I. Selection Statements

● Also called Decision-Making Statements.


● Two Types
1. ‘if’ Statement
a. Simple ‘if’
b. ‘if-else’
c. ‘Nested if-else’
d. ‘else-if ladder’
2. ‘switch’ Statement
1. (a) Simple ‘if’ (Continued…)

Fig. Flow Chart


1. (a) Simple ‘if’

● If the Boolean expression evaluates to true, then the


block of code inside the 'if' statement will be executed.
If the Boolean expression evaluates to false, then the
first set of code after the end of the 'if' statement (after
the closing curly brace) will be executed.
● If we do not provide the curly braces ‘{‘ and ‘}’ after
if(condition) then by default if statement will consider
the first immediately below statement to be inside its
block.
1. (b) ‘if-else’ (Continued…)

Fig. Flow Chart


1. (b) ‘if-else’ (Continued…)

● The if-else statement consists of two blocks, one for


false expression and one for true expression.
● We can use the else statement with the if statement to
execute a block of code when the condition is false.
1. (b) ‘if-else’
Program to find greater between two numbers.
1. (c) ‘Nested if-else’ (Continued…)
1. (c) ‘Nested if-else’ (Continued…)

Fig. Flow Chart


1. (c) ‘Nested if-else’ (Continued…)

● Nested if statements mean an if statement inside


another if statement.

● The outer if statement has two possible paths: one for


when the condition is true, and another for when the
condition is false. If the condition is true, the program
will execute the code inside the block associated with
the outer if statement.

● However, if the condition is false, the program will


skip over that block and move to the else block. Within
the outer if block, there is another if statement, which
1. (c) ‘Nested if-else’
Program to find the greatest among three numbers.
1. (d) ‘else-if ladder’ (Continued…)

Fig. Flow Chart


1. (d) ‘else-if ladder’
If (condition1)
statement1;
else if(condition2)
statement2;
else if(condition3)
statement3;
.
.
.
else if(condition-N)
statement-N;
else
1. (d) ‘else-if ladder’ (Continued…)
1. (d) ‘else-if ladder’ (Continued…)
● The else-if ladder statement is an extension to the if-
else statement. It is used in the scenario where there are
multiple cases to be performed for different conditions.
● In else-if ladder statement, if a condition is true then
the statements defined in the if block will be executed,
otherwise if some other condition is true then the
statements defined in the else-if block will be executed,
at the last if none of the condition is true then the
statements defined in the else block will be executed.
● There are multiple else-if blocks possible.
● It is similar to the switch case statement where the
default is executed instead of else block if none of the
cases is matched.
1. (d) ‘else-if ladder’
2. ‘switch’ Statement (Continued…)

Fig. Flow Chart


2. ‘switch’ Statement (Continued…)
● The switch statement in C is an alternate to else-if ladder
statement which allows us to execute multiple operations for the
different possibles values of a single variable called switch
variable.
● Here, we can define various statements in the multiple cases for
the different values of a single variable.
Rules for switch statement in C language:
i. The switch expression must be of an integer or character type.
ii. The case value must be an integer or character constant.
iii. The case value can be used only inside the switch statement.
iv. The break statement in switch-case is not must. It is optional.
If there is no break statement found in the case, all the cases
will be executed present after the matched case. It is known
as fall through the state of C switch statement.
2. ‘switch’ Statement
Program to print days of a week by taking number of day as input from user.
Program to swap values of variable using third variable.
Program to swap values of variable without using third variable.
Program to perform arithmetic operations using switch/simple calculator

Output:
Program to check whether the entered character is vowel or
consonant.
Quadratic Equation
Quadratic Equation (Continued…)
Program to find the roots and nature of a quadratic equation.
Output
Iterative Statements

● Also called Looping Statements/ Repetition Statements.


● The looping can be defined as repeating the same process
multiple times until a specific condition satisfies.
● Looping statements allow us to execute a statement or a block of
statements multiple times
● Controlled by Boolean expressions
● Three are three types of loops:
○ “for” Loop
○ “while” Loop
○ “do-while” Loop
“for” Loop (Continued…)

● “for” loop in C programming is a repetition control


structure that allows programmers to write a loop that
will be executed a specific number of times.
● “for” loop enables programmers to perform n number
of steps together in a single line.
“for” Loop (Continued…)

● Syntax

● Example
“for” Loop (Continued…)
In for loop, a loop variable is used to control the loop. Firstly we initialize the loop
variable with some value, then check its test condition. If the statement is true then
control will move to the body and the body of for loop will be executed. Steps will
be repeated till the exit condition becomes true. If the test condition will be false
then it will stop.
• Initialization Expression: In this expression, we assign a loop variable or loop
counter to some value. for example: int i=1;
• Test Expression: In this expression, test conditions are performed. If the
condition evaluates to true then the loop body will be executed and then an update
of the loop variable is done. If the test expression becomes false then the control
will exit from the loop. for example, i<=9;
• Update Expression: After execution of the loop body loop variable is updated by
some value it could be incremented, decremented, multiplied, or divided by any
value.
“for” Loop (Continued…)

Fig. “for” Loop Flow Diagram


“for” Loop

Program to print n natural numbers using for loop.

Output:
“while” Loop (Continued…)

● “while” loop does not depend upon the number of


iterations. In “for” loop the number of iterations was
previously known to us but in the “while” loop, the
execution is terminated on the basis of the test
condition. If the test condition will become false then it
will break from the “while” loop else body will be
executed.
● Syntax:
“while” Loop (Continued…)

Fig. “while” Loop Flow Diagram


“while” Loop

Program to print n natural numbers using “while”


loop.

Output:
“do-while” Loop (Continued…)
● The do-while loop is similar to a while loop but the only difference lies in the
do-while loop test condition which is tested at the end of the body. In the do-
while loop, the loop body will execute at least once irrespective of the test
condition.
● Syntax:
“do-while” Loop (Continued…)

Fig. “do-while” Loop Flow


Diagram
“do-while” Loop

Program to print n natural numbers using “do-


while” loop.

Output:
Description of All Types of Loops
(Continued…)
Description of All Types of Loops
Difference in Output using “while” and “do-while” Loop

Output: Output:
Transfer Statements

● Unconditional branching
● Four Types of branching control statements
i. break
ii. continue
iii. goto
iv. return
i. break Statement

● Already used to terminate a switch statement.


● Allows us to jump out of a loop(for, while and do-while loop)
instantly, without waiting to get back to the conditional test.
● The break statement is used with decision making statement
such as if...else.
i. break Statement (Continued…)

Output:
ii. continue Statement

● Skips some statements inside the loop.


● In a loop, the continue keyword causes control to immediately
jump to the next iteration.
ii. continue Statement (Continued…)

Output:
iii. goto Statement
● The C goto statement is a jump statement which is sometimes also referred to
as an unconditional jump statement. The goto statement can be used to jump
from anywhere to anywhere within a function.
● goto is a Keyword and Label is an identifier

● In the above syntax, the first line tells the compiler to go to or jump to the
statement marked as a label. Here, the label is a user-defined identifier that
indicates the target statement. The statement immediately followed after
‘label:’ is the destination statement. The ‘label:’ can also appear before the
‘goto label;’ statement in the above syntax.
iii. goto Statement (Continued…)

● Use of goto statement is highly not suggested.


● The use of goto makes tracing the flow of the program
very difficult.
● The use of the goto statement is highly discouraged as
it makes the program logic very complex.
● Hard to understand and hard to modify the program
● Can be used in rare instances such as exiting from a
deeply nested inner loop to the outermost level
iii. goto Statement (Continued…)


iv. return Statement

● C return statement ends the execution of a function


and returns the control to the function from where it
was called. The return statement may or may not return
a value depending upon the return type of the function.
For example, int returns an integer value, void returns
nothing, etc.
● In C, we can only return a single value from the
function using the return statement and we have to
declare the data type of the return value in the function
definition/declaration.
Pattern Printing: Concept of ‘for’ Loop within ‘for’ Loop

● Write a program in C to print the following


pattern:
Program
● #include <stdio.h>
● int main() {
● int rows, i, j, space;
● printf("Enter the number of rows: ");
● scanf("%d", &rows);
● for (i = 1; i <= rows; i++) {
● // Print leading spaces
● for (space = 1; space <= rows - i; space++) {
● printf(" "); // Two spaces for better pyramid shape
● }
● // Print asterisks
● for (j = 1; j <= 2 * i - 1; j++) {
● printf("* ");
● }
● printf("\n");
● }
● return 0;
●}
Write a program in C to print the following pattern:
Program
Write a program in C to print the following pattern:
Program
Write a program in C to print the following pattern:
Program
Program to Check Prime Number
● 2.2 A Finding area of geometric shapes
● 2.2 B To check the given alphabet is vowel or consonent using switch
2.3 A Finding Prime Numbers (for loop)
2.3 BGenerate Prime numbers from 1 to 100 (Nested For loop)
● switch(ch) switch(ch)
●{ { case 'a’:
● case 'a': printf("Vowel");
● case 'e': break; case 'e':
● case 'i': printf("Vowel");
● case 'o': break; case 'i':
● case 'u': printf("Vowel"); break;
● case 'A': case 'o': printf("Vowel");
● case 'E':
● case 'I':
● case 'O':
● case 'U':
● printf("Vowel");
● break;
default: printf("Consonant");

●}

You might also like