SlideShare una empresa de Scribd logo
1 de 37
UNIT 3 Conditional Program Execution: Applying if and switch statements, nesting if and else, restrictions on switch values, use of break and default with switch, Program Loops and Iteration: Uses of while, do and for loops, multiple loop variables, assignment operators, using break and continue, Modular Programming: Passing arguments by value, scope rules and global variables, separate compilation, and linkage, building your own modules.
The C language programs presented until now follows a sequential form of execution of statements. Many times it is required to alter the flow of the sequence of instructions. C language provides statements that can alter the flow of a sequence of instructions. These statements are called control statements. These statements help to jump from one part of the program to another. The control transfer may be conditional or unconditional.  Conditional Program Execution
if Statement  The simplest form of the control statement is the If statement. It is very frequently used in decision making and allowing the flow of program execution.  The If structure has the following syntax  if (condition)   statement;
Example program # include <stdio.h>  void main () {        int numbers;       printf (&quot;Type a number:&quot;);       scanf (&quot;%d&quot;, &number);       if (number < 0)       number = -number         printf (&quot;The absolute value is %d &quot;, number)   } Output: Type a number: -5 The absolute value is 5 The above program checks the value of the input number to see if it is less than zero. If it is then the following program statement which negates the value of the number is executed. If the value of the number is not less than zero, we do not want to negate it then this statement is automatically skipped. The absolute number is then displayed by the program, and program execution ends.
The If else construct: The syntax of the If else construct is as follows:-  If(condition) { Statement1; } else { Statement2; } The if else is actually just on extension of the general format of if statement. If the result of the condition is true, then program statement 1 is executed, otherwise program statement 2 will be executed. If any case either program statement 1 is executed or program statement 2 is executed but not both when writing programs this else statement is so frequently required that almost all programming languages provide a special construct to handle this situation.
Example Program #include <stdio.h>   void main () {       int num;       printf (&quot;Enter the number&quot;);       scanf (&quot;%d&quot;, &num);         if (num < 0)          printf (&quot;The number is negative&quot;);       else          printf (&quot;The number is positive&quot;);  } Output: Enter the number: 10 The  number is positive
The syntax in the statement ‘a’ represents a complex if statement which combines different conditions using the AND operator in this case if all the conditions are true only then the whole statement is considered to be true. Even if one condition is false the whole if statement is considered to be false.  The statement ‘b’ uses the logical operator OR (||) to group different expression to be checked. In this case if any one of the expression if found to be true the whole expression considered to be true, we can also uses the mixed expressions using logical operators AND and OR together.  Compound Relational tests:  Syntax: a> if (condition1 && condition2 && condition3)  b> if (condition1 || condition2 || condition3)
Nested if Statement  The if statement may itself contain another if statement is known as nested if statement.  Syntax:  The if statement may be nested as deeply as you need to nest it. One block of code will only be executed if two conditions are true. Condition 1 is tested first and then condition 2 is tested. The second if condition is nested in the first. The second if condition is tested only when the first condition is true else the program flow will skip to the corresponding else statement.  if (condition1)    if (condition2)       statement-1;    else       statement-2;  else        statement-3;
Example Program #include <stdio.h>  main () {        int a,b,c,big;        printf(&quot;Enter three numbers:&quot;);        scanf(&quot;%d %d %d&quot;, &a, &b, &c);       if (a > b)  {        if (a > c)           big = a;        else big = c;  }       else  { if (b > c)           big = b;         else big = c;  }       printf(&quot;Largest of %d, %d & %d = %d&quot;, a,b,c,big);      } In the above program the statement if (a>c) is nested within the if (a>b). If the first If condition if (a>b)  If (a>b) is true only then the second if statement if (a>b) is executed. If the first if condition is executed to be false then the program control shifts to the statement after corresponding else statement.
The ELSE If Ladder When a series of many conditions have to be checked we may use the ladder else if statement which takes the following general form.  This construct is known as if else construct or ladder. The conditions are evaluated from the top of the ladder to downwards. As soon on the true condition is found, the statement associated with it is executed and the control is transferred to the statement – x (skipping the rest of the ladder. When all the condition becomes false, the final else containing the default statement will be executed.  if (condition1)     statement – 1;  else if (condition2)     statement2;  else if (condition3)     statement3;  else if (condition)     statement n;  else     default statement;  statement-x;
Example program  #include <stdio.h>  void main ()  {      int  marks;        printf (&quot;Enter marks&quot;);      scanf (&quot;%d&quot;, &marks);        if (marks <= 100 && marks >= 70)           printf (&quot; Distinction&quot;) ;     else if (marks >= 60)            printf(&quot; First class&quot;);      else if (marks >= 50)            printf (&quot; second class&quot;);      else if (marks >= 35)            printf (&quot; pass class&quot;);      else            printf (&quot;Fail&quot;) ; } Marks Grade 70 to 100 60 to 69 50 to 59 40 to 49 0 to 39 DISTINCTION Ist Class Iind Class CLASS FAIL
The Switch Statement:  Unlike the If statement which allows a selection of two alternatives, the switch statement allows a program to select one statement for execution out of a set of alternatives. During the execution of the switch statement only one of the possible statements will be executed the remaining statements will be skipped. The usage of multiple If else statement increases the complexity of the program since when the number of If else statements increase it affects the readability of the program and makes it difficult to follow the program. The switch statement removes these disadvantages by using a simple and straight forward approach.  The general format of the Switch Statement is :  When the switch statement is executed the control expression is evaluated first and the value is compared with the case label values in the given order. If the label matches with the value of the expression then the control is transferred directly to the group of statements which follow the label. If none of the statements matches then the statement against the default is executed. The default statement is optional in switch statement in case if any default statement is not given and if none of the condition matches then no action takes place in this case the control transfers to the next statement of the if else statement.  switch (expression) {   case case1;   case case2;   case casen;   ………………   case default }
Example Program #include <stdio.h>  void main ()  {         int  num1, num2, result;       char operator;         printf (&quot;Enter two numbers&quot;);       scanf (&quot;%d %d&quot;, &num1, &num2) ;      printf (&quot;Enter an operator&quot;) ;      scanf (&quot;%c&quot;, &operator);        switch (operator)       {           case '+':              result = num1 + num2;             break;           case '-':              result = num1 - num2;              break;           case '*':              result = num1 * num2;              break;           case '/':              if (num2 != 0)                 result = num1 / num2;              else              {                         printf (&quot;warning : division by zero &quot;);                 result = 0;             }             break;           default:              printf (&quot; unknown operator&quot;);              result = 0;              break;       }      printf (&quot;%d&quot;, result);  }
The GOTO statement: The goto statement is simple statement used to transfer the program control unconditionally from one statement to another statement. Although it might not be essential to use the goto statement in a highly structured language like C, there may be occasions when the use of goto is desirablet The goto requires a label in order to identify the place where the branch is to be made. A label is a valid variable name followed by a colon.  The label is placed immediately before the statement where the control is to be transformed. A program may contain several goto statements that transferred to the same place when a program. The label must be unique. Control can be transferred out of or within a compound statement, and control can be transferred to the beginning of a compound statement. However the control cannot be transferred into a compound statement. The goto statement is discouraged in C, because it alters the sequential flow of logic that is the characteristic of C language.  a> goto label; ………… ………… ………… label: Statement; b>   label: ………… ………… ………… goto label;
Example Program #include <stdio.h>  main ()  {         int n, sum = 0, i = 0;         printf (&quot;Enter a number&quot;);         scanf (&quot;%d&quot;, &n) ;        loop:  i++;        sum += i ;        if (i < n) goto loop;        printf (&quot; sum of %d natural numbers = %d&quot;, n, sum)    }
Program Loops and Iteration During looping a set of statements are executed until some conditions for termination of the loop is encountered. A program loop therefore consists of two segments one known as body of the loop and other is the control statement. The control statement tests certain conditions and then directs the repeated execution of the statements contained in the body of the loop.  In looping process in general would include the following four steps  1. Setting and initialization of a counter  2. Exertion of the statements in the loop  3. Test for a specified conditions for the execution of the loop  4. Incrementing the counter  The test may be either to determine whether the loop has repeated the specified number of times or to determine whether the particular condition has been met.
The While Statement:  The simplest of all looping structure in C is the  while  statement. The general format of the while statement is:  while (test condition)  {    body of the loop  }  Here the given test condition is evaluated and if the condition is true then the body of the loop is executed. After the execution of the body, the test condition is once again evaluated and if it is true, the body is executed once again. This process of repeated execution of the body continues until the test condition finally becomes false and the control is transferred out of the loop. On exit, the program continues with the statements immediately after the body of the loop. The body of the loop may have one or more statements. The braces are needed only if the body contained two are more statements
Examples Program # include < stdio.h >  void main() {    int  n, i=0;    printf(“Enter the upper limit number”);    scanf(“%d”, &n);    while(I < = n)    {  printf(“%d”,I);    I++;   }  }
The Do while statement  The do while loop is also a kind of loop, which is similar to the while loop in contrast to while loop, the do while loop tests at the bottom of the loop after executing the body of the loop. Since the body of the loop is executed first and then the loop condition is checked we can be assured that the body of the loop is executed at least once.  The  syntax  of the do while loop is:  do  {    statement;  }  while(expression);
Example Program /* Program to illustrate the do while loop*/  #include<stdio.h> #include<conio.h> void main() { int n,i=0; printf(&quot;Enter the limit:&quot;); scanf(&quot;%d&quot;,&n); do { printf(&quot;%d&quot;,i); i++; } while(i<=n); getch(); }
The Break Statement:  Sometimes while executing a loop it becomes desirable to skip a part of the loop or quit the loop as soon as certain condition occurs, for example consider searching a particular number in a set of 100 numbers as soon as the search number is found it is desirable to terminate the loop. C language permits a jump from one statement to another within a loop as well as to jump out of the loop. The break statement allows us to accomplish this task. A break statement provides an early exit from for, while, do and switch constructs. A break causes the innermost enclosing loop or switch to be exited immediately.  Example program to illustrate the use of break statement .  /* A program to find the average of the marks*/  #include < stdio.h >  void main() {    int I, num=0;    float  sum=0,average;    printf(“Input the marks, -1 to end”);    while(1)    {    scanf(“%d”,&I);    if(I==-1)    break;    sum+=I;    num++;   } }
Continue statement:  During loop operations it may be necessary to skip a part of the body of the loop under certain conditions. Like the break statement C supports similar statement called continue statement. The continue statement causes the loop to be continued with the next iteration after skipping any statement in between. The continue with the next iteration the format of the continue statement is simply:  Continue;  Consider the following program that finds the sum of five positive integers. If a negative number is entered, the sum is not performed since the remaining part of the loop is skipped using continue statement.  #include < stdio.h >  void main() {    int I=1, num, sum=0;    for (I = 0; I < 5; I++)    {    printf(“Enter the integer”);    scanf(“%I”, &num);    if(num < 0)    {    printf(“You have entered a negative number”);    continue;    }    sum+=num;    }    printf(“The sum of positive numbers entered = %d”,sum);  }
For Loop  The for loop provides a more concise loop control structure. The general form of the for loop is:  for (initialization; test condition; increment)  {  body of the loop  }  When the control enters for loop the variables used in for loop is initialized with the starting value such as I=0,count=0. The value which was initialized is then checked with the given test condition. The test condition is a relational expression, such as I < 5 that checks whether the given condition is satisfied or not if the given condition is satisfied the control enters the body of the loop or else it will exit the loop. The body of the loop is entered only if the test condition is satisfied and after the completion of the execution of the loop the control is transferred back to the increment part of the loop. The control variable is incremented using an assignment statement such as I=I+1 or simply I++ and the new value of the control variable is again tested to check whether it satisfies the loop condition. If the value of the control variable satisfies then the body of the loop is again executed. The process goes on till the control variable fails to satisfy the condition.
Additional features of the for loop   We can include multiple expressions in any of the fields of for loop provided that we separate such expressions by commas. For example in the for statement that begins  for( I = 0; j = 0; I < 10, j=j-10)  The initialization expression field can simply be “left blank” in such a case as long as the semicolon is still included:  for(;j!=100;++j)  The above statement might be used if j were already set to some initial value before the loop was entered. A for loop that has its looping condition field omitted effectively sets up an infinite loop, that is a loop that theoretically will be executed for ever.
For loop example program:  /* The following is an example that finds the sum of the first fifteen positive natural numbers*/  #include < stdio.h >  void main() {    int I;    int sum=0,sum_of_squares=0;    for(I=0;I < = 30; I+=2)    {    sum+=I;    sum_of_squares += I*I;    }    printf(“Sum of first 15 positive even numbers=%d”,sum);    printf(“Sum of their squares=%d”,sum_of_squares);  }
Functions (Modular Programming) The basic philosophy of function is divide and conquer by which a complicated tasks are successively divided into simpler and more manageable tasks which can be easily handled. A program can be divided into smaller subprograms that can be developed and tested successfully. A function is a complete and independent program which is used (or invoked) by the main program or other subprograms. A subprogram receives values called arguments from a calling program, performs calculations and returns the results to the calling program. There are many advantages in using functions in a program they are: 1.  It facilitates top down modular programming. In this programming style, the high level  logic of the overall problem is solved first while the details of each lower level functions  is addressed later.  2.  the length of the source program can be reduced by using functions at appropriate  places.This factor is critical with microcomputers where  memory  space is limited.  3.  It is easy to locate and isolate a faulty function for further investigation.  4.  A function may be used by many other programs this means that a c programmer can  build on what others have already done, instead of starting over from scratch.  5.  A program can be used to avoid rewriting the same sequence of code at two or more  locations in a program. This is especially useful if the code involved is long or  complicated.  6.  Programming teams does a large percentage of programming. If the program is divided into  subprograms, each subprogram can be written by one or two team members of the team rather than  having the whole team to work on the complex program
Function definition [ data type]  function name (argument list)  {    local variable declarations;    statements;    [return expression]  }  Example  mul(int a,int b)  {    int y;    y=a+b;    return y;  }  When the value of y which is the addition of the values of a and b. the last two statements ie,  y=a+b; can be combined as  return(y)  return(a+b);
Types of functions:  A function may belong to any one of the following categories:  1. Functions with no arguments and no return values.  2. Functions with arguments and no return values.  3. Functions with arguments and return values.  Functions with no arguments and no return values:  Let us consider the following program  /* Program to illustrate a function with no argument and no return values*/  #include <stdio.h> void main()  {    statement1();    starline();    statement2();    starline();  }  /*function to print a message*/  statement1()  {    printf(“ Sample subprogram output”);  }  statement2()  {    printf(“ Sample subprogram output  two”);  }  starline()  {    int a;    for (a=1;a<60;a++)    printf(“*”);    printf(“”);  }
Functions with arguments but no return values: The formal arguments may be valid variable names, the actual arguments may be variable names expressions or constants. The values used in actual arguments must be assigned values before the function call is made.  When a function call is made only a copy of the values actual arguments is passed to the called function. What occurs inside the functions will have no effect on the  variables  used in the actual argument list.  Let us consider the following program  /*Program to find the largest of two numbers using function*/  #include<stdio.h>  main()  {    int a,b;    printf(“Enter the two numbers”);    scanf(“%d%d”,&a,&b);    largest(a,b)  }  /*Function to find the largest of two numbers*/  largest(int a, int b)  {  if(a>b)    printf(“Largest element=%d”,a);  else    printf(“Largest element=%d”,b);  }  in the above program we could make the calling function to read the data from the terminal and pass it on to the called function. But function foes not return any value.
Functions with arguments and return values:  ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
CONTD….. 2. The called function must be declared at the start of the body in the calling function, like any other variable. This is to tell the calling function the type of data the function is actually returning. The program given below illustrates the transfer of a floating-point value between functions done in a multiple function program.  #include<stdio.h> float add(float,float); double sub(double,double); void main() { float x,y; x=12.345; y=9.82; printf(&quot;%f&quot;,add(x,y)); printf(&quot;%lf&quot;,sub(x,y)); } float add(float a,float b) { return(a+b); } double sub(double p,double q) { return(p-q); } We can notice that the functions too are declared along with the variables. These declarations clarify to the compiler that the return type of the function add is float and sub is double.
Void functions:  The functions that do not return any values can be explicitly defined as void. This prevents any accidental use of these functions in expressions.  Nesting of functions:  C permits nesting of two functions freely. There is no limit how deeply functions can be nested. Suppose a function a can call function b and function b can call function c and so on. Consider the following program:  #include<stdio.h> float ratio(int,int,int); int difference(int,int); void main() { int a,b,c; scanf(&quot;%d%d%d&quot;,&a,&b,&c); printf(&quot;%f&quot;,ratio(a,b,c)); } float ratio(int x,int y,int z) { if(difference(y,z))   return(x/(y-z)); else   return(0.0); } difference(int p,int q) { if(p!=q) return(1); else return(0); }
CONTD…. the above program calculates the ratio a/b-c;  and prints the result. We have the following three functions:  main()  ratio()  difference()  main reads the value of a,b,c and calls the function ratio to calculate the value a/b-c) this ratio cannot be evaluated if(b-c) is zero. Therefore ratio calls another function difference to test whether the difference(b-c) is zero or not
The scope and lifetime of variables in functions:  The scope and lifetime of the variables define in C is not same when compared to other languages. The scope and lifetime depends on the storage class of the variable in c language the variables can be any one of the four storage classes:  1. Automatic Variables  2. External variable  3. Static variable  4. Register variable.  Automatic variables:  Automatic variables are declared inside a particular function and they are created when the function is called and destroyed when the function exits. Automatic variables are local or private to a function in which they are defined by default all variable declared without any storage specification is automatic. The values of variable remains unchanged to the changes that may happen in other functions in the same program and by doing this no error occurs.  #include<stdio.h> void main()  {  int m=1000;  function2();  printf(“%d”,m);  }  function1()  {  int m=10;  printf(“%d”,m);  }  function2()  {  int m=100;  function1();  printf(“%d”,m);  }
External variables:  Variables which are common to all functions and accessible by all functions of aprogram are internal variables. External variables can be declared outside a function.  Example  int sum;  float percentage;  main()  {  …..  …..  }  function1()  {  ….  ….  }   function2()  {  ….  ….  }   The variables sum and percentage are available for use in all the three functions main, function1, function2.  Local variables take precedence over global variables of the same name.
Static variables:  The value given to a variable declared by using keyword static persistes until the end of the program.  A static variable is initialized only once, when the program is compiled. It is never initialized again. During the first call to stat in the example shown below x is incremented to 1. because x is static, this value persists and therefore the next call adds another 1 to x giving it a value of 2. The value of x becomes 3 when third call is made. If we had declared x as an auto then output would here been x=1 all the three times.  main()  {    int j;    for(j=1;j<3;j++)    stat();  }  stat()  {    static int x=0;    x=x+1;    printf(“x=%d”,x);  }
Register variables:  A variable is usually stored in the memory but it is also possible to store a varible in the compilers register by defining it as register variable. The registers access is much faster than a memory access, keeping the frequently accessed variables in the register will make the execution of the program faster.  This is done as follows:  register int count;

Más contenido relacionado

La actualidad más candente

Control Structures
Control StructuresControl Structures
Control Structures
Ghaffar Khan
 

La actualidad más candente (20)

Maxbox starter
Maxbox starterMaxbox starter
Maxbox starter
 
Learn C# Programming - Decision Making & Loops
Learn C# Programming - Decision Making & LoopsLearn C# Programming - Decision Making & Loops
Learn C# Programming - Decision Making & Loops
 
Lecture13 control statementswitch.ppt
Lecture13 control statementswitch.pptLecture13 control statementswitch.ppt
Lecture13 control statementswitch.ppt
 
Control Structures
Control StructuresControl Structures
Control Structures
 
Introduction To Programming with Python Lecture 2
Introduction To Programming with Python Lecture 2Introduction To Programming with Python Lecture 2
Introduction To Programming with Python Lecture 2
 
Bt0067 c programming and data structures 1
Bt0067 c programming and data structures 1Bt0067 c programming and data structures 1
Bt0067 c programming and data structures 1
 
Types of Statements in Python Programming Language
Types of Statements in Python Programming LanguageTypes of Statements in Python Programming Language
Types of Statements in Python Programming Language
 
Conditions In C# C-Sharp
Conditions In C# C-SharpConditions In C# C-Sharp
Conditions In C# C-Sharp
 
Declaration of variables
Declaration of variablesDeclaration of variables
Declaration of variables
 
Ch4 Expressions
Ch4 ExpressionsCh4 Expressions
Ch4 Expressions
 
Control Structures: Part 1
Control Structures: Part 1Control Structures: Part 1
Control Structures: Part 1
 
Control structures i
Control structures i Control structures i
Control structures i
 
C interview questions
C interview  questionsC interview  questions
C interview questions
 
C language 2
C language 2C language 2
C language 2
 
Fortran 90 Basics
Fortran 90 BasicsFortran 90 Basics
Fortran 90 Basics
 
The Three Basic Selection Structures in C++ Programming Concepts
The Three Basic Selection Structures in C++ Programming ConceptsThe Three Basic Selection Structures in C++ Programming Concepts
The Three Basic Selection Structures in C++ Programming Concepts
 
Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statements
 
Control structures ii
Control structures ii Control structures ii
Control structures ii
 
Decision statements in c language
Decision statements in c languageDecision statements in c language
Decision statements in c language
 
C decision making and looping.
C decision making and looping.C decision making and looping.
C decision making and looping.
 

Destacado

Destacado (15)

Learning the C Language
Learning the C LanguageLearning the C Language
Learning the C Language
 
Memory management of datatypes
Memory management of datatypesMemory management of datatypes
Memory management of datatypes
 
Unit4 Slides
Unit4 SlidesUnit4 Slides
Unit4 Slides
 
Mechanics of materials
Mechanics of materialsMechanics of materials
Mechanics of materials
 
differential equations Boyce & Diprima Solution manual
differential equations Boyce & Diprima Solution manualdifferential equations Boyce & Diprima Solution manual
differential equations Boyce & Diprima Solution manual
 
Higher order differential equations
Higher order differential equationsHigher order differential equations
Higher order differential equations
 
Storage classes in C
Storage classes in CStorage classes in C
Storage classes in C
 
CO By Rakesh Roshan
CO By Rakesh RoshanCO By Rakesh Roshan
CO By Rakesh Roshan
 
Unit 2 stresses in composite sections
Unit 2  stresses in composite sectionsUnit 2  stresses in composite sections
Unit 2 stresses in composite sections
 
2 axial loading- Mechanics of Materials - 4th - Beer
2 axial loading- Mechanics of Materials - 4th - Beer2 axial loading- Mechanics of Materials - 4th - Beer
2 axial loading- Mechanics of Materials - 4th - Beer
 
3 torsion- Mechanics of Materials - 4th - Beer
3 torsion- Mechanics of Materials - 4th - Beer3 torsion- Mechanics of Materials - 4th - Beer
3 torsion- Mechanics of Materials - 4th - Beer
 
Higher Differential Equation
Higher Differential EquationHigher Differential Equation
Higher Differential Equation
 
02 first order differential equations
02 first order differential equations02 first order differential equations
02 first order differential equations
 
Mechanics of materials lecture 01, Engr. Abdullah Khan
Mechanics of materials lecture 01, Engr. Abdullah KhanMechanics of materials lecture 01, Engr. Abdullah Khan
Mechanics of materials lecture 01, Engr. Abdullah Khan
 
Higher Differential Equation
Higher Differential Equation Higher Differential Equation
Higher Differential Equation
 

Similar a C language UPTU Unit3 Slides

Dti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selectionDti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selection
alish sha
 
Dti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selectionDti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selection
alish sha
 
Fundamentals of prog. by rubferd medina
Fundamentals of prog. by rubferd medinaFundamentals of prog. by rubferd medina
Fundamentals of prog. by rubferd medina
rurumedina
 
C statements.ppt presentation in c language
C statements.ppt presentation in c languageC statements.ppt presentation in c language
C statements.ppt presentation in c language
chintupro9
 

Similar a C language UPTU Unit3 Slides (20)

Control statements-Computer programming
Control statements-Computer programmingControl statements-Computer programming
Control statements-Computer programming
 
Control Structures in C
Control Structures in CControl Structures in C
Control Structures in C
 
Control All
Control AllControl All
Control All
 
Controls & Loops in C
Controls & Loops in C Controls & Loops in C
Controls & Loops in C
 
C Programming Unit-2
C Programming Unit-2C Programming Unit-2
C Programming Unit-2
 
Decision statements in c laguage
Decision statements in c laguageDecision statements in c laguage
Decision statements in c laguage
 
Dti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selectionDti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selection
 
Dti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selectionDti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selection
 
Fundamentals of prog. by rubferd medina
Fundamentals of prog. by rubferd medinaFundamentals of prog. by rubferd medina
Fundamentals of prog. by rubferd medina
 
Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8
 
C programming session3
C programming  session3C programming  session3
C programming session3
 
C programming session3
C programming  session3C programming  session3
C programming session3
 
C statements.ppt presentation in c language
C statements.ppt presentation in c languageC statements.ppt presentation in c language
C statements.ppt presentation in c language
 
C Programming: Control Structure
C Programming: Control StructureC Programming: Control Structure
C Programming: Control Structure
 
Unit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in CUnit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in C
 
Ch04
Ch04Ch04
Ch04
 
computer programming Control Statements.pptx
computer programming Control Statements.pptxcomputer programming Control Statements.pptx
computer programming Control Statements.pptx
 
2. Control structures with for while and do while.ppt
2. Control structures with for while and do while.ppt2. Control structures with for while and do while.ppt
2. Control structures with for while and do while.ppt
 
Fundamentals of programming)
Fundamentals of programming)Fundamentals of programming)
Fundamentals of programming)
 
Lecture 1
Lecture 1Lecture 1
Lecture 1
 

Último

Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
AnaAcapella
 

Último (20)

Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 

C language UPTU Unit3 Slides

  • 1. UNIT 3 Conditional Program Execution: Applying if and switch statements, nesting if and else, restrictions on switch values, use of break and default with switch, Program Loops and Iteration: Uses of while, do and for loops, multiple loop variables, assignment operators, using break and continue, Modular Programming: Passing arguments by value, scope rules and global variables, separate compilation, and linkage, building your own modules.
  • 2. The C language programs presented until now follows a sequential form of execution of statements. Many times it is required to alter the flow of the sequence of instructions. C language provides statements that can alter the flow of a sequence of instructions. These statements are called control statements. These statements help to jump from one part of the program to another. The control transfer may be conditional or unconditional. Conditional Program Execution
  • 3. if Statement The simplest form of the control statement is the If statement. It is very frequently used in decision making and allowing the flow of program execution. The If structure has the following syntax if (condition) statement;
  • 4. Example program # include <stdio.h> void main () {       int numbers;       printf (&quot;Type a number:&quot;);       scanf (&quot;%d&quot;, &number);       if (number < 0)       number = -number         printf (&quot;The absolute value is %d &quot;, number)   } Output: Type a number: -5 The absolute value is 5 The above program checks the value of the input number to see if it is less than zero. If it is then the following program statement which negates the value of the number is executed. If the value of the number is not less than zero, we do not want to negate it then this statement is automatically skipped. The absolute number is then displayed by the program, and program execution ends.
  • 5. The If else construct: The syntax of the If else construct is as follows:- If(condition) { Statement1; } else { Statement2; } The if else is actually just on extension of the general format of if statement. If the result of the condition is true, then program statement 1 is executed, otherwise program statement 2 will be executed. If any case either program statement 1 is executed or program statement 2 is executed but not both when writing programs this else statement is so frequently required that almost all programming languages provide a special construct to handle this situation.
  • 6. Example Program #include <stdio.h>   void main () {     int num;     printf (&quot;Enter the number&quot;);     scanf (&quot;%d&quot;, &num);       if (num < 0)         printf (&quot;The number is negative&quot;);     else         printf (&quot;The number is positive&quot;); } Output: Enter the number: 10 The number is positive
  • 7. The syntax in the statement ‘a’ represents a complex if statement which combines different conditions using the AND operator in this case if all the conditions are true only then the whole statement is considered to be true. Even if one condition is false the whole if statement is considered to be false. The statement ‘b’ uses the logical operator OR (||) to group different expression to be checked. In this case if any one of the expression if found to be true the whole expression considered to be true, we can also uses the mixed expressions using logical operators AND and OR together. Compound Relational tests: Syntax: a> if (condition1 && condition2 && condition3) b> if (condition1 || condition2 || condition3)
  • 8. Nested if Statement The if statement may itself contain another if statement is known as nested if statement. Syntax: The if statement may be nested as deeply as you need to nest it. One block of code will only be executed if two conditions are true. Condition 1 is tested first and then condition 2 is tested. The second if condition is nested in the first. The second if condition is tested only when the first condition is true else the program flow will skip to the corresponding else statement. if (condition1)    if (condition2)       statement-1;    else       statement-2;  else       statement-3;
  • 9. Example Program #include <stdio.h> main () {       int a,b,c,big;       printf(&quot;Enter three numbers:&quot;);       scanf(&quot;%d %d %d&quot;, &a, &b, &c);       if (a > b) {       if (a > c)         big = a;       else big = c; }       else { if (b > c)         big = b;       else big = c; }       printf(&quot;Largest of %d, %d & %d = %d&quot;, a,b,c,big);     } In the above program the statement if (a>c) is nested within the if (a>b). If the first If condition if (a>b) If (a>b) is true only then the second if statement if (a>b) is executed. If the first if condition is executed to be false then the program control shifts to the statement after corresponding else statement.
  • 10. The ELSE If Ladder When a series of many conditions have to be checked we may use the ladder else if statement which takes the following general form. This construct is known as if else construct or ladder. The conditions are evaluated from the top of the ladder to downwards. As soon on the true condition is found, the statement associated with it is executed and the control is transferred to the statement – x (skipping the rest of the ladder. When all the condition becomes false, the final else containing the default statement will be executed. if (condition1)    statement – 1; else if (condition2)    statement2; else if (condition3)    statement3; else if (condition)    statement n; else    default statement; statement-x;
  • 11. Example program #include <stdio.h> void main () {     int marks;       printf (&quot;Enter marks&quot;);     scanf (&quot;%d&quot;, &marks);       if (marks <= 100 && marks >= 70)           printf (&quot; Distinction&quot;) ;     else if (marks >= 60)           printf(&quot; First class&quot;);     else if (marks >= 50)           printf (&quot; second class&quot;);     else if (marks >= 35)           printf (&quot; pass class&quot;);     else           printf (&quot;Fail&quot;) ; } Marks Grade 70 to 100 60 to 69 50 to 59 40 to 49 0 to 39 DISTINCTION Ist Class Iind Class CLASS FAIL
  • 12. The Switch Statement: Unlike the If statement which allows a selection of two alternatives, the switch statement allows a program to select one statement for execution out of a set of alternatives. During the execution of the switch statement only one of the possible statements will be executed the remaining statements will be skipped. The usage of multiple If else statement increases the complexity of the program since when the number of If else statements increase it affects the readability of the program and makes it difficult to follow the program. The switch statement removes these disadvantages by using a simple and straight forward approach. The general format of the Switch Statement is : When the switch statement is executed the control expression is evaluated first and the value is compared with the case label values in the given order. If the label matches with the value of the expression then the control is transferred directly to the group of statements which follow the label. If none of the statements matches then the statement against the default is executed. The default statement is optional in switch statement in case if any default statement is not given and if none of the condition matches then no action takes place in this case the control transfers to the next statement of the if else statement. switch (expression) { case case1; case case2; case casen; ……………… case default }
  • 13. Example Program #include <stdio.h> void main () {       int num1, num2, result;     char operator;       printf (&quot;Enter two numbers&quot;);     scanf (&quot;%d %d&quot;, &num1, &num2) ;     printf (&quot;Enter an operator&quot;) ;     scanf (&quot;%c&quot;, &operator);       switch (operator)     {         case '+':           result = num1 + num2;           break;         case '-':           result = num1 - num2;           break;         case '*':           result = num1 * num2;           break;         case '/':           if (num2 != 0)               result = num1 / num2;           else           {                       printf (&quot;warning : division by zero &quot;);               result = 0;           }           break;         default:           printf (&quot; unknown operator&quot;);           result = 0;           break;     }     printf (&quot;%d&quot;, result); }
  • 14. The GOTO statement: The goto statement is simple statement used to transfer the program control unconditionally from one statement to another statement. Although it might not be essential to use the goto statement in a highly structured language like C, there may be occasions when the use of goto is desirablet The goto requires a label in order to identify the place where the branch is to be made. A label is a valid variable name followed by a colon. The label is placed immediately before the statement where the control is to be transformed. A program may contain several goto statements that transferred to the same place when a program. The label must be unique. Control can be transferred out of or within a compound statement, and control can be transferred to the beginning of a compound statement. However the control cannot be transferred into a compound statement. The goto statement is discouraged in C, because it alters the sequential flow of logic that is the characteristic of C language. a> goto label; ………… ………… ………… label: Statement; b>  label: ………… ………… ………… goto label;
  • 15. Example Program #include <stdio.h> main () {       int n, sum = 0, i = 0;       printf (&quot;Enter a number&quot;);       scanf (&quot;%d&quot;, &n) ;       loop: i++;       sum += i ;       if (i < n) goto loop;       printf (&quot; sum of %d natural numbers = %d&quot;, n, sum)   }
  • 16. Program Loops and Iteration During looping a set of statements are executed until some conditions for termination of the loop is encountered. A program loop therefore consists of two segments one known as body of the loop and other is the control statement. The control statement tests certain conditions and then directs the repeated execution of the statements contained in the body of the loop. In looping process in general would include the following four steps 1. Setting and initialization of a counter 2. Exertion of the statements in the loop 3. Test for a specified conditions for the execution of the loop 4. Incrementing the counter The test may be either to determine whether the loop has repeated the specified number of times or to determine whether the particular condition has been met.
  • 17. The While Statement: The simplest of all looping structure in C is the while statement. The general format of the while statement is: while (test condition) { body of the loop } Here the given test condition is evaluated and if the condition is true then the body of the loop is executed. After the execution of the body, the test condition is once again evaluated and if it is true, the body is executed once again. This process of repeated execution of the body continues until the test condition finally becomes false and the control is transferred out of the loop. On exit, the program continues with the statements immediately after the body of the loop. The body of the loop may have one or more statements. The braces are needed only if the body contained two are more statements
  • 18. Examples Program # include < stdio.h > void main() { int n, i=0; printf(“Enter the upper limit number”); scanf(“%d”, &n); while(I < = n) { printf(“%d”,I); I++; } }
  • 19. The Do while statement The do while loop is also a kind of loop, which is similar to the while loop in contrast to while loop, the do while loop tests at the bottom of the loop after executing the body of the loop. Since the body of the loop is executed first and then the loop condition is checked we can be assured that the body of the loop is executed at least once. The syntax of the do while loop is: do { statement; } while(expression);
  • 20. Example Program /* Program to illustrate the do while loop*/ #include<stdio.h> #include<conio.h> void main() { int n,i=0; printf(&quot;Enter the limit:&quot;); scanf(&quot;%d&quot;,&n); do { printf(&quot;%d&quot;,i); i++; } while(i<=n); getch(); }
  • 21. The Break Statement: Sometimes while executing a loop it becomes desirable to skip a part of the loop or quit the loop as soon as certain condition occurs, for example consider searching a particular number in a set of 100 numbers as soon as the search number is found it is desirable to terminate the loop. C language permits a jump from one statement to another within a loop as well as to jump out of the loop. The break statement allows us to accomplish this task. A break statement provides an early exit from for, while, do and switch constructs. A break causes the innermost enclosing loop or switch to be exited immediately. Example program to illustrate the use of break statement . /* A program to find the average of the marks*/ #include < stdio.h > void main() { int I, num=0; float sum=0,average; printf(“Input the marks, -1 to end”); while(1) { scanf(“%d”,&I); if(I==-1) break; sum+=I; num++; } }
  • 22. Continue statement: During loop operations it may be necessary to skip a part of the body of the loop under certain conditions. Like the break statement C supports similar statement called continue statement. The continue statement causes the loop to be continued with the next iteration after skipping any statement in between. The continue with the next iteration the format of the continue statement is simply: Continue; Consider the following program that finds the sum of five positive integers. If a negative number is entered, the sum is not performed since the remaining part of the loop is skipped using continue statement. #include < stdio.h > void main() { int I=1, num, sum=0; for (I = 0; I < 5; I++) { printf(“Enter the integer”); scanf(“%I”, &num); if(num < 0) { printf(“You have entered a negative number”); continue; } sum+=num; } printf(“The sum of positive numbers entered = %d”,sum); }
  • 23. For Loop The for loop provides a more concise loop control structure. The general form of the for loop is: for (initialization; test condition; increment) { body of the loop } When the control enters for loop the variables used in for loop is initialized with the starting value such as I=0,count=0. The value which was initialized is then checked with the given test condition. The test condition is a relational expression, such as I < 5 that checks whether the given condition is satisfied or not if the given condition is satisfied the control enters the body of the loop or else it will exit the loop. The body of the loop is entered only if the test condition is satisfied and after the completion of the execution of the loop the control is transferred back to the increment part of the loop. The control variable is incremented using an assignment statement such as I=I+1 or simply I++ and the new value of the control variable is again tested to check whether it satisfies the loop condition. If the value of the control variable satisfies then the body of the loop is again executed. The process goes on till the control variable fails to satisfy the condition.
  • 24. Additional features of the for loop We can include multiple expressions in any of the fields of for loop provided that we separate such expressions by commas. For example in the for statement that begins for( I = 0; j = 0; I < 10, j=j-10) The initialization expression field can simply be “left blank” in such a case as long as the semicolon is still included: for(;j!=100;++j) The above statement might be used if j were already set to some initial value before the loop was entered. A for loop that has its looping condition field omitted effectively sets up an infinite loop, that is a loop that theoretically will be executed for ever.
  • 25. For loop example program: /* The following is an example that finds the sum of the first fifteen positive natural numbers*/ #include < stdio.h > void main() { int I; int sum=0,sum_of_squares=0; for(I=0;I < = 30; I+=2) { sum+=I; sum_of_squares += I*I; } printf(“Sum of first 15 positive even numbers=%d”,sum); printf(“Sum of their squares=%d”,sum_of_squares); }
  • 26. Functions (Modular Programming) The basic philosophy of function is divide and conquer by which a complicated tasks are successively divided into simpler and more manageable tasks which can be easily handled. A program can be divided into smaller subprograms that can be developed and tested successfully. A function is a complete and independent program which is used (or invoked) by the main program or other subprograms. A subprogram receives values called arguments from a calling program, performs calculations and returns the results to the calling program. There are many advantages in using functions in a program they are: 1. It facilitates top down modular programming. In this programming style, the high level logic of the overall problem is solved first while the details of each lower level functions is addressed later. 2. the length of the source program can be reduced by using functions at appropriate places.This factor is critical with microcomputers where memory space is limited. 3. It is easy to locate and isolate a faulty function for further investigation. 4. A function may be used by many other programs this means that a c programmer can build on what others have already done, instead of starting over from scratch. 5. A program can be used to avoid rewriting the same sequence of code at two or more locations in a program. This is especially useful if the code involved is long or complicated. 6. Programming teams does a large percentage of programming. If the program is divided into subprograms, each subprogram can be written by one or two team members of the team rather than having the whole team to work on the complex program
  • 27. Function definition [ data type] function name (argument list) { local variable declarations; statements; [return expression] } Example mul(int a,int b) { int y; y=a+b; return y; } When the value of y which is the addition of the values of a and b. the last two statements ie, y=a+b; can be combined as return(y) return(a+b);
  • 28. Types of functions: A function may belong to any one of the following categories: 1. Functions with no arguments and no return values. 2. Functions with arguments and no return values. 3. Functions with arguments and return values. Functions with no arguments and no return values: Let us consider the following program /* Program to illustrate a function with no argument and no return values*/ #include <stdio.h> void main() { statement1(); starline(); statement2(); starline(); } /*function to print a message*/ statement1() { printf(“ Sample subprogram output”); } statement2() { printf(“ Sample subprogram output two”); } starline() { int a; for (a=1;a<60;a++) printf(“*”); printf(“”); }
  • 29. Functions with arguments but no return values: The formal arguments may be valid variable names, the actual arguments may be variable names expressions or constants. The values used in actual arguments must be assigned values before the function call is made. When a function call is made only a copy of the values actual arguments is passed to the called function. What occurs inside the functions will have no effect on the variables used in the actual argument list. Let us consider the following program /*Program to find the largest of two numbers using function*/ #include<stdio.h> main() { int a,b; printf(“Enter the two numbers”); scanf(“%d%d”,&a,&b); largest(a,b) } /*Function to find the largest of two numbers*/ largest(int a, int b) { if(a>b) printf(“Largest element=%d”,a); else printf(“Largest element=%d”,b); } in the above program we could make the calling function to read the data from the terminal and pass it on to the called function. But function foes not return any value.
  • 30.
  • 31. CONTD….. 2. The called function must be declared at the start of the body in the calling function, like any other variable. This is to tell the calling function the type of data the function is actually returning. The program given below illustrates the transfer of a floating-point value between functions done in a multiple function program. #include<stdio.h> float add(float,float); double sub(double,double); void main() { float x,y; x=12.345; y=9.82; printf(&quot;%f&quot;,add(x,y)); printf(&quot;%lf&quot;,sub(x,y)); } float add(float a,float b) { return(a+b); } double sub(double p,double q) { return(p-q); } We can notice that the functions too are declared along with the variables. These declarations clarify to the compiler that the return type of the function add is float and sub is double.
  • 32. Void functions: The functions that do not return any values can be explicitly defined as void. This prevents any accidental use of these functions in expressions. Nesting of functions: C permits nesting of two functions freely. There is no limit how deeply functions can be nested. Suppose a function a can call function b and function b can call function c and so on. Consider the following program: #include<stdio.h> float ratio(int,int,int); int difference(int,int); void main() { int a,b,c; scanf(&quot;%d%d%d&quot;,&a,&b,&c); printf(&quot;%f&quot;,ratio(a,b,c)); } float ratio(int x,int y,int z) { if(difference(y,z)) return(x/(y-z)); else return(0.0); } difference(int p,int q) { if(p!=q) return(1); else return(0); }
  • 33. CONTD…. the above program calculates the ratio a/b-c; and prints the result. We have the following three functions: main() ratio() difference() main reads the value of a,b,c and calls the function ratio to calculate the value a/b-c) this ratio cannot be evaluated if(b-c) is zero. Therefore ratio calls another function difference to test whether the difference(b-c) is zero or not
  • 34. The scope and lifetime of variables in functions: The scope and lifetime of the variables define in C is not same when compared to other languages. The scope and lifetime depends on the storage class of the variable in c language the variables can be any one of the four storage classes: 1. Automatic Variables 2. External variable 3. Static variable 4. Register variable. Automatic variables: Automatic variables are declared inside a particular function and they are created when the function is called and destroyed when the function exits. Automatic variables are local or private to a function in which they are defined by default all variable declared without any storage specification is automatic. The values of variable remains unchanged to the changes that may happen in other functions in the same program and by doing this no error occurs. #include<stdio.h> void main() { int m=1000; function2(); printf(“%d”,m); } function1() { int m=10; printf(“%d”,m); } function2() { int m=100; function1(); printf(“%d”,m); }
  • 35. External variables: Variables which are common to all functions and accessible by all functions of aprogram are internal variables. External variables can be declared outside a function. Example int sum; float percentage; main() { ….. ….. } function1() { …. …. } function2() { …. …. } The variables sum and percentage are available for use in all the three functions main, function1, function2.  Local variables take precedence over global variables of the same name.
  • 36. Static variables: The value given to a variable declared by using keyword static persistes until the end of the program. A static variable is initialized only once, when the program is compiled. It is never initialized again. During the first call to stat in the example shown below x is incremented to 1. because x is static, this value persists and therefore the next call adds another 1 to x giving it a value of 2. The value of x becomes 3 when third call is made. If we had declared x as an auto then output would here been x=1 all the three times. main() { int j; for(j=1;j<3;j++) stat(); } stat() { static int x=0; x=x+1; printf(“x=%d”,x); }
  • 37. Register variables: A variable is usually stored in the memory but it is also possible to store a varible in the compilers register by defining it as register variable. The registers access is much faster than a memory access, keeping the frequently accessed variables in the register will make the execution of the program faster. This is done as follows: register int count;