Presentation is loading. Please wait.

Presentation is loading. Please wait.

Unit 3 Control Structure

Similar presentations


Presentation on theme: "Unit 3 Control Structure"— Presentation transcript:

1 Unit 3 Control Structure

2 Flow of Control Unless specified otherwise, the order of statement execution through a function is linear: one statement after another in sequence Some programming statements allow us to: decide whether or not to execute a particular statement execute a statement over and over, repetitively These decisions are based on Boolean expressions (or conditions) that evaluate to true or false The order of statement execution is called the flow of control

3 C Keywords auto double int struct break else long switch
case enum register typedef char extern return union const float short unsigned continue for signed void default goto sizeof volatile do if static while The words in bold print are used in control statements. They change the otherwise sequential execution of the assignment statements in a function block

4 Conditional Statements
A conditional statement lets us choose which statement will be executed next Therefore they are sometimes called selection statements The C conditional statements are the: if statement : Specifies which block of code is execute if-else statement: Check condition true or false if-else if statement : multiple condition at one time Nested if statement : if statement contain another if statement in either its block or else block or both block Switch statement

5 Logic of an if statement
condition evaluated false statement true

6 The if Statement The if statement has the following syntax:
The condition must be a boolean expression. It must evaluate to either true or false. if is a C reserved word if ( condition ) statement; If the condition is true, the statement is executed. If it is false, the statement is skipped.

7 To Print largest of two number using if Statement
#include<Stdio.h> Main() { int a=10, b=15, max; max=b; if(a>b) { max=a; } printf(“ The largest between two number is =%d”, max); Output: The largest two number is= 15

8 The if-else Statement An else section can be added to an if statement to make an if-else statement if ( condition ) statement1; else statement2; If the condition is true, statement1 is executed; if the condition is false, statement2 is executed One or the other will be executed, but not both

9 Logic of an if-else statement
condition evaluated false statement2 statement1 true

10 To check number is even or odd.
#include<stdio.h> main() { int num; if (num%2=0) printf(“Number %d is even”, num); } else printf(“Number %d is odd”, num);

11 The if-else if Statement
To perform various actions based on multiple conditions at one time we can use if-else if statement. If neither of the condition evaluates to true, default statement will be executed. if ( condition ) { statement1; } else if ( condition ) statement2; }

12 Nested if Statements If statement contain another if statement in either its block or else block or both block. These are called nested if statements. if ( condition ) { statement1; else statement2; } else else statement2; }

13 To check greatest of three number.
#include<stdio.h> main() { Float A,B,C; Printf(“Enter the three number”); Scanf(“%f%f%f”, &A,&B,&C); Printf(“Largest number is”); if (A>B) if (A>C) printf(“%f”, A); else printf(“%f”, C); } if (C>B) printf(“%F”, C); printf(“%f”, B);

14 The switch Statement The switch statement provides another way to decide which statement to execute next The switch statement evaluates an expression, then attempts to match the result to one of several possible cases Each case contains a value and a list of statements The flow of control transfers to statement associated with the first case value that matches

15 The switch Statement Often a break statement is used as the last statement in each case's statement list A break statement causes control to transfer to the end of the switch statement If a break statement is not used, the flow of control will continue into the next case Sometimes this may be appropriate, but often we want to execute only the statements associated with one case

16 The switch Statement A switch statement can have an optional default case The default case has no associated value and simply uses the reserved word default If the default case is present, control will transfer to it if no other case value matches If there is no default case, and no other value matches, control falls through to the statement after the switch

17 The switch Statement The expression of a switch statement must result in an integral type, meaning an integer (byte, short, int,) or a char It cannot be a floating point value (float or double) You cannot perform relational checks with a switch statement

18 Flow of switch statement

19 The switch Statement The general syntax of a switch statement is:
and case are reserved words switch ( expression ) { case value1 : statement-list1; break; case value2 : statement-list2; case value3 : statement-list3; case ... default: default-block; } If expression matches value2, control jumps to here

20 Switch Statement Example
case values must be constants int month, daysInMonth, leapYear; switch (month) { case 0: printf("January\n"); daysInMonth = 31; break; case 1: printf("February\n"); daysInMonth = leapYear ? 29 : 28; break; case 2: printf("March\n"); daysInMonth = 31; break; case 3: printf("April\n"); daysInMonth = 30; break; … } // switch break statement needed to jump over subsequent cases default case is optional (not shown)

21 Repetition in Programs
In most software, the statements in the program may need to repeat for many times. e.g., calculate the value of n!. If n = 10000, it’s not well-designed to write the code as 1*2*3*…*10000. Loop is a control structure that repeats a group of steps in a program. Loop body stands for the repeated statements. There are three C loop control statements: while, for, and do-while.

22 The while Statement in C
The syntax of while statement in C: initialization; while (loop repetition condition) { statement; } Loop repetition condition is the condition which controls the loop. The loop repetition condition is tested before loop body executed. The statement is repeated as long as the loop repetition condition is true. A loop is called an infinite loop if the loop repetition condition is always true.

23 An Example of a while Loop
#include<stdio.h> Main() { int n=1,fact=1; while (n<=5) { fact=fact*n; n++; } printf(“Factorial of Number is :%d”, fact);

24 The for Statement in C The syntax of for statement in C:
for (initialization expression; loop repetition condition; update expression) { statement; } The initialization expression set the initial value of the loop control variable. The loop repetition condition test the value of the loop control variable i.e. Boolean Expression. The update expression update increment/ decrement value. Body of loop is executed, till the repeat condition becomes false. e.g., for (int i = 0; i < 100; i++)

25 #include<stdio.h>
Main() { int n=1,fact=1; for(n=1;n<=5;n++) { fact=fact*n; } printf(“Factorial of Number is :%d”, fact);

26 Nested For Loops Outer loop Inner loop
Nested loops consist of an outer loop with one or more inner loops. Syntax for (initialization expression; loop repetition condition; update expression) { { (Statement); } } e.g., for (i=1;i<=100;i++){ for(j=1;j<=50;j++){ } The above loop will run for 100*50 iterations. Outer loop Inner loop

27 The do-while Statement in C
The syntax of do-while statement in C: initialization; Do { statement } while (loop repetition condition); The statement is first executed. If the loop repetition condition is true, the statement is repeated. Otherwise, the loop is exited.

28 An Example of the do-while Loop
#include<stdio.h> Main() { int n=1,fact=1; do { fact=fact*n; n++; } while (n<=5); printf(“Factorial of Number is :%d”, fact); }

29 Jump statement allow program to execute in a nonlinear fashion.
Jump statements Jump statement allow program to execute in a nonlinear fashion. break statement continue statement goto Return

30 break statement Terminates innermost loop/switch
From this statement, control is transferred to outside the loop/switch. Usage ■ Within loops : Generally used in conjunction with conditional statements ■ Within Switch Case statements : useful to break the switch statement

31 break Example #include<stdio.h> Main() { int a; for(a=0;a<100;a++) { printf(“\t %d”, a); if(a==10) { break; } }

32 continue statement The continue statement in C programming language works somewhat like the break statement. Instead of forcing termination, however, continue forces the next iteration of the loop to take place,. For the for loop, 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 passes to the conditional tests. Syntax: continue;

33 continue Example void main( ) { for( int i=0; i<10; i++) { printf(“%d”, i); if(i%2==0) continue; } /*end of if*/ printf(“\n"); } /*end of for*/ }

34 goto statement A goto statement in C programming language provides an unconditional jump from the goto to a labeled statement in the same function. It is used to transferring the control to some other part of the program. Syntax : goto label; .. . label: statement; Here label can be any plain text except C keyword and it can be set anywhere in the C program above or below to goto statement.

35 The goto statement is of two types :
Conditional goto Statement Unconditional goto Statement Conditional goto Statement : The Conditional goto is used to transfer control of the execution from one part of program to the other part in some conditional Statement. e.g. Main() { Int a,b; printf(“Enter the values of a and b”); Scanf(“%d %d”, &a, &b); if (a>b) { goto 1; } else { goto 2; } 1: printf((“Largest is %d”, a); 2: Printf(“Largest is %d”,b); }

36 Unconditional goto : it is used to transfer the control of the execution from one part of the program to the other part without checking any condition . e.g. #include<stdio.h> Main() { Start: Printf(“Hello”); goto Start; }

37 Return Statement The return statement is use to return from a function. It is categorized as a jump statement because it causes execution to return (jump back) to the point at which call to the function was made. A return may or may not have a value associated with it. A return with a value can be used only in a function with a non-void return type. So value associated with return becomes the return value of the function. A return without a value is used to return from a void function. Syntax: return expression;

38 Where expression is the value to return
Where expression is the value to return. we can use as many return statements as we want within a function. but the function will stop executing as soon as it encounters the first return. A function declared as a void can not contain a return statement that specifies a values. E.g. #include<stdio.h> main() { int t=1; printf(“Before the return”); if(t==1) { return 0; } printf(“This will not execute”); Output : Before the return

39 C Functions Function is a group of statements that together perform a task. Every C program has at least one function, which is main(), and all the most trivial programs can define additional functions. A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function. The C standard library provides numerous built-in functions that your program can call. For example, function strcat() to concatenate two strings, function memcpy() to copy one memory location to another location and many more functions. A function is known with various names like a method or a sub-routine or a procedure, etc.

40 Defining a Function The general form of a function definition in C programming language is as follows: return type function name( parameter list ) { body of the function } A function definition in C programming language consists of a function header and a function body. Here are all the parts of a function: Return Type: A function may return a value. The return_type is the data type of the value of the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void. Function Name: This is the actual name of the function. The function name and the parameter list together constitute the function signature.

41 Parameters: A parameter is like a placeholder
Parameters: A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; i.e. a function may contain no parameters. Function Body: The function body contains a collection of statements that define what the function does.

42 /* function returning the max between two numbers */
Example: Following is the source code for a function called max(). This function takes two parameters num1 and num2 and returns the maximum between the two: /* function returning the max between two numbers */ int max(int num1, int num2) { /* local variable declaration */ int result; if (num1 > num2) result = num1; else result = num2; return result; }

43 Function Declarations
A function declaration tells the compiler about a function name and how to call the function. The actual body of the function can be defined separately. A function declaration has the following parts: return_type function_name( parameter list ); For the above defined function max(), following is the function declaration: int max(int num1, int num2); Parameter names are not important in function declaration only their type is required, so following is also valid declaration: int max(int, int); Function declaration is required when you define a function in one source file and you call that function in another file. In such case you should declare the function at the top of the file i.e. calling the function.

44 Calling a Function While creating a C function, you give a definition of what the function has to do. When a program calls a function, program control is transferred to the called function. A called function performs defined task, and when its return statement is executed, it returns program control back to the main program. To call a function, you simply need to pass the required parameters along with function name.

45 For example: #include <stdio.h> /* function declaration */
int max(int num1, int num2); int main () { /* local variable definition */ int a = 100; int b = 200; int ret; /* calling a function to get max value */ ret = max(a, b); printf( "Max value is : %d\n", ret ); return 0; }

46 /. function returning the max between two numbers
/* function returning the max between two numbers */ int max(int num1, int num2) { /* local variable declaration */ int result; if (num1 > num2) result = num1; else result = num2; return result; } It kepts max() function along with main() function and compiled the source code. While running final executable, it would produce the following result: Max value is : 200

47 Function Arguments If a function is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the function. The formal parameters behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit. While calling a function, there are two ways that arguments can be passed to a function: Function call by value Function call by reference

48 Function call by value The call by value method of passing arguments to a function copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument. By default, C programming language uses call by value method to pass arguments.

49 Consider the function swap() definition as follows:
/* function definition to swap the values */ void swap(int x, int y) { int temp; temp = x; /* save the value of x */ x = y; /* put y into x */ y = temp; /* put x into y */ return; } Now, let us call the function swap() by passing actual values as in the following example:

50 #include <stdio. h> /. function declaration
#include <stdio.h> /* function declaration */ void swap(int x, int y); int main () { /* local variable definition */ int a = 100; int b = 200; printf("Before swap, value of a : %d\n", a ); printf("Before swap, value of b : %d\n", b ); /* calling a function to swap the values */ swap(a, b);

51 printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b ); return 0; } Let us put above code in a single C file, compile and execute it, it will produce the following result: Before swap, value of a :100 Before swap, value of b :200

52 Function call by reference
The call by reference method of passing arguments to a function copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the passed argument. To pass the value by reference, argument pointers are passed to the functions just like any other value. So accordingly you need to declare the function parameters as pointer types as in the following function swap(), which exchanges the values of the two integer variables pointed to by its arguments.

53 /. function definition to swap the values. / void swap(int. x, int
/* function definition to swap the values */ void swap(int *x, int *y) { int temp; temp = *x; /* save the value at address x */ *x = *y; /* put y into x */ *y = temp; /* put x into y */ return; } Let us call the function swap() by passing values by reference as in the following example which is in subsequent slide:

54 #include <stdio. h> /. function declaration. / void swap(int
#include <stdio.h> /* function declaration */ void swap(int *x, int *y); int main () { /* local variable definition */ int a = 100; int b = 200; printf("Before swap, value of a : %d\n", a ); printf("Before swap, value of b : %d\n", b ); /* calling a function to swap the values. * &a indicates pointer to a i.e. address of variable a and * &b indicates pointer to b i.e. address of variable b. */

55 swap(&a, &b); printf("After swap, value of a : %d\n", a ); printf("After swap, value of b : %d\n", b ); return 0; } Let us put above code in a single C file, compile and execute it, it will produce the following result: Before swap, value of a :100 Before swap, value of b :200 After swap, value of a :200 After swap, value of b :100 Which shows that there is no change in the values though they had been changed inside the function.

56 C Scope Rules A scope in any programming is a region of the program where a defined variable can have its existence and beyond that variable cannot be accessed. There are three places where variables can be declared in C programming language: Inside a function or a block which is called local variables, Outside of all functions which is called global variables. In the definition of function parameters which is called formal parameters. Let us explain what are local and global variables and formal parameters.

57 Local Variables Variables that are declared inside a function or block are called local variables. They can be used only by statements that are inside that function or block of code. Following is the example using local variables. Here all the variables a, b and c are local to main() function which is explain in subsequent slide .

58 #include <stdio. h> int main () { /. local variable declaration
#include <stdio.h> int main () { /* local variable declaration */ int a, b; int c; /* actual initialization */ a = 10; b = 20; c = a + b; printf ("value of a = %d, b = %d and c = %d\n", a, b, c); return 0; }

59 Global Variables Global variables are defined outside of a function, usually on top of the program. The global variables will hold their value throughout the lifetime of your program and they can be accessed inside any of the functions defined for the program. A global variable can be accessed by any function. That is, a global variable is available for use throughout your entire program after its declaration. Following is the example using global and local variables.

60 #include <stdio. h> /. global variable declaration
#include <stdio.h> /* global variable declaration */ int g; int main () { /* local variable declaration */ int a, b; /* actual initialization */ a = 10; b = 20; g = a + b; printf ("value of a = %d, b = %d and g = %d\n", a, b, g); return 0; }

61 A program can have same name for local and global variables but value of local variable
inside a function will take preference. Following is an example: #include <stdio.h> /* global variable declaration */ int g = 20; int main () { /* local variable declaration */ int g = 10; printf ("value of g = %d\n", g); return 0; } When the above code is compiled and executed, it produces the following result: value of g = 10

62 Formal Parameters Function parameters, so called formal parameters, are treated as local variables within that function and they will take preference over the global variables. Following is an example: #include <stdio.h> /* global variable declaration */ int a = 20; int main () { /* local variable declaration in main function */ int a = 10; int b = 20; int c = 0;

63 printf ("value of a in main() = %d\n", a); c = sum( a, b); printf ("value of c in main() = %d\n", c); return 0; } /* function to add two integers */ int sum(int a, int b) { printf ("value of a in sum() = %d\n", a); printf ("value of b in sum() = %d\n", b); return a + b; When the above code is compiled and executed, it produces the following result: value of a in main() = 10 value of c in main() = 30 value of a in sum() = 10 value of b in sum() = 20

64 Initializing Local and Global Variables
When a local variable is defined, it is not initialized by the system, you must initialize it yourself. Global variables are initialized automatically by the system when you define them as follows: It is a good programming practice to initialize variables properly otherwise, your program may produce unexpected results because uninitialized variables will take some garbage value already available at its memory location Data Type Initial Default Value int Char ‘\0’ Float Double Pointer NULL

65 WAP to print sum of squares of first 20 even number by using (i) while (ii) do while (iii) for loop By using while loop: #include<stdio.h> Main() { int sum=0,i; while(i<=40) { if(i%2==0) { sum=sum+i*i; i++; } printf(“The sum of squares of Even number is : %d”, sum); Output: The sum of squares of Even number is : 11480

66 By using for loop: #include<stdio
By using for loop: #include<stdio.h> Main() { int sum=0,i; for(i=1;i<=40;i++) { if(i%2==0) { sum=sum+i*i; } printf(“The sum of squares of Even number is : %d”, sum); Output: The sum of squares of Even number is : 11480

67 By using Do while loop: #include<stdio
By using Do while loop: #include<stdio.h> Main() { int sum=0,i=1; Do { if(i%2==0) { sum=sum+i*i; i++; } while(i<=40); printf(“The sum of squares of Even number is : %d”, sum); Output: The sum of squares of Even number is : 11480

68 Read an integer through the keyboard
Read an integer through the keyboard. Sort odd and even numbers by using while loop. Write a program to add sum of odd and even number separately and display the results. #include<stdio.h> Main() { int odd=0,even=0,i=1,n; printf(“How Many Numbers are there :”); scanf(“%d”, &n); while(i<=n) { printf(“Enter the Number”); scanf(“%d”, &i); if(i%2==0) { even= even+i; } else odd= odd+i; }

69 printf(“The sum of Even Number is =%d”, even); printf(“The sum of odd Number is =%d”, odd); } Output : How many Numbers are there : 7 Enter the Number 1 Enter the Number 2 Enter the Number 3 Enter the Number 4 Enter the Number 5 Enter the Number 6 Enter the Number 7 The Sum of Even Numbers is =12 The Sum of Odd Numbers is =16

70 Q. Write a program to print the following series along with sum of first 20 terms of the series ………….. Using i) while ii) do while iii) for loop By Using For Loop #include>stdio.h> #include<math.h> Main() { int n, i, sum=0, sign=1; n=20; For(i=1;i<=20;i++) sum=sum+(sign)* pow(I,2); sign*=-1; /* Sign switches between +1` and -1 */ } printf(“Sum is =%d”, sum); Output: Sum is = -210

71 By Using While Loop #include<stdio. h> #include<math
By Using While Loop #include<stdio.h> #include<math.h> Main() { int n, i=1, sum=0, sign=1; n=20; while (i<=20) sum=sum(sign)* pow(I,2); sign*=-1; i++; } printf(“Sum is =%d”, sum); Output: Sum is = -210

72 By Using Do While Loop #include>stdio. h> #include<math
By Using Do While Loop #include>stdio.h> #include<math.h> Main() { int n, i=1, sum=0, sign=1; n=20; do sum=sum(sign)* pow(I,2); sign*=-1; i++; } while (i<=20); printf(“Sum is =%d”, sum); Output: Sum is = -210

73 WAP by do while loop to calculate the sum of odd no start from 1and less than 99. #include<stdio.h> Main() { int sum=0,i=1; do { if(i%2!=o) { sum=sum+i; i=i+2; } while(i<99); printf(“The sum of odd number is : %d”, sum); Output: The sum of odd Number is: 2401

74 Q. Find the output of following program: #include<stdio
Q. Find the output of following program: #include<stdio.h> Main() { int c=1,s=0,n; n=6; For(;c<=n;c++) s+=c; } printf(“\n sum is %d”, s); Output: sum is 21


Download ppt "Unit 3 Control Structure"

Similar presentations


Ads by Google