You are on page 1of 70

Module – 1

C Programming Fundamentals

Dr.Jayanthi R
SCOPE
Experiments -1
• Programs using basic control structures, branching
and looping

2
Content
• Variables
• Reserved Words
• Data Types
• Operators – Operator Presedence
• Expressions
• Type Conversions
• I/O statements
• Branching and Looping – If – else,nested if,if-else
ladder,Switch statement,goto statement
• Loop-for ,while and do ..while
• Break and continue statements.
3

Control Structure
Control Statements are the statements that alter the flow of execution and provide
better control to the programmer on the flow of execution.
• Control statements are used to decide the program execution order based on some
conditions.
• It is also called decision making statements.
• A program executes from top to bottom except when we use control statements, we
can control the order of execution of the program, based on logic and values.
• In C, control statements can be divided into the following three categories:
• Selection Statements or Branching statements (ex: if-else, switch case, nested if-
else, if-else ladder)
• Iteration Statements or looping statements (ex: while loop, do-while loop, for-
loop)
• Jump Statements (ex: break, continue, return, goto).

4
Control Structure
What are Selection Statements in C?
• Selection statements allow you to control the flow of program execution
on the basis of the outcome of an expression or state of a variable
known during run time.
Selection statements can be divided into the following categories:
• if-else statements
• switch statements
if-else statements
• if...else is a branching statement.
• It is used to take an action based on some condition.
• For example - if user inputs valid account number and pin, then allow
money withdrawal.
• if statement works like "If condition is met, then execute the task".
• If is used to compare things and take some action based on the
comparison.
• Relational and logical operators supports this comparison.
• If statement perform action based on boolean expression true or false. 5

Control Structure
C language supports three variants of if statement
1. Simple if statement
2. If …else and if …else…if statement
3. Nested if …else Statement
Simple if statement
Syntax of If statement

• In above syntax if boolean expression evaluates true, then


statements inside if body executes otherwise skipped. 6
Note: Here, the block of statements executes only when the condition is true. And
if the condition is false, then it will skip the execution of the statements.
7
Control Structure
Example: To check whether the number is greater than 10
• We will take the number from the user and then we will check whether
that number is greater than 10 or not using If Statement.
#include<stdio.h>
int main()
{
int number;
printf("Enter a Number : ");
scanf("%d", &number);
if(number > 10)
{
printf("%d is greater than 10 \n", number);
printf("End of if block \n");
}
printf("End of Main Method");
return 0;
} 8
Control Structure
• In the above program, inside the main method, we are declaring one
integer variable i.e. number, and then we are taking the input from the
user by using the scanf function and storing it in the number variable.
• After reading the input we are checking whether the given
number is greater than 10.
• If the number > 10, then if the condition is true and, in that
case, we are executing the two statements that are present
inside the block else if the condition is false, then the if block
statements will be skipped and the last printf statement gets
executed.
For example,
1. We take 15 as an input, 15 > 10 means the condition is true, then the
if block statement gets executed.
2. We take 5 as an input, 5 > 10 means the condition is false, then the if
block statements will be skipped

9
Control Structure

10
Control Structure
Single vs compound statement inside if body
• If there is only single statement inside if body, then
braces { } are optional.
• However, braces after if statement is mandatory, when
body of if contains more than one statement.
• So, you can write an if condition in two ways.

11

Control Structure
When you want to perform single task inside if.
For example - If it is Saturday or Sunday, then employee should not login
today.
• If a student got more than 80 marks, then he passed with distinction.
• In such situations you can ignore braces {}.
If Statement without Curly Braces in C Language
• In the declaration of if block if we do not specify statements using blocks ({})
nothing but braces, then only the first statement will be considered as the if
block statement.
#include<stdio.h>
int main()
{
int number;
printf("Enter a Number : ");
scanf("%d", &number);
if(number > 10)
printf("%d is greater than 10 \n", number);
printf("End of Main Method");
12
return 0;
Control Structure
• As you can see, in the above example, we have not
specified the curly braces to define the if block.
• In this case, only the first statement will be
considered as the if block statement.
• The second statement will not be a part of the if block.
• For better understanding, please have a look at the below
image. The statement which is in red color will belong to the if
block and the statement which is in the black color do not
belong to the if block.

13
Control Structure

• So, when you execute the above program, irrespective of the condition,
the black statement is always going to be executed as it is not part of the
if block.
• The red statement is only executed when if the condition is true.

14
Control Structure
Example program of if statement
• Write a program to input user age and check if he is eligible to vote in India
or not. A person in India is eligible to vote if he is 18+

15
If Else Block in Programming Language
• The If-Else block is used to provide some optional
information whenever the given condition is FALSE in the if
block.
• That means if the condition is true, then the if block
statements will execute, and if the condition is false, then the
else block statement will execute.
• Following is the syntax to use IF ELSE block in most of the
programming languages.

16
If Else Block in Programming Language
• Note: only one block of statement i.e. either if block or else
block is going to be executed at a time.
• So, if the condition is TRUE if block statements get executed
and if the condition is FALSE, else block statements get
executed.
Is it mandatory to use else block?
• No, it is not mandatory to use else block.
• It is an optional block.
• If you want to provide any information when the condition is
failed, then you need to use this optional else block

17
If Else Block in Programming Language
Flow Chart of If-Else Block:
• The flow chart of the if-else block is almost similar to the if block.
• In this case, when the condition is true, the if block statements get executed
and when the condition is false, the else block statements get executed.

18
If Else Block in Programming Language
Points to Remember:
• The ‘if’ control statement allows you to check the validity of a
certain condition and perform required operations depending on
the condition.
• If the condition followed by the ‘if’ keyword holds True, the
code is written inside the braces of the ‘if’ statement will be
executed, otherwise the program control will skip the loop
execution and continue with the remaining program.
• ‘if’ statement is generally accompanied by the ‘else’ block which
lets the compiler know about actions to be performed if the
condition following the ‘if’ statement is False.
Note: In C Programming Langauge, if and else are reserved
words. The expressions or conditions specified in the if block can
be a Relational or Boolean expression or condition that evaluates
to a TRUE(1) or FALSE(0).
19
If Else Block in Programming Language
Write a Program to check whether a number is even or odd.
• We will take the input number from the user and then we will check whether
that number is even or odd using the if-else statement.
#include<stdio.h>
int main()
{
int number;
printf("Enter a Number : ");
scanf("%d", &number);
if(number % 2 == 0)
{
printf("%d is an Even Number", number);
}
else
{
printf("%d is an Odd Number", number);
}
return 0;
20
}
• In the above program, inside the main method, we are declaring
one integer variable i.e. number.
• Then we are reading input from the user using the scanf
function
• Then storing the value in the address of the number variable.
• After reading the input we are checking whether the given
number is even or odd.
• An Even number is a number that is divisible by 2.
• If number % 2 equals 0, then the if condition is true and, in
that case, we are printing a message that it is an even number
and if the condition is false then we are printing a message
that it is an odd number.

21
For example,
• We take 16 as an input, 16%2 == 0 means the condition is
true, then the if block statement gets executed. And the output
will be 16 is an Even Number.
• We take 13 as an input, 13%2 == 0 means condition is false,
then the else block statements get executed. And the output will
be 13 is an Odd Number.

22
If and Else Block without Curly Braces in C Programming
Language.
• In the declaration of if block or else block if we do not specify
statements using blocks ({}) nothing but braces, then only the
first statement will be considered as the if block or else block
statement.
#include<stdio.h>
int main()
{
if(1 == 1)
printf("Hi\n");
else
printf("Hello\n");
printf("Bye\n");
return 0;
}
23
• As you can see, in the above example, while creating the if and
else block we have not specified the curly braces.
• So, in this case, the first printf statement will belong to the if
block.
• After the else statement, we have two printf statements.
• Here, the printf statement which printing the Hello message
will belongs to the else block only.
• The next printf statement which printing the message bye will
not belong to else block.
• Now, if you execute the above program then you will get the
following output.

24
• Now, if we replace the Hello statement in the if block, then an
ERROR message will be displayed.
• The reason is, “not more than one statement gets executed
without braces”.
• One statement will execute inside the if block.
• If we want to execute more than one statement then you
should use braces and all the statements will be inside the
braces.
#include<stdio.h>
int main()
{
if(1 == 1)
printf("Hi\n");
printf("Hello\n");
else
printf("Bye\n");
return 0;
25
}
Nested If-Else Statement in C
• When an if-else statement is present inside the body of
another “if” or “else” then this is called nested if-else.
• Nested ‘if’ statements are used when we want to check for
a condition only when a previous dependent
condition is true or false.
• C allows us to nested if statements within if statements,
i.e. we can place an if statement inside
another if statement..
What is Nested If block?
• Nested if block means defining if block inside another if
block.
• We can also define the if block inside the else blocks.
• Depending on our logic requirements, we can use nested
if block in n number of ways.
• You can define nested if block at many levels. 26
Nested If-Else Statement in C
Syntax:

27
Nested If-Else Statement in C
• we will take one example and try to understand the flow chart. Here
we have an if-else block inside the if block, as well as, if-else block
inside the else block.

28
How it will Execute the flow?
• First, it will check the first if condition i.e. the outer if condition and if it
is true, then the outer else block will be terminated. So, the control
moves inside the first or the outer if block.
• Then again it checks the inner if condition and if the inner if condition is
true, then the inner else block gets terminated. So, in this case, the
outer if and inner if block statements get executed.
• Now, if the outer if condition is true, but the inner if condition is false,
then the inner if block gets terminated. So, in this case, the outer if and
inner else block statements get executed.
• Now, if the outer if condition is false, then the outer if block gets
terminated and control moves to the outer else block.
• Inside the outer else block, again it checks the inner if condition, and if
the inner if condition is true, then the inner else block gets terminated. So,
in this case, the outer else and inner if block statements get executed.
• Now, if the outer if condition is false as well as the if condition inside the
outer else blocks also failed, then the if block gets terminated. And in
this case, the outer else and inner else block statements get executed.
• This is how statements get executed in Nested if. Now we will see the
flow chart of nested if blocks.
29
Flow chart of Nested If Block in C Programming Language:

30
Flow chart of Nested If Block in C Programming Language:
• First, it will check the outer if condition and if the outer if condition is
true, then the control come inside and it will check the inner.
• if condition, and if the inner if condition is true, then the outer if
block statements and inner if block statements get executed. And
after execution, it will come to end.
• Suppose, the outer if condition is true but the inner if condition is
failed, then the outer if block statements and the inner else block
statement get executed. And once the statement gets executed, it will
come to end.
• Suppose, the outer if condition is failed, then the control directly
comes to the else block and checks the inner if condition. And
again, for the inner if condition two options are there.
• If the inner if condition is true, then it will execute the
outer else block and inner if block statement, and if the
inner if condition is false, then it will execute the outer
else block and inner else block statements and then
comes to end.
31
#include <stdio.h>
int main()
{
int i = 10;
if (i == 10)
{
if (i < 15) // First if statement
printf("i is smaller than 15\n"); // Nested - if statement
// Will only be executed if statement above is true.
if (i < 12)
printf("i is smaller than 12 too\n");
else
printf("i is greater than 15");
}
return 0;
}

32
Ladder if-else statements in C:
• In Ladder if-else statements one of the statements will be
executed depending upon the truth or falsity of the
conditions.
• if condition1 is true then Statement 1 will be executed and
so on but if all conditions are false then Statement 3 will be
executed.
• The C if statements are executed from the top down.
• 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 are true, then the final else
statement will be executed.

33
34
Syntax to use Ladder if-else statements in C:

35
Output: i is 20 36
Switch Statements in C
• The switch is a keyword, by using the switch keyword we
can create selection statements with multiple blocks.
• Multiple blocks can be constructed by using a “case”
keyword.
• Switch case statements are a substitute for long if
statements that compare a variable to several integral
values.
• The switch statement is a multi-way branch statement.
• It provides an easy way to dispatch execution to different
parts of code based on the value of the expression.
• The switch is a control statement that allows a value to
change control of execution.

37
Switch Statements in C
Rules for switch statement in C:
1.The expression provided in the switch should result in a constant
value otherwise it would not be valid.
2.Duplicate case values are not allowed.
3.The default statement is optional.
4.Even if the switch case statement does not have a default statement,
it would run without any problem.
5.The break statement is used inside the switch to terminate a statement
sequence.
6. When a break statement is reached, the switch terminates, and the flow
of control jumps to the next line following the switch statement.
7.The break statement is optional.
8.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.
9.Nesting of switch statements is allowed, which means you can have
switch statements inside another switch.
10.However nested switch statements should be avoided as it makes the
program more complex and less readable.
38
Switch Statements in C

39
40
Syntax of switch statements in C:

When do we need to go for a switch statement?


• When there are several options and we have to choose
only one option from the available options depending on
a single condition then we need to go for a switch
statement.
• Depending on the selected option a particular task can be
performed.
41
Syntax of switch statements in C:

When do we need to go for a switch statement?


• When there are several options and we have to choose
only one option from the available options depending on
a single condition then we need to go for a switch
statement.
• Depending on the selected option a particular task can be
performed.
42
Program to understand switch statement in C:

Output: Choice is 2

43
What is the difference between nested if-else and switch statements?

44
What will be the output in the below program?
#include <stdio.h>
int main()
{
int i;
i = 3;
switch(i)
{
case 1:
printf("A");
break; Output: CB
case 3:
printf("C");
case 2:
printf("B");
break;
default:
printf("D");
}
return 0;
}

45
• This is because whenever we are working with switch statements
randomly we can create the cases i.e. in any sequences it can be
created. I
• n order to execute the switch block, it can be executed all cases
in sequence from the matching case onwards until it finds the
break statement.

46
Points Remember when working with C Switch Statement:
1. When we are working with the switch statement at the time of compilation
switch condition/expression return value will match with case constant value.
2. At the time of execution if the matching case occurs then control will pass to
correspondent block, from matching case up to break everything will be
executed, if the break does not occur then including default all cases will be
executed.
3. At the time of execution if the matching case does not occur then control will
pass to default block.
4. Default is a special kind of case that will be executed automatically when the
matching case does not occur. Using default is always optional, it is
recommended to use when we are not handling all cases of the switch
block.
5. When we are working with the switch it required expression or condition as
a type of integer only.

47
While Loop in C
What is looping?
• The process of repeatedly executing a statement or group of
statements until the condition is satisfied is called looping.
• In this case, when the condition becomes false the execution of the
loops terminates.
• The way it repeats the execution of the statements will form a circle
that’s why iteration statements are called loops.

• While we are working with a while loop, first we need to check the
condition, if the condition is true then control will pass within the body if
it is false the control pass outside the body.
• When we don’t know the exact iteration count or the loop count,
we should use while loop.
• In other words, if iteration count depends on the input, we should
use while loop 48
While Loop in C

49
While Loop in C
Enter a number and print the Fibonacci series up to that number using a
while loop.
#include <stdio.h>
int main ()
{
int i, n, j, k;
printf ("Enter a Number : ");
scanf ("%d", &n);

i = 0;
j = 1;
printf ("%d %d ", i, j);
k = i + j;
while (k <= n)
{
printf (" %d", k);
i = j;
j = k;
k = i + j;
}
50
return 0;
Nested While Loop in C Programming Language
• Writing while loop inside another while loop is called nested while loop
or you can say defining one while loop inside another while loop is
called nested while loop.
• That is why nested loops are also called “loop inside the loop”. There
can be any number of loops inside one another with any of the three
combinations depending on the complexity of the given problem.
• In implementation when we need to repeat the loop body itself n
number of times then we need to go for nested loops.
• Nested loops can be designed up to 255 blocks.
Syntax:

51
Note: In the nested while loop, the number of iterations will be equal
to the number of iterations in the outer loop multiplied by the number of
iterations in the inner loop.
• Nested while loops are mostly used for making various pattern
programs like number patterns or shape patterns.
Execution Flow of Nested While Loop in C Programming Language:
• The outer while loop executes based on the outer condition and the inner
while loop executes based on the inner condition.
• First, it will check the outer loop condition and if the outer loop condition
fails, then it will terminate the loop.
• Suppose if the outer loop condition is true, then it will come inside, first, it will
print the outer loop statements which are there before the inner loop. Then it
will check the inner loop condition. If the inner while condition is true, then
the control move inside and executes the inner while loop statements. After
execution of inner while loop statements, again, it will check the inner while loop
condition because it is a loop and as long as the condition is true, it will repeat
this process.
• Once the inner while loop condition fails, then the control moves outside and
executes the statements which are present after the inner while loop. Once it
executes then, again it will go and check the outer while loop condition. And if it
is true, then it will again execute the same process. So, when the loop will
terminate means when the outer while loop condition becomes false 52
53
Summary
• The flow will start and first, it will check the outer while
loop condition.
• And if the outer while loop condition failed, then it will come
to end.
• Suppose, the outer loop condition is true, then it will first
execute the outer while loop statements if any. After
execution of Outer while loop statements, it will check the
inner while loop condition. For the inner while loop
condition, it will also check for true and false.
• Suppose, the inner while loop condition is true, then inner
while loop statements are executed.
• After executing the inner while loop statements, again, it will
check the inner while loop condition and this inner loop
execution process will repeat as long as the inner while loop
condition is true.
• If the inner while loop condition is false, then the remaining
outer loop statements are executed.
• Once, the outer loop statements are executed, then again, it
will come and check the outer while condition.
• This is the flow of the nested while loop. 54
Write a C program to print the following format

55
Write a C program to print the following format

56
Write a C program to print the following format

57
Do While Loop in C Program with Examples
• The do-while loop is a post-tested loop.
• Using the do-while loop, we can repeat the execution of
several parts of the statements.
• The do-while loop is mainly used in the case where we need to
execute the loop at least once.
• The do-while loop is mostly used in menu-driven programs
where the termination condition depends upon the end-user.

58
Syntax to use Do While Loop in C

Example
#include <stdio.h>
int main()
{
int j=0;
do
{
printf("Value of variable j is: %d\n", j);
j++;
}while (j<=3);
return 0; 59
}
Summary
Note: When you want to execute the loop body at least once
irrespective of the condition, then you need to use the do-while
loop.
• We have to use do while loop when we need to execute
a group of statements at least once.
• Only difference between while and do while loop is
that while loop will execute statements only when
given condition is true whereas do while will execute
statements at least once without checking the
condition.

60
For Loop in C Program
• Loops are used in programming to repeat the execution of a
specific block of code until the given condition becomes false.
• In general, we should use for the loop when we know the exact
loop count.
• It is frequently used to traverse the data structures like the
array and linked list.

61
For Loop in C Program
For loop contains 3 parts, such as
1.Initialization
2.Condition
3.Iteration (increment or decrement statement)

Syntax to use for loop in C:

62
• for loop always execution process will start from the initialization
block.
• After the initialization block, the control will pass to the condition
block. If the condition is evaluated as true then control will pass to
the statement block.
• After execution of the statement block, the control will pass to
iteration block, from iteration it will pass back to condition.
• Always repetition will happen beginning condition, statement block,
and iteration only.
• Initialization block will be executed only once when we are entering
into the loop first time.
• When we are working with for loop everything is optional but
mandatory to place 2 semicolons (;;).
• While we are working with for loop if the condition part is not given
then it will repeat infinite times because the condition part will
replace it as non-zero.
• So it is always true as like for(; 1; )
• Whenever we are working with for loop it repeats in an
anticlockwise direction.
• In for loop also the pre-checking process will occur i.e. before the
execution of the statement block (body of the for loop), condition part
will be executed
63
Write a C Program to print the number from 1 to 10 using for loop
#include <stdio.h>
int main()
{
int i;
for (i = 1; i <= 10; i++) Output: 1 2 3 4 5 6 7 8 9 10
{
printf("%d ", i);
}
}

Note: In implementation when we need to create more than one


initialization, more than one iteration part then use the comma
as a separator for every expression.
Whenever the body is not specified for the loop then
automatically scope will be terminated to next (;) i.e. under the
condition only 1 statement will be placed.

64
Break Statement in C Language
What are Jump Statements in C?
• Jump statements are used to modify the behavior of conditional and
iterative statements.
• Jump statements allow you to exit a loop, start the next iteration of a
loop, or explicitly transfer program control to a specified location in your
program. C provides the following loop for jump statements:
1. break
2. continue
3. Return
Break Statement in C:
• The break is a keyword.
• By using break we can terminate the loop body or switch
body.
• Using break is always optional but it should be placed within
the loop body and switch body only.
• In an implementation where we know the maximum number of
repetition but some condition is there where we need to
terminate the loop body then we need to go for a break.
65
Break Statement in C Language
• The break statement ends the loop immediately when it is
encountered.
• The break statement is almost always used with the if…else
statement inside the loop.

66
How does the break statement work in C?

Syntax: break;
67
Program to understand break statement in c:
#include <stdio.h>
int main()
{
int var;
for (var =100; var>=10; var --)
{
printf("var: %d\n", var);
if (var==99)
{
break;
}
}
printf("Out of for-loop");
return 0;
}

68
Some tricky questions related to C Break Statement:
What will be the output in the below program?

#include <stdio.h>
int main()
{
int a = 1;
while(a <= 10) Output: 1 2 3 4
{
printf("%d ", a);
if(a > 3)
break;
a++;
}
return 0;
}
• This is because whenever the value of a become 4 then the
condition becomes true then the break statement will be
executed.
• Whenever the break statement is executed automatically
control will pass outside of the loop body. 69
Continue Statement in C Language
Continue is a keyword. By using continue we can skip the
statement from the loop body. Using continue is always optional
but it should be placed within the loop body only. In an
implementation where we know the maximum number of
repetition but some condition is there we need to skip the
statement from loop body then we need to go for continue
statement.

The continue statement provides a convenient way to immediately


start the next iteration of the enclosing FOR, WHILE, or REPEAT
loop. Whereas the BREAK statement exits from a loop, the continue
statement exits only from the current loop iteration, proceeding
immediately to the next iteration. The continue statement is
almost always used with the if…else statement. For the for loop,
the continue statement causes the conditional test and increment
portions of the loop to execute.

For the while and do-while loops, continue statement causes the
program control to pass to the conditional tests. 70

You might also like