Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

Module 2

The document provides an overview of control statements in C programming, focusing on decision-making constructs such as if, if-else, nested if, and switch statements. It explains the syntax, usage, and flow of these constructs, along with examples and exercises for practice. Additionally, it covers looping constructs like for, while, and do-while loops, emphasizing their purpose in executing code repeatedly based on conditions.

Uploaded by

tusharsurti6
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Module 2

The document provides an overview of control statements in C programming, focusing on decision-making constructs such as if, if-else, nested if, and switch statements. It explains the syntax, usage, and flow of these constructs, along with examples and exercises for practice. Additionally, it covers looping constructs like for, while, and do-while loops, emphasizing their purpose in executing code repeatedly based on conditions.

Uploaded by

tusharsurti6
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 76

‘C’ Programming

By Asst. Prof. Sudeshna Baliarsingh


Information & Technology Dept.
KJSIT, Mumbai
1. Learning objectives
Understanding meaning of a statement and statement block

Learn about decision type control constructs in C and the way these are
used

Learn about looping type control constructs in C and the technique of


putting them to use

Learn the use of special control constructs such as goto, break, continue,
and return

Learn about nested loops and their utility


2. Control Statements include
3. Program Control Statements/Constructs in ‘C’
4.1. Relational 4.2. Equality and
Operators Logical Operators
To Specify Symbol Used To Specify Symbol Used
less than <
Equal to ==
greater than >
Not equal to !=
less than or equal to <=
greater than or equal >= Logical AND &&
to
Logical OR ||

Negation !
Points to Note
If an expression, involving the relational operator, is true, it is given a value
of 1. If an expression is false, it is given a value of 0. Similarly, if a numeric
expression is used as a test expression, any non-zero value (including
negative) will be considered as true, while a zero value will be considered
as false.

Space can be given between operand and operator (relational or logical)


but space is not allowed between any compound operator like <=, >=, ==,
!=. It is also compiler error to reverse them.

a == b and a = b are not similar, as == is a test for equality, a = b is an


assignment operator. Therefore, the equality operator has to be used
carefully.

The relational operators have lower precedence than all arithmetic


operators.
Decision Making in C (if , if..else, Nested if, if-else-if )

The conditional statements (also known as decision


control structures) such as if, if else, switch, etc. are used for
decision-making purposes in C programs.

They are also known as Decision-Making Statements and


are used to evaluate one or more conditions and make the
decision whether to execute a set of statements or not.

These decision-making statements in programming languages


decide the direction of the flow of program execution.
1. if in C
The if statement is the most simple decision-making statement. It is used to decide
whether a certain statement or block of statements will be executed or not i.e if a
certain condition is true then a block of statements is executed otherwise not.

Syntax of if Statement
if(condition)
{
// Statements to execute if
// condition is true
}
Here, the condition after evaluation will be either true or false. C if statement
accepts boolean values – if the value is true then it will execute the block of
statements below it otherwise not.

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
How does an if Statement Work in C?

If statement allows to evaluate the test expression first and then,


building upon whether the condition of the expression is
true(non-zero) or false(zero), it shifts the control to a particular
block of statement. This point of the program has two paths to
follow, one path for the true condition and the other path for the
false.

If a certain condition is true then it will execute a block of the


statement below it otherwise not.
Flowchart of if Statement
How it works (If Statement)
Output:
Hey there

As the condition
present in the if
statement is false. So,
the block below the if
statement is not
executed.
Example 1: C Program to check whether the number is even or odd.
Output 1

Enter an integer: -2
You entered -2.
The if statement is easy.

Output 2

Enter an integer: 5
The if statement is
easy.
2. if-else in C
The if statement alone tells us that if a condition is true it will
execute a block of statements and if the condition is false it
won’t.

But what if we want to do something else when the condition is false?

Here comes the C else statement.


We can use the else statement with the if statement to execute a
block of code when the condition is false.

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


expression and one for true expression.
Syntax of if else in C
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
Flowchart of
if-else Statement
Output
i is greater than 15

The block of code


following the else
statement is executed as
the condition present in
the if statement is false.
Program that checks if a number is positive, negative, or zero using the
if-else statement:
Output:

For an input of 5, the


output would be:

Enter an integer: 5
The number is positive.

For an input of -3, the


output would be:

Enter an integer: -3
The number is negative.

For an input of 0, the


output would be:

Enter an integer: 0
The number is zero.
3. Nested if-else in C
A nested if in C is an if statement that is the target of another if
statement.

Nested if statements mean an if statement inside another if


statement.

Yes, C allow us to nested if statements within if statements, i.e, we


can place an if statement inside another if statement.
Syntax of Nested if-else
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
else
{
// Executes when condition2 is false
}
Flowchart of
Nested
if-else
Example 1 : Check if three numbers are equal
Input 1

134

Output 1

No

Input 2

111

Output 2

Yes
Output

i is smaller than 15
i is smaller than 12
too
4. if-else-if Ladder in C
The if else if statements are used when the user has to decide among
multiple options.

The C if statements are executed from the top down.

As soon as one of the conditions controlling the if is true, the statement


associated with that if is executed, and the rest of the C else-if ladder is
bypassed.

If none of the conditions is true, then the final else statement will be
executed.

if-else-if ladder is similar to the switch statement.


Syntax of if-else-if Ladder

if (Condition1)
{
Statement1;
}
else if(Condition2)
{
Statement2;
}
.
.
.
else if(ConditionN)
{
StatementN;
}
else
{
Default_Statement;
}
Flowchart of if-else-if Ladder
Working of if else if ladder statement:

In the above syntax of if-else-if, if the Condition1 is TRUE then the


Statement1 will be executed and control goes to next statement in the
program following if-else-if ladder.

If Condition1 is FALSE then Condition2 will be checked, if Condition2


is TRUE then Statement2 will be executed and control goes to next
statement in the program following if-else-if ladder.

Similarly, if Condition2 is FALSE then next condition will be checked


and the process continues.

If all the conditions in the if-else-if ladder are evaluated to FALSE,


then Default_Statement will be executed.
C program to find largest from three numbers given by user to explain working of
if-else-if statement or ladder
C program to find largest from three numbers given by user to explain working of
if-else-if statement or ladder
#include <stdio.h>
int main()
{
int a, b, c;
printf(“\nEnter the three numbers”);
scanf(“%d %d %d”, &a, &b, &c);
if(a > b)
if(a > c)
printf(“%d”, a);
else
printf(“%d”, c);
else
if(b > c)
printf(“%d”, b);
else
printf(“%d”, c);
return 0;
}
C program to find largest from three numbers given by user to explain working of
if-else-if statement or ladder
C program to find largest from three numbers given by user to explain working of
if-else-if statement or ladder Explanation:
Explanation
During the first run i.e. Run 1, numbers given by user are 12, 33, and -17 respectively. These numbers are
stored in variable a, b and c i.e. a gets 12, b gets 33 and c gets -17. In the if-else-if ladder first condition is
a>b && a>c. So, what happens here? Lets break this condition!

Putting values of a, b and c condition becomes 12>33 && 12>-17, Right? In the first part of condition, we
have 12>33. This is checking, is 12 greater than 33? Answer is NO. So, 12>33 evaluates to FALSE.
Similarly, In the second part of condition, we have 12>-17. This is checking, is 12 greater than -17?
Answer is YES. So, 12>-17 evaluates to TRUE. Results of these two conditions are combined by logical
AND opeartor. So, finally FALSE && TRUE is evaluated. Since logical AND opeartors gives FALSE when
one of the operand is FALSE, so FALSE && TRUE evaluates to FALSE.

When condition in if is FALSE then it prevents execution of printf("Largest = %d", a); and checks for
another condition. Another condition here is b>a && b>c. Which is 33>12 && 33>-17 and evaluates to
TRUE && TRUE, which in turn evaluates to TRUE. So b>a && b>c evaluates to TRUE and hence
printf("Largest = %d", b); is executed printing Largest = 33. And then execution goes to next statement
neglecting else block where it executes retun(0) which is the last statement in the program and program
execution comes to end.
Exercise<<< for IF Else Programming:
1. Write a c program to print weekday based on given
number by using ladder(if-else-if statement),
2. Write a C program to check whether a number is
negative, positive or zero.
3. Write a C program to check whether a character is
uppercase or lowercase alphabet.
4. Write a C program to find all roots of a quadratic
equation.
5. Write a C program to check whether the triangle is
equilateral, isosceles or scalene triangle.
6. Write a C program to check whether a number is even or
odd.
Switch Statement in C
prize wheel game

The wheel will be divided into


segments, each holding a prize, and
there will also be a pointer. The game
master will rotate the wheel, and when
it comes to a stop, the pointer will tell
you the prize you get to take home.

Now, imagine you have been asked to


create a program, you will be given
the color as the input, and you will
have to print the prize the user has
won.
Switch Statement in C
Switch case statement evaluates a given expression and based on the
evaluated value(matching a certain condition), it executes the statements
associated with it. Basically, it is used to perform different actions based on
different conditions(cases).

Switch case statements follow a selection-control mechanism and allow a value to


change control of execution.
They are a substitute for long if statements that compare a variable to several
integral values.
The switch statement is a multiway branch statement. It provides an easy way to
dispatch execution to different parts of code based on the value of the
expression.
In C, the switch case statement is used for executing one condition from
multiple conditions. It is similar to an if-else-if ladder.
Syntax of switch Statement in C
switch(expression) Note ;The expression in
{ the syntax can be
case value1: Arithmetic, Relational or
//code to be executed; Logical expression.
break; //optional
case value2:
//code to be executed;
break; //optional
......

default:
//code to be executed if all cases are not
matched;
}
Rules of the switch case statement
Following are some of the rules that we need to follow while using the switch
statement:

● In a switch statement, the “case value” must be of “char” and “int” type.
● You can't use two case labels with the same value. Duplicate case values
would throw an error.
● You can't define ranges within a case statement, nor can you use a single
case label for more than one value. A case label can hold only one value.
● There can be one or N number of cases.
● The values in the case must be unique.
● Each statement of the case can have a break statement. It is optional.
● The default Statement is also optional.
Rules of the switch case statement
Break in switch case

This keyword is used to stop the execution inside a switch block.


It helps to terminate the switch block and break out of it.

When a break statement is reached, the switch terminates, and


the flow of control jumps to the next line following the switch
statement.

The break statement is optional. If omitted, execution will


continue on into the next case.

The flow of control will fall through to subsequent cases until a


break is reached.
How switch Statement Work?
The working of the switch statement in C is as follows:

Step 1: The switch variable is evaluated.


Step 2: The evaluated value is matched against all the present cases.
Step 3A: If the matching case value is found, the associated code is
executed.
Step 3B: If the matching code is not found, then the default case is
executed if present.
Step 4A: If the break keyword is present in the case, then program
control breaks out of the switch statement.
Step 4B: If the break keyword is not present, then all the cases after
the matching case are executed.
Step 5: Statements after the switch statement are executed.
How switch Statement Work?

NOte:

It is important to note that the switch statement


compares the result of the given expression with the
value provided on the case statements sequentially.

So it is necessary to always define the default statement


at the end of the switch statement because all the case
statements defined under the default statement will
never get executed.
Example of
switch case

Output
Case 1 is
Matched.
Example of switch case

without break

Output
Case 2 is executed.
Case 3 is executed.Case 4 is
executed.
Output
The day with
number 2 is
Tuesday
A simple
calculator by
Switch Case:

Output
Enter first number = 6
Enter second number = 7
Choose operator to
perform operations = +
Result: 6 + 7 = 13.000000
A simple calculator by
Switch Case:
2nd Approach

Output

Enter an operator (+, -, *,): *


Enter two operands: 1.5
4.5
1.5 * 4.5 = 6.8
For loop, While Loop ,Do While Loop

Loops in programming are used to repeat a block of code until the specified
condition is met.

A loop statement allows programmers to execute a statement or group of


statements multiple times without repetition of code.
There are mainly two types of loops in C Programming:
1. Entry Controlled loops: In Entry controlled loops the test condition is checked before entering
the main body of the loop. For Loop and While Loop is Entry-controlled loops.
2. Exit Controlled loops: In Exit controlled loops the test condition is evaluated at the end of the
loop body. The loop body will execute at least once, irrespective of whether the condition is true
or false. do-while Loop is Exit Controlled loop.
Syntax of for loop C

The initialization statement states the starting condition


for the loop. It is run only once. As long as the semicolon
appears, we aren’t required to put a statement here.

The condition statement is used to control the flow of


execution of the loop based on some conditions. If this
statement is not declared properly, it may lead to an
infinite loop.

Finally, the update statement is used to update the value


of loop control variables. This statement may even be left
blank while running the loop.
Output
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
NOTE:

They both increment the number. ++i is equivalent to i = i + 1.

i++ and ++i are very similar but not exactly the same. Both increment the
number, but ++i increments the number before the current expression is
evaluted, whereas i++ increments the number after the expression is
evaluated.

int i = 3;
int a = i++; // a = 3, i = 4
int b = ++a; // b = 4, a = 4
For the case of the company wanting to calculate their salary and bonus of the their
employees

Logic:: Imagine a company maintains an array salary that contains the salaries
of its employees that they should receive every month. During the festive
months of November-December, the company happens to decide to give each
employee a bonus of 15% their salary. Hence, the company will have to create
a new array updated Salary that contains the salaries to be given to their
employees that have their bonuses updated.

To do this, the tech team will use a for loop to first calculate the salary+bonus
of each employee, and then update the new array with this sum.

How this occurs, is that a loop is run on the array salary where each element of
the array is appended, the bonus is calculated using the formula (0.15 *
salary), and then is added to the original salary. This sum is then appended
into the new array updatedSalary where it is stored in the same position as the
For the case of the company wanting to calculate their salary and bonus of the their
employees

OUTPUT:

15000
30000
22500
18000
28500
Multiplication Table Up to 10 using For Loop
Forms of for loop
A) NO INITIALIZATION:
Initialization can be skipped as shown below:

int x = 10;
for( ; x < 50; x++)

B) NO UPDATION:
We can run a for loop without needing an updation in the
following way:
C) NO INITIALIZATION AND UPDATE
STATEMENT:
int num;
We can avoid both initialization and update
for (num = 50; num < 60; )
statements too!
{ int x = 20;
num++; for (; x < 40; )
} {
x++;
}
While Loop
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: How while loop works?
● The while loop evaluates the testExpression
initialization_expression; inside the parentheses ().
● If testExpression is true, statements inside the
while (test_expression) body of while loop are executed. Then,
{ testExpression is evaluated again.
// body of the while ● The process goes on until testExpression is
loop evaluated to false.
● If testExpression is false, the loop terminates
update_expression; (ends).
}
Flowchart of while loop:
Syntax:

initialization_expression;

while (test_expression)
{
// body of the while
loop

update_expression;
}
Here, we have initialized i to 1.
Output
When i = 1, the test expression i <= 5 is
1
2 true. Hence, the body of the while loop is
3 executed. This prints 1 on the screen and
4 the value of i is increased to 2.
5
Now, i = 2, the test expression i <= 5 is
again true. The body of the while loop is
executed again. This prints 2 on the screen
and the value of i is increased to 3.

This process goes on until i becomes 6.


Then, the test expression i <= 5 will be
false and the loop terminates.
do-while Loop
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.
do-while Loop
Syntax:
initialization_expression;
do
{
// body of do-while loop

update_expression;

} while (test_expression);
Output
Hello World
Output

Enter a number: 1.5


Enter a number: 2.4
Enter a number: -3.4
Enter a number: 4.2
Enter a number: 0
Sum = 4.70
EXercise:

Let's suppose, you have set an alarm clock to buzz at 05:00AM in the morning
(body of the loop). It will go off at 05:00AM in the morning i.e. at least once,
and suppose the condition at the end of the loop is that if you have snoozed
your alarm or not. If you have snoozed (i.e. true), it will buzz again after a
certain time and it will not buzz if you have set the alarm off without snoozing it
(i.e. false).
Output

This loop will run forever.


This loop will run forever.
This loop will run forever.
…….
Types of Jump Statements in C 1. break in C
There are 4 types of jump statements in C: The break statement exits or terminates the
loop or switch statement based on a certain
1. break condition, without executing the remaining
2. continue code. Syntax of break in C
3. goto break;
4. return

Uses of break in C

Note: If the break statement is used inside an inner loop


● To come out of the loop.
● To come out from the
in a nested loop, it will break the inner loop without
nested loops. affecting the execution of the outer loop.
● To come out of the
switch case. Note:The break statement is also used inside the
switch statement to terminate the switch statement
after the matching case is executed.
Output
1 2 3 4 5 Loop exited.

Explanation:

Loop Execution Starts and goes normally till i = 5.


When i = 6, the condition for the break statement
becomes true and the program control immediately
exits the loop.
The control continues with the remaining
statements outside the loop.
2. Continue in C
The continue statement in C is used to skip the remaining code after the continue
statement within a loop and jump to the next iteration of the loop. When the continue
statement is encountered, the loop control immediately jumps to the next iteration, by
skipping the lines of code written after it within the loop body.

Syntax of continue in C
continue;

Note: Just like break, the continue statement also


works for one loop at a time.
Output
Executing iteration 0
Executing iteration 1
Skipping iteration 2
Executing iteration 3
Executing iteration 4
Explanation: The for loop iterates
from 0 to 4. Inside the loop, we
check if i is equal to 2. If the
condition is true, the continue
statement is executed, and it skips
the remaining code within the loop
for that iteration. If the condition is
false, the code proceeds normally.

Note: While using continue in loop,


we have to make sure that we put
the continue after the loop variable
updation or else it will result in an
infinite loop.
3. Goto Statement in C
The goto statement is used to jump to a specific point from anywhere in a function.
It is used to transfer the program control to a labeled statement within the same
function.

Syntax of goto Statement

goto label;
.
.
label:
//code
Check if a number is odd or even using goto statement.
Output
26 is even

Note: The use of goto is generally


discouraged in the programmer’s
community as it makes the code complex
to understand.
4. Return Statement in C
The return statement in C is used to terminate the execution of a function and return a value to the caller. It is
commonly used to provide a result back to the calling code.

return expression;

Result: 8
KJSIT MUMBAI
Exercises:
1. Write a c program to print table of given number using for loop.
2. Write a C program to display a pattern like a right angle triangle with a number.
The pattern like :

1
12
123
1234

3.
Write a program in C to display n terms of natural numbers and their sum.
Test Data : 7
Expected Output :
The first 7 natural number is :
1234567
The Sum of Natural Number upto 7 terms : 28
4. Write a program in C to display the first 10 natural numbers.
Expected Output :
1 2 3 4 5 6 7 8 9 10

You might also like