0% found this document useful (0 votes)
9 views36 pages

Unit 2 Notes C Programing

Uploaded by

jeevanjo2008
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)
9 views36 pages

Unit 2 Notes C Programing

Uploaded by

jeevanjo2008
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/ 36

UNIT 2

Module II Decision Making and Looping Statements


Introduction to Decision and Control Statements - Conditional Branching Statements – Iterative
Statements- Nested Loops – Break and Continue Statements – goto Statements.

DECISION MAKING / SELECTION STATEMENTS

The Decision Making Statements are used to evaluate the one or more conditions and make the
decision whether to execute set of statement or not.

if statement

The if statement checks whether the text expression inside parenthesis () is true or not. If
the test expression is true, statement/s inside the body of if statement is executed but if test is
false, statement/s inside body of if is ignored.

Syntax

if (test_expression)

Staements to be executed if test expression is true;

Flow chart
Example program

// C program to illustrate If statement

include <stdio.h>

int main()

int i = 10;

if (i > 15) {

printf("10 is greater than 15");

printf("I am Not in if");


}

Output:

I am Not in if

if – else statement

The if...else statement is used if the programmer wants to execute some statement/s when
the test expression is true and execute some other statement/s if the test expression is false.

Syntax

if (test expression)

statements to be executed if test expression is true;

else

statements to be executed if test expression is false;

Flow chart

Example program

#include <stdio.h>
int main()

{ int i = 20;

if (i < 15) {

printf("i is smaller than 15");

else {

printf("i is greater than 15");

return 0;

Output:

i is greater than 15

Nested if –else statement

The nested if...else statement is used when program requires more than one test
expression.

Syntax

if (condition1)

// Executes when condition1 is true if (condition2)

// Executes when condition2 is true

Flow chart
Example program

include <stdio.h>

int main()

int i = 10;

if (i == 10) {// First if statement

if (i < 15)

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;

Output:

i is smaller than 15

i is smaller than 12 too

if-else-if ladder

if else if ladder in C programming is used to test a series of conditions sequentially.


Furthermore, if a condition is tested only when all previous if conditions in the if-else ladder are
false. If any of the conditional expressions evaluate to be true, the appropriate code block will be
executed, and the entire if-else ladder will be terminated

Syntax:

if (condition)

statement;

else if (condition)

statement;

..

else statement;
Flow chart

Example program

#include <stdio.h>

int main()

{int i = 20;

if (i == 10)

printf("i is 10");

else if (i == 15)

printf("i is 15");
else if (i == 20)

printf("i is 20");

else

printf("i is not present"); }

Output:

i is 20

Switch Statement

Switch case statement evaluates a given expression and based on the evaluated value(matching a
certain condition), it executes the statements associated with it.

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.

The switch case statement is used for executing one condition from multiple conditions. It is
similar to an if-else-if ladder.

Syntax

switch(expression)

{ case value1: statement_1;

break; case

value2: statement_2;

break; . . .

case value_n: statement_n;

break;

default: default_statement; }
Flow chart

Example program

#include <stdio.h>

int main ()

{char grade = 'B';

switch(grade) {

case 'A' :

printf("Excellent!\n" );

break;

case 'B' :

printf("Well done\n" );

break;
default :

printf("Invalid grade\n" ); }

printf("Your grade is %c\n", grade );

return 0;

Output

Well done

Your grade is B

JUMP STATEMENTS

They support four types of jump statements:

 Break

 continue

 goto statements

Break: The break statement can be used in terminating all three loops for, while and do...while
loops.

Syntax is: break;

Example program

#include<stdio.h>

#include<stdlib.h>
void main ()

int i;

for(i = 0; i<10; i++)

printf("%d ",i);

if(i == 5)

break;

printf("came outside of loop i = %d",i);

Output

0 1 2 3 4 5 came outside of loop i = 5

Continue Statement

The continue statement is opposite to that of the break statement, instead of terminating the loop,
it forces to execute the next iteration of the loop.

When the continue statement is executed in the loop, the code inside the loop following the
continue statement will be skipped and the next iteration of the loop will begin.

Syntax is: continue;


Example program

#include <stdio.h>

int main()

{// loop from 1 to 10

for (int i = 1; i <= 10; i++)

// If i is equals to 6, // continue to next iteration // without printing

if (i == 6)

continue;

else

// otherwise print the value of i

printf("%d ", i);

return 0;

Output:

1 2 3 4 5 7 8 9 10

goto statement

In C programming, goto statement is used for altering the normal sequence of program
execution by transferring control to some other part of the program.

Syntax

goto label;

.............

.............

label:
statement;

Label is an identifier. When, the control of program reaches to goto statement, the control of the
program will jump to the label: and executes the code below it.

Example program

#include <stdio.h>

// function to print numbers from 1 to 10

void printNumbers()

{ int n = 1;

label:

printf("%d ", n);

n++;

if (n <= 10)

goto label; } // Driver program to test above function

int main()

printNumbers();

return 0;}

Output:

1 2 3 4 5 6 7 8 9 10
LOOP STATEMENT / ITERATIVE STATEMENTS

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:

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.

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.

for Loop

The for loop in C language is used to iterate the statements or a part of the program
several times. It is frequently used to traverse the data structures like the array and linked list.

Syntax

for(Expression 1; Expression 2; Expression 3)

//code to be executed }
Flow Chart

Example program

#include <stdio.h>

int main()

int i = 0;

for (i = 1; i <= 5; i++)

printf( "Hello World\n");

} return 0;}

Output

Hello World

Hello World

Hello World

Hello World

Hello World
while loop

The while loop checks whether the test expression is true or not. If it is true, code/s inside
the body of while loop is executed, that is, code/s inside the braces { } are executed. Then again
the test expression is checked whether test expression is true or not. This process continues until
the test expression becomes false.

Syntax

while (test_expression)

// body of the while loop update_expression;

Flow chart

Example Program

#include <stdio.h>
int main () {

/* local variable definition */


int a = 10;

/* while loop execution */


while( a < 20 ) {
printf("value of a: %d\n", a);
a++; }

return 0;
}

Output

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

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.
Syntax
do
{
// body of do-while loop update_expression;
} while (test_expression);
Flow Chart

Example program
#include <stdio.h>
int main()
{ // Initialization expression
int i = 2;
do
{// loop body
printf( "Hello World\n"); // Update expression
i++; // Test expression
} while (i < 1);
return 0;
}
Output
Hello World

Nested Loops
Nesting of loops is the feature in C that allows the looping of statements inside another
loop. Any number of loops can be defined inside another loop, i.e., there is no restriction for
defining any number of loops. The nesting level can be defined at n times.
You can define any type of loop inside another loop; for example, you can define 'while' loop
inside a 'for' loop.
Syntax
Outer_loop
{
Inner_loop
{
// inner loop statements.
}
// outer loop statements.
}

Flow Chart

Example program

#include <stdio.h>

int main()
{

int weeks = 1, days_in_week = 7;

for (int i = 1; i <= weeks; ++i)

printf("Week: %d\n", i);

for (int j = 1; j <= days_in_week; ++j)

printf(" Day: %d\n", j);

}}

return 0;

Output

Week: 1

Day:1

Day:2

Day:3

Day:4

Day:5

Day:6

Day:7

Block Statement

A Block is also called a compound statement. All definitions, declarations, and


statements enclosed within a single set of braces are treated as a single statement. A component
statement does not end with a semicolon

Example

#include <stdio.h>
int main()

int a=7

{ a=a+1,

Printf(“%d”, a);

return 0;

}
Storage classes

Storage classes in C are used to determine the lifetime, visibility, memory location, and initial
value of a variable. There are four types of storage classes in C

 Automatic
 External
 Static
 Register

Storage Storage Default Scope Lifetime


Classes Place Value

Auto RAM Garbage Local Within function


Value

Extern RAM Zero Global Till the end of the main program
Maybe declared anywhere in the
program

Static RAM Zero Local Till the end of the main program,
Retains value between multiple
functions call

Register Register Zero Local Within the function

Automatic

Automatic variables are allocated memory automatically at runtime. The automatic


variables are initialized to garbage by default. Garbage value means random value. The keyword
used for defining automatic variables is auto. Every local variable is automatic in C by default.

Example
#include <stdio.h>
int main()
{
auto int a; //auto
char b;
float c;
printf("%d %c %f",a,b,c); // printing initial default value of automatic variables a, b, and c.
return 0;
}

Output:

garbage garbage garbage

70 80 67

Static

 The variables defined as static specifier can hold their value between the multiple
function calls.
 Static local variables are visible only to the function or the block in which they are
defined.
 A same static variable can be declared many times but can be assigned at only one time.
 Default initial value of the static integral variable is 0 otherwise null.
 The visibility of the static global variable is limited to the file in which it has declared.
 The keyword used to define static variable is static.

Example

#include<stdio.h>

void display()

static int a =10;

int a=a+10;

printf(“a=%d\n”,a);

int main()

{
For(i=1; i<=3; i++)

{display();

}return 0;

Output

a=20

a=30

a=40

Register

 The variables defined as the register is allocated the memory into the CPU registers
depending upon the size of the memory remaining in the CPU.
 We cannot dereference the register variables, i.e., we cannot use &operator for the
register variable.
 The access time of the register variables is faster than the automatic variables.
 The initial default value of the register local variables is 0.
 The register keyword is used for the variable which should be stored in the CPU register.
However, it is compiler?s choice whether or not; the variables can be stored in the
register.
 We can store pointers into the register, i.e., a register can store the address of a variable.
 Static variables can not be stored into the register since we can not use more than one
storage specifier for the same variable.

Example
#include <stdio.h>
int main()
{
register int a; // variable a is allocated memory in the CPU register.
The initial default value of a is 0.
printf("%d",a);
}
Output: 0
External

 The external storage class is used to tell the compiler that the variable defined as extern is
declared with an external linkage elsewhere in the program. 
 The variables declared as extern are not allocated any memory. It is only declaration and
intended to specify that the variable is declared elsewhere in the program. 
 The default initial value of external integral type is 0 otherwise null. 
 We can only initialize the extern variable globally, i.e., we can not initialize the external
variable within any block or method.
 An external variable can be declared many times but can be initialized at only once. 
 If a variable is declared as external then the compiler searches for that variable to be
initialized somewhere in the program which may be extern or static. If it is not, then the
compiler will show an error.

Example 1

#include <stdio.h>
int main() In this program just declared the extern ‘a’ variable in
{ main functions but not define variable in globally
extern int a;
printf("%d",a);
}

Output

main.c:(.text+0x6): undefined reference to `a'


collect2: error: ld returned 1 exit status

Example 2
#include <stdio.h>
int a; //variable a is defined globally
int main()
{
extern int a; // just declare a variable in main function,
printf("%d",a); // default value zero will be print in output
}
Output
0
Example 3
#include <stdio.h>
int a;
int main()
{
extern int a = 0; // this will show a compiler error since we can not use extern and initializer at s
ame time
printf("%d",a);
}

Output

compile time error


main.c: In function ?main?:
main.c:5:16: error: ?a? has both ?extern? and initializer
extern int a = 0;

Example 4
#include <stdio.h>
int main()
{
extern int a; // Compiler will search here for a variable a defined and initialized somewhere in th
e pogram or not.
printf("%d",a);
}
int a = 20;

Output

20
PART A

1. Mention the various decisions making statement available in C.


 if statement
 if...else statement
 nested if statements
 switch statement
 nested switch statements

2. What is the difference between if and while statement?

If
 It is a conditional statement.
 If the condition is true, it executes some statements.
 If the condition is false then it stops the execution the statements.
While
 It is a loop control statement.
 Executes the statements within the while block if the condition is true.
 If the condition is false the control is transferred to the next statement of the loop.

3. What are the types of looping statements available in C?


C programming language provides following types of loop to handle looping requirements.
 for loop
 while loop
 do...while loop
4. Distinguish between while and do.. in C.
while statement
a) Executes the statements within the while block, if only the condition is true.
b) The condition is checked at the starting of the loop.
c) It is an entry controlled loop.
Do..while
a) Executes the statements within the while block at least once.
b) The condition is checked at the end of the loop.
c) It is an exit controlled loop.

5. Write a for loop statement to print numbers from 10 to 1.


#include <stdio.h>
{
int count; // Display the numbers 10 to 1
for(count = 10; count >= 1; count--)
printf("%d", count);
}

6. What are the storage classes available in C?


Storage classes are categorized in four types as,
Automatic Storage Class - auto
Register Storage Class - register
Static Storage Class - static
External Storage Class - extern

7. What is register storage in storage class?


Register is used to define local variables that should be stored in a register instead of RAM. This means
that the variable has a maximum size equal to the register size (usually one word)and can’t have the unary '&'
operator applied to it (as it does not have a memory location).
Ex.register int a=200;

8. What is static storage class?


Static is the default storage class for global variables. The static storage class object will be stored in the main
memory.
Ex. static int Count=19;

9. Define Auto storage class in C.


Auto is the default storage class for all local variables. The auto storage class data object will be stored in the
main memory. These objects will have automatic (local) lifetime.
Ex. auto int Month;

10. Define Branching


 The C language programs follow a sequential form of execution of statements.
 Many times it is required to alter the flow of sequence of instructions. C language provides statements
that can alter the flow of a sequence of instructions.
 These statements are called as control statements.
11. Define Looping.
A loop statement allows us to execute a statement or group of statements multiple times.

12. Write down the syntax of if-else statement.


If (condition)
Program statement 1;
Else
Program statement 2;

13. Define Switch Statement.


 A switch statement allows a variable to be tested for equality against a list of values.
 Each value is called a case, and the variable being switched on is checked for each switch case.

14. Define goto statement.


goto statement is highly discouraged in any programming language because it makes difficult to trace the
control flow of a program, making the program hard to understand and hard to modify.

15. Define comma operator.


Comma operator represented by ‘,’ ensures the evaluation from left to right, one by one, of two or more
expressions, separated with commas, and result of entire expression is value of rightmost expression.
Example int a = 10, b = 20, c = 30;
16. What is the purpose of continue statement?
 The continue statement in C programming works somewhat like the break statement.
 Instead of forcing termination, it forces the next iteration of the loop to take place, skipping any
code in between.

17.Write the syntax of While loop?


while(condition)
{
statement(s);
}
18. Can the "switch" statement be nested in C?
No, we cannot nest the switch statement in C. This means that a switch statement in C cannot contain
another switch statement inside it.
19. How many "case" statements can a "switch" statement have in C?
A "switch" statement in C can have any number of "case" statements.
20. What happens if none of the "case" statements match in a "switch" statement in C?
If none of the "case" statements match in a "switch" statement in C, the code within the "default" block is
executed.
21. Can the "break" statement be used outside of loops and switch statements in C?
No, the "break" statement can only be used within loops and switch statements in C.
22. Can the "goto" statement be used to jump to a label defined in another function in C?
No, the "goto" statement can only jump to a label defined within the same function in C.

23. What is a Statement in C?


A statement is a block of code that does something.
24. Different Types of Statements?
Null Statement, Expression Statement, Compound Statement, Return Statement, Conditional Statements,
Iterative or Looping Statements, Unconditional Statements
25. Define Null Statement?
A "null statement" is a statement containing only a semicolon;
26. Define Expression Statement?
When an expression statement is executed, the expression is evaluated according to the rules outlined in
Expressions and Assignments.
27. Define Compound Statement?
A compound statement (also called a "block") typically appears as the body of another statement which is in
between {
and
}
28. Define Return Statement?
The return statement terminates the execution of a function and returns control to the calling function. A
return statement can also return a value to the calling function.
29. Define Conditional Statements and give the list of them?
Conditional Statements which allows to perform actions depending upon some conditions provided by the
programmer. The Different types of conditional statements are:
1) If Statement

2) If else statement

3) Nested- if else statement

4) Switch Statement
30.Write the Syntax for IF Statement?
if ( <expression> )
<statement>
31.Write the Syntax for IF- ELSE Statement?
if ( <expression> )
<statement 1> else
<statement 2>
32. Write the Syntax for NESTED- IF - ELSE Statement?
if ( <expression1> )
{
if(<expression2>)
{
<Statements>
}
else
{
<Statements>
}
}
else
<statement>
33. Write the Syntax for Switch Case Statement?
switch ( <expression> )
( <case list>
} where
<case list> is a sequence of
case <value>:
<statement list>
break; and optionally one
default:
<statement list>
break;

34. What are Iterative or Looping Statements?


Iterative or Looping statement which executes the statements with in the compound statement by checking the
condition, and performs same set of statements as a iterative process or as a loop until the condition false.
The Iterative or Looping Statements are: While, do-while, for
35.Write Syntax for WHILE Statement?
while ( <expression> )
<statement>
36. Write Syntax for DO- WHILE Statement?
do <statement>
while ( <expression> );
37. Write Syntax for FOR Statement?
for ( <Initialization>;<Condition>;<Increment/Decrement>)
<statement>
38. What is the difference between for loop and while loop?
For Loop is used to execute a set of statements in fixed number of times. We use While loop when the number
of iterations to be performed is not known in advance we use while loop.
39. What are Unconditional Statements?
goto and labeled statements, break Statement continue Statement.
40. Define goto and labeled Statement, Write syntax for goto and labeled statements? Ans: The goto
statement transfers control to a label. The given label must reside in the same function and can appear before
only one statement in the same function.
Syntax:
goto <label>;
<label>: <Statement>;
41. Define Break Statement, Write syntax for Break statement?
The break statement terminates the execution of the nearest enclosing do, for, switch, or while statement in
which it appears. Control passes to the statement that follows the terminated statement.
Syntax:
break;
42. Define Continue Statement, Write syntax for Continue statement?
The continue statement passes control to the next iteration of the nearest enclosing do, for, or while statement
in which it appears
Syntax:
continue;

PART B

1. Explain the following (i) conditional statements. (ii) switch Statements (iIi)Nested if-else statement
2. Write about the need and types of looping statements in C language and discuss with examples.
3. Write about the need and types of branching statements in C language and discuss with examples.
4. List out the block statements available in C with an example?
5. Explain with syntax, if, if-else and nested if-else statements in, C‟ program
6. Write a program in „C‟ to find the sum of „n‟ natural numbers without using any loops
7. Write a C program to demonstrate the use of unconditional goto statement
8. Show how break and continue statements are used in a C program, with example
9. Write a calculator program in C language to do simple operations like addition, subtraction, multiplication
and division. Use switch statement in your program
10. Differentiate between the if statement and the while loop in c programming. Provide a simple code
example for each.
11. Write C programs to find the factorial of a number using do-while, where the number n is entered by user.
12. List the differences between while loop and do-while loop. Write a C program to find sum of Natura
numbers from 1 to N using for loop
13. Write a C program to find the biggest of three numbers
14. Explain with example, the meaning of statement and block in a C program
15. Explain briefly about the decision making statement with suitable example?
16. Write a program to check whether a given number is prime or not.
17. Write a C program to print the students grade of student.
18. Write a C program that takes three coefficients (a,b,and c) of a quadtatic equation ; (ax2+bx+c) as input
and compute all possible roots and print them with appropriate messages.
19. Write a C program to find GCD of two numbers using ternary operator and for loop
20. Write a C program that takes from user an arithmetic operator („+‟, „-„, „*‟, or „/‟) and two operands.
Perform corresponding arithmetic operation on the operands using switch statement

Case-Study Problems

Find biggest number of three given numbers


Algorithm
1. Ask the user to enter three integer values.
2. Read the three integer values in num1, num2, and num3 (integer variables).
3. Check if num1 is biggest than num2.
4. If true, then check if num1 is biggest than num3.
1. If true, then print ‘num1’ as the biggest number.
2. If false, then print ‘num3’ as the biggest number.
5. If false, then check if num2 is biggest than num3.
1. If true, then print ‘num2’ as the biggest number.
2. If false, then print ‘num3’ as the biggest number
FlowChart
PROGRAM
#include <stdio.h>
int main()
{
int num1, num2, num3;
printf(" Enter the number1 = ");
scanf("%d", &num1);
printf("\n Enter the number2 = ");
scanf("%d", &num2);
printf("\n Enter the number3 = ");
scanf("%d", &num3);
if (num1 >= num2 && num1 >= num3)
{
printf("\n %d is the biggest number.\n", num1);
}
if (num2 >= num1 && num2 >= num3)
{
printf("\n %d is the biggest number.\n", num2);
}
if (num3 >= num1 && num3 >= num2)
{
printf("\n %d is the biggest number.\n", num3);
}
return 0;
}
Output:
Enter the number1 = 6
Enter the number2 = 27
Enter the number3 = 24
27 is the biggest number.

2. To find whether the number is even, odd or zero(using nested if)


Algorthim
 Declare the variable
 Take input from the user
 if else condition to check whether the number is even or odd. if the condition is true print number is
event
 Then nested if else condition to check if n is divisible by 4 or not. If the condition is true print the
number is divisible by 4 or the condition is false print the number is not divisible by 4 or else print the
number is odd
 Then nested if else condition to check if n is divisible by 3 or not
 If the condition is true print the number is divisible by 3or the condition is false print the number is not
divisible by 3.
Flowchart

Program
#include <stdio.h>
int main() {
// variable to store the given number
int n;
//take input from the user
scanf("%d", &n);
//if else condition to check whether the number is even or odd
if (n % 2 == 0) {

//the number is even


printf("Even ");
//nested if else condition to check if n is divisible by 4 or not
if (n % 4 == 0) {
//the number is divisible by 4
printf("and divisible by 4");
} else {
//the number is not divisible by 4
printf("and not divisible by 4");
}
} else {
//the number is odd
printf("Odd ");
//nested if else condition to check if n is divisible by 3 or not
if (n % 3 == 0) {
//the number is divisible by 3
printf("and divisible by 3");
} else {
//the number is not divisible by 3
printf("and not divisible by 3");
}
}
return 0;
}

OUTPUT
14
Even and not divisible by 4

You might also like