Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Unit – III
1. Decision Control Structures in ‘C’:
Control conditions are the basic building blocks of C programming language. In this
tutorial, we will cover the control conditions through some easy to understand
examples.
I) if statement
This is basic most condition in C – ‘if’ condition. If programmer wants to execute some
statements only when any condition is passed, then this single ‘if’ condition statement
can be used. Basic syntax for ‘if’ condition is given below:
if (expression) {
Statement 1;
Statement 1;
The if statement evaluates the test expression inside parenthesis. If test expression is evaluated to
true (nonzero), statements inside the body of if is executed. If test expression is evaluated to false
(0), statements inside the body of if is skipped.
Flowchart of if statement
Example: if statement
// Program to display a number if user enters negative number
// If user enters positive number, that number won't be displayed
#include <stdio.h>
int main()
{
int number;
printf("Enter an integer: ");
scanf("%d", &number);
// Test expression is true if number is less than 0
if (number < 0)
{
printf("You entered %d.\n", number);
}
printf("The if statement is easy.");
return 0;
}
Output 1
Enter an integer: -2
When user enters -2, the test expression (number < 0) becomes true. Hence, You entered -2 is
displayed on the screen.
Output 2
Enter an integer: 5
When user enters 5, the test expression (number < 0) becomes false and the statement inside the
body of if is skipped.
II) if...else statement
This is two-way condition in C – „if-else‟ condition. The if...else statement executes some code if
the test expression is true (nonzero) and some other code if the test expression is false (0). Either
„if‟ case statements are executed or „else‟ case statements are executed. Basic syntax for „if-else‟
condition is given below:
Syntax of if...else
if (testExpression) {
else {
If test expression is true, code inside the body of if statement is executed; and code inside the
body of else statement is skipped. If test expression is false, code inside the body
of else statement is executed; and code inside the body of if statement is skipped
Flowchart of if...else statement
#include <stdio.h>
int main()
{
int number;
printf("Enter an integer: ");
scanf("%d",&number);
// True if remainder is 0
if( number%2 == 0 )
printf("%d is an even integer.",number);
else
printf("%d is an odd integer.",number);
return 0;
}
Output
Enter an integer: 7
7 is an odd integer.
When user enters 7, the test expression (number%2 == 0 ) is evaluated to false. Hence, the
statement inside the body of else statement printf("%d is an odd integer"); is executed and the
statement inside the body of if is skipped.
else if(testExpression2)
else if (testExpression 3)
}
.
else
The if...else statement executes two different codes depending upon whether the test expression
is true or false. Sometimes, a choice has to be made from more than 2 possibilities.The nested
if...else statement allows you to check for multiple test expressions and execute different codes
for more than two conditions.
#include <stdio.h>
int main()
{
int number1, number2;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);
return 0;
}
Output
23
Result: 12 < 23
V) CASCADING IF-ELSE
A cascading if statement varies from a standard if statement through the use of the keyword else
if which follows the initial if condition. This statement is able to handle more than most other
conditional statements, and is best used when there are two or more conditions to be evaluated.
int main();
{
return 0;
}
This example shows us a Cascading if statement using the else if and else keywords:
VI) Switch Case Statement
he nested if...else statement allows you to execute a block code among many alternatives. If
you are checking on the value of a single variable in nested if...else statement, it is better to
use switch statement. The switch statement is often faster than nested if...else (not always).
Also, the syntax of switch statement is cleaner and easy to understand.
Syntax of switch...case
switch (n)
case constant1:
break;
case constant2:
break;
.
.
default:
When a case constant is found that matches the switch expression, control of the program passes
to the block of code associated with that case. In the above pseudo code, suppose the value
of n is equal to constant2. The compiler will execute the block of code associate with the case
statement until the end of switch block, or until the break statement is encountered. The break
statement is used to prevent the code running into the next case.
int main()
{
char ch='b';
switch (ch)
{
case 'd':
printf("CaseD ");
break;
case 'b':
printf("CaseB");
break;
case 'c':
printf("CaseC");
break;
case 'z':
printf("CaseZ ");
break;
default:
printf("Default ");
}
return 0;
}
3) The expression provided in the switch should result in a constant value otherwise it would not
be valid.
4) We don't use those expressions to evaluate switch case, which may return floating point
values or strings.
5) It isn't necessary to use break after each block, but if you do not use it, all the consecutive
block of codes will get executed after the matching block.
1. int i = 1;
2. switch(i)
3. {
4. case 1:
5. printf("A"); // No break
6. case 2:
7. printf("B"); // No break
8. case 3:
9. printf("C");
10. break;
11. }
Output : A B C
The output was supposed to be only A because only the first case matches, but as there is no
break statement after the block, the next blocks are executed, until the cursor encounters a break.
6) default case can be placed anywhere in the switch case. Even if we don't include the default
case switch statement works.
2. Loop Control Structures
Loop control statements in C are used to perform looping operations until the given condition is
true. Control comes out of the loop statements once condition becomes false.
I. For
II. While
III. do-while
I. For Loop
This is one of the most frequently used loop in C programming. The syntax of for loop looks
like this –
Example:
…
int i;
for (i=1; i<=3; i++)
{
printf("hello, World");
}
…
Output:
hello, World
hello, World
hello, World
Step 1: first initialization happens and the counter variable gets initialized, here variable is I,
which has been assigned by value 1.
Step 2: then condition checks happen, where variable has been tested for a given condition, if the
condition results in true then C statements enclosed in loop body gets executed by compiler,
otherwise control skips the loop and continue with the next statement following loop.
Step 3: After successful execution of loop‟s body, the counter variable is incremented or
decremented, depending on the operation (++ or –).
1) Here instead of num++, I‟m using num=num+1 which is nothing but same as num++.
int num=10;
for (;num<20;num++)
Must Note: Although we can skip init part but semicolon (;) before condition is must, without
which you will get compilation error.
3) Like initialization, you can also skip the increment part as we did below. In this case
semicolon (;) is must, after condition logic. The increment part is being done in for loop body
itself.
int num=10;
for (;num<20;)
{
//Statements
num++;
}
5) Counter can be decremented also, In the below example the variable gets decremented each
time the loop runs until the condition num>10 becomes false.
main()
{
for (int i=0; i<=10; i++)
{
for (int j=0; j<=10; j++)
{
printf("%d, %d",i ,j);
}
}
}
In the above example we have nested a for loop inside another for loop, this is called nesting of
loops. Such type of nesting is often used for handling multidimensional arrays.
Multiple initialization inside for Loop
Have a look at the below for loop –
..
main()
{
int count=1;
while (count <=4)
{
printf("%d ", count);
count++;
}
}
Output:
1 2 3 4
step1: first counter variable count got initialized with value 1 and then it has been tested for the
condition.
step2: If condition holds true then the body of the while loop gets executed otherwise control
come out of the loop.
step3: count value got incremented using ++ operator then it has been tested again for the loop
condition. It keeps happening until the condition returns false.
statement(s);
}while (condition);
The code block (loop body) inside the braces is executed once. Then, the test expression is
evaluated. If the test expression is true, the loop body is executed again. This process goes on
until the test expression is evaluated to 0 (false). When the test expression is false (nonzero),
the do...while loop is terminated.
Flowchart of do-while loop
main()
{
int i=0
while(i==1)
{
printf("while vs do-while");
}
printf("Out of loop");
}
Output:
Out of loop
Same example using do-while loop
main()
{
int i=0
do
{
printf("while vs do-while\n");
}while(i==1);
printf("Out of loop");
}
Output:
while vs do-while
Out of loop
Explanation: As I mentioned above do-while runs at least once even if the condition is false
because compiler checks the condition after execution of its body.
a) It is used to come out of the loop instantly. Whenever compiler finds a break statement inside
a loop, the control directly comes out of loop and passed to the statement following the loop. It is
used along with if statement, whenever used inside loop.
b) It is used in switch case control structure also. Whenever it is encountered in switch-case
block, the control comes out of the switch-case body.
Example – Use of break in a while loop
#include <stdio.h>
int main()
{
int num =0;
while(num<=100)
{
printf("variable value is: %d", num);
if (num==2)
{
break;
}
num++;
}
printf("Out of while-loop");
return 0;
}
Output:
var: 100
var: 99
Out of for-loop
Example – Use of break statement in switch-case
int main()
{
int num;
printf("Enter value of num:");
scanf("%d",&num);
switch (num)
{
case 1:
printf("You have entered value 1 ");
break;
case 2:
printf("You have entered value 2 ");
break;
case 3:
printf("You have entered value 3 ");
break;
default:
printf("Input value is other than 1,2 & 3 ");
}
return 0;
}
V) Continue Statement in C
Continue statement is mostly used inside loops. Whenever it is encountered inside a loop, control
directly jumps to the beginning of the loop for next iteration, skipping the execution of
statements inside loop‟s body for the current iteration.
10 9 8 6 5 4 3 2 1 0
Iteration is skipped when counter value is 7.
value of j: 0
value of j: 1
value of j: 2
value of j: 3
value of j: 4
value of j: 5
value of j: 6
value of j: 8
value of j: 9
3. Pointers in c
Pointers are variables that hold address of another variable of same data type.Pointers are one of
the most distinct and exciting features of C language. It provides power and flexibility to the
language. Although pointer may appear little confusing and complicated in the beginning, but
trust me its a powerful tool and handy to use once its mastered.
Concept of Pointer
Whenever a variable is declared, system will allocate a location to that variable in the memory,
to hold value. This location will have its own address number.
Let us assume that system has allocated memory location 80F for a variable a.
int a = 10 ;
We can access the value 10 by either using the variable name a or the address 80F. Since the
memory addresses are simply numbers they can be assigned to some other variable. The
variable that holds memory address are called pointer variables. A pointer variable is
therefore nothing but a variable that contains an address, which is a location of another
variable. Value of pointer variable will be stored in another memory location.
Address Operators
1. Pointer address operator is denoted by „&‟ symbol
2. When we use ampersand symbol as a prefix to a variable name „&‟, it gives the address
of that variable.
Value of n is : 10
Value of &n is : 1002
Consider the above example, where we have used to print the address of the variable using
ampersand operator.
In order to print the variable we simply use name of variable while to print the address of the
variable we use ampersand along with %u
#include<stdio.h>
int main()
{
int i = 5;
int *ptr;
ptr = &i;
printf("\nAddress of i : %u",&i);
printf("\nValue of ptr is : %u",ptr);
return(0);
}
int i = 5;
int *ptr;
after Assigning the address of variable to pointer , i.e after the execution of this statement –
ptr = &i;
In order to create pointer to a variable we use “*” operator and to find the address of variable we
use “&” operator. Don‟t Consider “&” and “*” operator as Logical AND and Multiplication
Operator in Case of Pointer.
Important Notes :
data-type *pointer_name;
Data type of pointer must be same as the variable, which the pointer is pointing. void type
pointer works with all data types, but isn't used oftenly.
int a = 10 ;
or,
float a;
int *ptr;
Pointer allows references to function and thereby helps in passing of function as arguments
to other function.