SlideShare a Scribd company logo
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 \n&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\n&quot;);      scanf (&quot;%d&quot;, &marks);        if (marks <= 100 && marks >= 70)           printf (&quot;\n Distinction&quot;) ;     else if (marks >= 60)            printf(&quot;\n First class&quot;);      else if (marks >= 50)            printf (&quot;\n second class&quot;);      else if (marks >= 35)            printf (&quot;\n 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 \n&quot;);                 result = 0;             }             break;           default:              printf (&quot;\n 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;\n 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(“\t%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;\nEnter the limit:&quot;); scanf(&quot;%d&quot;,&n); do { printf(&quot;\n%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\n”);    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\n”,sum);    printf(“Sum of their squares=%d\n”,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(“\n Sample subprogram output”);  }  statement2()  {    printf(“\n Sample subprogram output  two”);  }  starline()  {    int a;    for (a=1;a<60;a++)    printf(“*”);    printf(“\n”);  }
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:  The function of the type Arguments with return values will send arguments from the calling function to the called function and expects the result to be returned back from the called function back to the calling function.  A C function returns a value of type int as the default data type when no other type is specified explicitly. For example if function does all the calculations by using float values and if the return statement such as return (sum); returns only the integer part of the sum. This is since we have not specified any return type for the sum. There is the necessity in some cases it is important to receive float or character or double data type. To enable a calling function to receive a non-integer value from a called function we can do the two things:    The explicit type specifier corresponding to the data type required must be mentioned in the function header. The general form of the function definition is  Type_specifier function_name(argument list)  Argument declaration;  {  function statement;  }    The type specifier tells the  compiler , the type of data the function is to return.
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\n&quot;,add(x,y)); printf(&quot;%lf\n&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\n&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\n”,m);  }  function1()  {  int m=10;  printf(“%d\n”,m);  }  function2()  {  int m=100;  function1();  printf(“%d\n”,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\n”,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;

More Related Content

What's hot (20)

PDF
Maxbox starter
Max Kleiner
 
PDF
Learn C# Programming - Decision Making & Loops
Eng Teong Cheah
 
PDF
Lecture13 control statementswitch.ppt
eShikshak
 
PPT
Control Structures
Ghaffar Khan
 
PPTX
Introduction To Programming with Python Lecture 2
Syed Farjad Zia Zaidi
 
PDF
Bt0067 c programming and data structures 1
Techglyphs
 
PPTX
Types of Statements in Python Programming Language
Explore Skilled
 
PPTX
Conditions In C# C-Sharp
Abid Kohistani
 
PPT
Declaration of variables
Maria Stella Solon
 
PPTX
Ch4 Expressions
SzeChingChen
 
PPT
Control Structures: Part 1
Andy Juan Sarango Veliz
 
PPT
Control structures i
Ahmad Idrees
 
PDF
C interview questions
Kuntal Bhowmick
 
PPTX
C language 2
Arafat Bin Reza
 
PDF
Fortran 90 Basics
Tariqul Dipu
 
PPT
The Three Basic Selection Structures in C++ Programming Concepts
Tech
 
PDF
Loops and conditional statements
Saad Sheikh
 
PPT
Control structures ii
Ahmad Idrees
 
PPTX
Decision statements in c language
tanmaymodi4
 
PPTX
C decision making and looping.
Haard Shah
 
Maxbox starter
Max Kleiner
 
Learn C# Programming - Decision Making & Loops
Eng Teong Cheah
 
Lecture13 control statementswitch.ppt
eShikshak
 
Control Structures
Ghaffar Khan
 
Introduction To Programming with Python Lecture 2
Syed Farjad Zia Zaidi
 
Bt0067 c programming and data structures 1
Techglyphs
 
Types of Statements in Python Programming Language
Explore Skilled
 
Conditions In C# C-Sharp
Abid Kohistani
 
Declaration of variables
Maria Stella Solon
 
Ch4 Expressions
SzeChingChen
 
Control Structures: Part 1
Andy Juan Sarango Veliz
 
Control structures i
Ahmad Idrees
 
C interview questions
Kuntal Bhowmick
 
C language 2
Arafat Bin Reza
 
Fortran 90 Basics
Tariqul Dipu
 
The Three Basic Selection Structures in C++ Programming Concepts
Tech
 
Loops and conditional statements
Saad Sheikh
 
Control structures ii
Ahmad Idrees
 
Decision statements in c language
tanmaymodi4
 
C decision making and looping.
Haard Shah
 

Viewers also liked (15)

PDF
Learning the C Language
nTier Custom Solutions
 
PPTX
Memory management of datatypes
Monika Sanghani
 
PDF
Mechanics of materials
Self-employed
 
PDF
differential equations Boyce & Diprima Solution manual
shayangreen
 
PDF
Higher order differential equations
Mateus Nieves Enrique - DIE-UD
 
PPTX
Storage classes in C
Nitesh Bichwani
 
PPT
CO By Rakesh Roshan
Anurag University Hyderabad
 
PDF
Unit 2 stresses in composite sections
Hareesha N Gowda, Dayananda Sagar College of Engg, Bangalore
 
PPT
2 axial loading- Mechanics of Materials - 4th - Beer
Nhan Tran
 
PPT
3 torsion- Mechanics of Materials - 4th - Beer
Nhan Tran
 
PPT
Higher Differential Equation
gtuautonomous
 
PPT
02 first order differential equations
vansi007
 
PDF
Mechanics of materials lecture 01, Engr. Abdullah Khan
Abdullah Khan
 
PDF
Higher Differential Equation
Abdul Hannan
 
Learning the C Language
nTier Custom Solutions
 
Memory management of datatypes
Monika Sanghani
 
Mechanics of materials
Self-employed
 
differential equations Boyce & Diprima Solution manual
shayangreen
 
Higher order differential equations
Mateus Nieves Enrique - DIE-UD
 
Storage classes in C
Nitesh Bichwani
 
CO By Rakesh Roshan
Anurag University Hyderabad
 
2 axial loading- Mechanics of Materials - 4th - Beer
Nhan Tran
 
3 torsion- Mechanics of Materials - 4th - Beer
Nhan Tran
 
Higher Differential Equation
gtuautonomous
 
02 first order differential equations
vansi007
 
Mechanics of materials lecture 01, Engr. Abdullah Khan
Abdullah Khan
 
Higher Differential Equation
Abdul Hannan
 
Ad

Similar to C language UPTU Unit3 Slides (20)

DOCX
PPS 3.3CONDITIONAL BRANCHING AND LOOPS WRITING AND EVALUATION OF CONDITIONAL...
Sitamarhi Institute of Technology
 
PDF
Control statements-Computer programming
nmahi96
 
PDF
Principals of Programming in CModule -5.pdfModule_2_P2 (1).pdf
anilcsbs
 
PPT
Decision making in C(2020-2021) statements
BalaKrishnan466
 
PPTX
Control Structures in C
sana shaikh
 
PPT
Control All
phanleson
 
PPTX
control_structures_c_language_regarding how to represent the loop in language...
ShirishaBuduputi
 
PPTX
chapter 3enejngewngjnjnfjndnennwnnefwf.pptx
TriggeredZulkar
 
PPTX
6 Control Structures-1.pptxAAAAAAAAAAAAAAAAAAAAA
EG20910848921ISAACDU
 
PDF
Controls & Loops in C
Thesis Scientist Private Limited
 
PPTX
C Programming Unit-2
Vikram Nandini
 
PPTX
Decision statements in c laguage
Tanmay Modi
 
PPTX
Dti2143 chap 4 control structures aka_selection
alish sha
 
PPTX
Dti2143 chap 4 control structures aka_selection
alish sha
 
PPTX
Fundamentals of prog. by rubferd medina
rurumedina
 
PDF
Fundamental of Information Technology - UNIT 8
Shipra Swati
 
PDF
C programming session3
Keroles karam khalil
 
PDF
C programming session3
Keroles karam khalil
 
PDF
Lesson 2 C STATEMENT IN PROGRAMMING (M).pdf
WeejMaderazo
 
PPT
C statements.ppt presentation in c language
chintupro9
 
PPS 3.3CONDITIONAL BRANCHING AND LOOPS WRITING AND EVALUATION OF CONDITIONAL...
Sitamarhi Institute of Technology
 
Control statements-Computer programming
nmahi96
 
Principals of Programming in CModule -5.pdfModule_2_P2 (1).pdf
anilcsbs
 
Decision making in C(2020-2021) statements
BalaKrishnan466
 
Control Structures in C
sana shaikh
 
Control All
phanleson
 
control_structures_c_language_regarding how to represent the loop in language...
ShirishaBuduputi
 
chapter 3enejngewngjnjnfjndnennwnnefwf.pptx
TriggeredZulkar
 
6 Control Structures-1.pptxAAAAAAAAAAAAAAAAAAAAA
EG20910848921ISAACDU
 
Controls & Loops in C
Thesis Scientist Private Limited
 
C Programming Unit-2
Vikram Nandini
 
Decision statements in c laguage
Tanmay Modi
 
Dti2143 chap 4 control structures aka_selection
alish sha
 
Dti2143 chap 4 control structures aka_selection
alish sha
 
Fundamentals of prog. by rubferd medina
rurumedina
 
Fundamental of Information Technology - UNIT 8
Shipra Swati
 
C programming session3
Keroles karam khalil
 
C programming session3
Keroles karam khalil
 
Lesson 2 C STATEMENT IN PROGRAMMING (M).pdf
WeejMaderazo
 
C statements.ppt presentation in c language
chintupro9
 
Ad

Recently uploaded (20)

PDF
Isharyanti-2025-Cross Language Communication in Indonesian Language
Neny Isharyanti
 
PPTX
Neurodivergent Friendly Schools - Slides from training session
Pooky Knightsmith
 
PDF
The-Ever-Evolving-World-of-Science (1).pdf/7TH CLASS CURIOSITY /1ST CHAPTER/B...
Sandeep Swamy
 
PDF
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
PDF
LAW OF CONTRACT (5 YEAR LLB & UNITARY LLB )- MODULE - 1.& 2 - LEARN THROUGH P...
APARNA T SHAIL KUMAR
 
PDF
Dimensions of Societal Planning in Commonism
StefanMz
 
PPTX
SPINA BIFIDA: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
PDF
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
PPTX
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
PDF
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
PDF
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PPTX
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
PPT
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
PPTX
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
PDF
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
PDF
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
PPTX
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
PDF
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
PDF
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
PDF
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
Isharyanti-2025-Cross Language Communication in Indonesian Language
Neny Isharyanti
 
Neurodivergent Friendly Schools - Slides from training session
Pooky Knightsmith
 
The-Ever-Evolving-World-of-Science (1).pdf/7TH CLASS CURIOSITY /1ST CHAPTER/B...
Sandeep Swamy
 
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
LAW OF CONTRACT (5 YEAR LLB & UNITARY LLB )- MODULE - 1.& 2 - LEARN THROUGH P...
APARNA T SHAIL KUMAR
 
Dimensions of Societal Planning in Commonism
StefanMz
 
SPINA BIFIDA: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 

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 \n&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\n&quot;);     scanf (&quot;%d&quot;, &marks);       if (marks <= 100 && marks >= 70)           printf (&quot;\n Distinction&quot;) ;     else if (marks >= 60)           printf(&quot;\n First class&quot;);     else if (marks >= 50)           printf (&quot;\n second class&quot;);     else if (marks >= 35)           printf (&quot;\n 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 \n&quot;);               result = 0;           }           break;         default:           printf (&quot;\n 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;\n 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(“\t%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;\nEnter the limit:&quot;); scanf(&quot;%d&quot;,&n); do { printf(&quot;\n%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\n”); 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\n”,sum); printf(“Sum of their squares=%d\n”,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(“\n Sample subprogram output”); } statement2() { printf(“\n Sample subprogram output two”); } starline() { int a; for (a=1;a<60;a++) printf(“*”); printf(“\n”); }
  • 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. Functions with arguments and return values: The function of the type Arguments with return values will send arguments from the calling function to the called function and expects the result to be returned back from the called function back to the calling function. A C function returns a value of type int as the default data type when no other type is specified explicitly. For example if function does all the calculations by using float values and if the return statement such as return (sum); returns only the integer part of the sum. This is since we have not specified any return type for the sum. There is the necessity in some cases it is important to receive float or character or double data type. To enable a calling function to receive a non-integer value from a called function we can do the two things:   The explicit type specifier corresponding to the data type required must be mentioned in the function header. The general form of the function definition is Type_specifier function_name(argument list) Argument declaration; { function statement; }   The type specifier tells the compiler , the type of data the function is to return.
  • 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\n&quot;,add(x,y)); printf(&quot;%lf\n&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\n&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\n”,m); } function1() { int m=10; printf(“%d\n”,m); } function2() { int m=100; function1(); printf(“%d\n”,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\n”,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;