Sei sulla pagina 1di 30

Fundamentals of Programming Languages – I

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.

Decision making condition statement


 There are 3 types of decision making control statements in C language. They are,
I. if statements
II. if else statements
III. nested if statements

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

You entered -2.

The if statement is easy.

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

The if statement in C programming is easy.

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) {

// codes inside the body of if

else {

// codes inside the body of 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

Example: if...else statement


// Program to check whether an integer entered by the user is odd or even

#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.

III) Ternary Operator


There is alternative to „if-else‟ condition which is ternary operator that is different syntax but
provides functionality of „if-else‟ condition. Basic syntax of ternary operator is given below:

Condition expression ? if condition TRUE, return value1 : Otherwise, return value2;


IV) Nested if...else statement
This is multi-way condition in C – „if-else-if‟ condition. If programmer wants to execute
different statements in different conditions and execution of single condition out of multiple
conditions at one time, then this „if-else-if‟ condition statement can be used. Once any condition
is matched, „if-else-if‟ condition is terminated. Basic syntax for „if-else-if‟ condition is given
below:

Syntax of nested if...else statement.


if (testExpression1)

// statements to be executed if testExpression1 is true

else if(testExpression2)

// statements to be executed if testExpression1 is false and


testExpression2 is true

else if (testExpression 3)

// statements to be executed if testExpression1 and testExpression2 is


false and testExpression3 is true

}
.

else

// statements to be executed if all test expressions are false

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.

Example: nested if...else statement


// Program to relate two integers using =, > or <

#include <stdio.h>
int main()
{
int number1, number2;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);

//checks if two integers are equal.


if(number1 == number2)
{
printf("Result: %d = %d",number1,number2);
}

//checks if number1 is greater than number2.


else if (number1 > number2)
{
printf("Result: %d > %d", number1, number2);
}

// if both test expression is false


else
{
printf("Result: %d < %d",number1, number2);
}

return 0;
}

Output

Enter two integers: 12

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.

Example of a Cascading If else Statement

int main();
{

// the initial if statement


if (gpa >= 3.0)
{
student = "smart";
}
//if that statement is false, it will move next to the "else if"
statements

else if ((gpa >= 2.0) && (gpa< 3.0))


{
student = "average";
}
else if ((gpa >= 1.0) && (gpa < 2.0))
{
student = "below average";
}
else if ((gpa >= 0.0) && (gpa < 1.0))
{
student = "unsatisfactory";
}

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:

// code to be executed if n is equal to constant1;

break;

case constant2:

// code to be executed if n is equal to constant2;

break;

.
.

default:

// code to be executed if n doesn't match any constant

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.

Switch Statement Flowchart


Example of Switch Statement

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;
}

Few points about Switch Case


1) Case doesn‟t always need to have order 1, 2, 3 and so on. It can have any integer value after
case keyword. Also, case doesn‟t need to be in an ascending order always, you can specify them
in any order as per the need of the program.

2) You can also use characters in switch case

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.

TYPES OF LOOP CONTROL STATEMENTS IN C:


There are 3 types of loop control statements in C language. They are,

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 –

for (initialization; condition test; increment or decrement)


{
//Code – C statements needs to be repeated
}

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 –).

Various forms of FOR LOOP


I am using variable num in all the below examples –

1) Here instead of num++, I‟m using num=num+1 which is nothing but same as num++.

for (num=10; num<20; num=num+1)


2) Initialization part can be skipped from loop as shown below, the counter variable is declared
before the loop itself.

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.

for (num=10; num<20; )


{
//Code
num++;
}
4) Below case is also possible, increment in body and init during declaration of counter variable.

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.

for(num=20; num>10; num--)

Nested For Loops


Nesting of loops is also possible. Consider the below program –

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 –

for (i=1,j=1;i<10 && j<10; i++, j++)

II. While Loop


This loop is generally used for performing a same task, a fixed number of times.

Syntax of while loop:

while (condition test)


{
// C- statements, which requires repetition.
// Increment (++) or Decrement (--) Operation.
}

Example – Few examples to understand while loop better

..
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.

III. Do-While Loop


The do..while loop is similar to the while loop with one important difference. The body
of do...while loop is executed once, before checking the test expression. Hence, the do...while
loop is executed at least once.

Syntax of do-while loop


do

statement(s);

... ... ...

}while (condition);

How do...while loop works?

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

Difference between while and do-while loop?


do-while loop is similar to while loop, however there is one basic difference between them – do-
while runs at least one even if the test condition is false at first place. let‟s understand this with
an example –

Using 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.

IV) break statement in C

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:

variable value is: 0


variable value is: 1
variable value is: 2
Out of while-loop

Example – Use of break in a for loop


#include <stdio.h>
int main()
{
int var;
for (var =100; var>=10; var --)
{
printf("var: %d", num);
if (var==99)
{
break;
}
}
printf("Out of for-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.

Example: continue statement inside for loop


..
for (int j=0; j<=8; j++)
{
if (j==4)
{
continue;
}

printf("%d ", j);


}
..
Output:
0 1 2 3 5 6 7 8
Value 4 is missing in the output, why? When j‟s value is 4, the program encountered a continue
statement, which makes it to jump at the beginning of for loop for next iteration, skipping the
statements for current iteration (that‟s the reason printf didn‟t execute when j is equal to 4).

Example: Use of continue in While loop


..
int counter=10;
while (counter >=0)
{
if (counter==7)
{
counter--;
continue;
}
printf("%d ", counter);
counter--;
}
..
Output:

10 9 8 6 5 4 3 2 1 0
Iteration is skipped when counter value is 7.

Another Example of continue & do-While loop


#include <stdio.h>
int main()
{
int j=0;
do
{
if (j==7)
{
j++;
continue;
}
printf("\nvalue of j: %d", j);
j++;
}while(j<10);
return 0;
}
Output:

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.

lets take an example –

&n - It gives an address on variable n

Working of address operator


#include<stdio.h>
void main()
{
int n = 10;
printf("\nValue of n is : %d",n);
printf("\nValue of &n is : %u",&n);
}
Output :

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

printf("\nValue of &n is : %u",&n);

Understanding address operator


Consider the following program –

#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);
}

After declaration memory map will be like this –

int i = 5;
int *ptr;
after Assigning the address of variable to pointer , i.e after the execution of this statement –

ptr = &i;

Pointer Operator in C Program :

Operator Operator Name Purpose

* Value at Operator Gives Value stored at Particular address

& Address Operator Gives Address of Variable

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 :

1. „&‟ operator is called as address Operator

2. ‘*’ is called as ‘Value at address’ Operator

3. „Value at address’ Operator gives „Value stored at Particular address.


4. ‘Value at address’ is also called as ‘Indirection Operator’

Declaring a pointer variable


General syntax of pointer declaration is,

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.

Initialization of Pointer variable


Pointer Initialization is the process of assigning address of a variable to pointer variable.
Pointer variable contains address of variable of same data type. In C language address
operator & is used to determine the address of a variable. The & (immediately preceding a
variable name) returns the address of the variable associated with it.

int a = 10 ;

int *ptr ; //pointer declaration

ptr = &a ; //pointer initialization

or,

int *ptr = &a ; //initialization and declaration together

Pointer variable always points to same type of data.

float a;

int *ptr;

ptr = &a; //ERROR, type mismatch


Benefit of using pointers

 Pointers are more efficient in handling Array and Structure.

 Pointer allows references to function and thereby helps in passing of function as arguments

to other function.

 It reduces length and the program execution time.

 It allows C to support dynamic memory management.

Potrebbero piacerti anche