TechWeb is an award winning blog that talks about living a boss free life with blogging. We cover about WordPress, SEO, Make money Blogging, Affiliate marketing, Topic Tutorials , C/C++, Java , Python.
A scope in any programming is a region of the program
where a defined variable can have its existence and beyond that variable it cannot be accessed.
There are three places where variables can be declared in C programming language: Inside a function or a block which is called local variables, Outside of all functions which is called global variables. In the definition of function parameters which are called formal parameters. Let us understand what are local and global variables,and formal parameters . Local Variables Variables that are declared inside a function or block are called local variables. They can be used only by statements that are inside that function or block of code. Local variables are not known to functions outside their own. The following example shows how local variables are used. Here all the variables a, b,and c are local to main() function. include /* global variable declaration / int g; int main () { / local variable declaration / int a, b; / actual initialization */
a = 10;
b = 20;
g = a + b;
printf ("value of a = %d, b = %d and g = %d\n", a, b, g);
return 0;
} A program can have same name for local and global variables but the value of local variable inside a function will take preference. Here is an example: include /* global variable declaration */
int g = 20; int main () { /* local variable declaration */ int g = 10; printf ("value of g = %d\n", g); return 0; }
When the above code is compiled and executed, it produces the following result:
value of g = 10
Formal Parameters
Formal parameters are treated as local variables with-in a function and they take precedence over global variables. Following is an example: include /* global variable declaration / int a = 20; int main () { / local variable declaration in main function */ int a = 10;
int b = 20;
int c = 0;
printf ("value of a in main() = %d\n", a);
c = sum( a, b);
printf ("value of c in main() = %d\n", c);
return 0; } /* function to add two integers */
int sum(int a, int b)
{
printf ("value of a in sum() = %d\n", a);
printf ("value of b in sum() = %d\n", b);
return a + b;
}
When the above code is compiled and executed, it produces the following result:
value of a in main() = 10 value of a in sum() = 10 value of b in sum() = 20 value of c in main() = 30 Initializing Local and Global Variables
When a local variable is defined, it is not initialized by the system, you must initialize it yourself. Global variables are initialized automatically by the system
when you define them, as follows: Data Type Initial Default Value int 0 char '\0' float 0 double 0 pointer NULL It is a good programming practice to initialize variables properly, otherwise your
program may produce unexpected results, because uninitialized variables will
take some garbage value already available at their memory location.
Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. Instead of declaring individual variables, such as number0, number1, …, and
number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and …, numbers[99] to represent individual variables.
A specific element in an array is accessed by an index. All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element. Declaring Arrays
To declare an array in C, a programmer specifies the type of the elements and
the number of elements required by an array as follows: type arrayName [ arraySize ];
This is called a single-dimensional array. The arraySize must be an integer constant greater than zero and type can be any valid C data type. For example, to declare a 10-element array called balance of type double, use this statement:
double balance[10];
Here, balance is a variable array which is sufficient to hold up to 10 double numbers.
Initializing Arrays You can initialize an array in C either one by one or using a single statement as follows:
double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0}; The number of values between braces { } cannot be larger than the number of elements that we declare for the array between square brackets [ ].
If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write:
double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};
You will create exactly the same array as you did in the previous example. Following is an example to assign a single element of the array:
balance[4] = 50.0;
The above statement assigns the 5th element in the array with a value of 50.0.
All arrays have 0 as the index of their first element which is also called the base
index and the last index of an array will be total size of the array minus 1. Shown below is the pictorial representation of the array we discussed above:
Accessing Array Elements
An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example:
double salary = balance[9];
The above statement will take the 10th element from the array and assign the
value to salary variable. The following example shows how to use all the three
above-mentioned concepts viz. declaration, assignment, and accessing arrays: include int main () { int n[ 10 ]; /* n is an array of 10 integers / int i,j; / initialize elements of array n to 0 / for ( i = 0; i < 10; i++ ) { n[ i ] = i + 100; / set element at location i t } /* output each array element's value */ for (j = 0; j < 10; j++ ) { printf("Element[%d] = %d\n", j, n[j] ); } return 0; }
When the above code is compiled and executed, it produces the following result:
Arrays are important to C and should need a lot more attention. The following
important concepts related to array should be clear to a C programmer: Concept Description
Multidimensional arrays C supports multidimensional arrays. The simplest form of the multidimensional array is the two-dimensional array. Passing arrays to functions You can pass to the function a pointer to an array by specifying the array's name without an index. Return array from a function C allows a function to return an array. Pointer to an array You can generate a pointer to the first element of an array by simply specifying the array name, without any index Multidimensional Arrays
C programming language allows multidimensional arrays. Here is the general form of a multidimensional array declaration:
type name[size1][size2]…[sizeN];
For example, the following declaration creates a three-dimensional integer array:
int threedim [5][10][4];
Two-dimensional Arrays
The simplest form of multidimensional array is the two-dimensional array. A two-dimensional array is, in essence, a list of one-dimensional arrays. To declare
a two-dimensional integer array of size [x][y], you would write something as follows:
type arrayName [ x ][ y ];
Where type can be any valid C data type and arrayName will be a valid C identifier. A two-dimensional array can be considered as a table which will have x number of rows and y number of columns. A two-dimensional array a, which contains three rows and four columns can be shown as follows:
Thus, every element in the array a is identified by an element name of the form a[ i ][ j ], where ‘a’ is the name of the array, and ‘i' and ‘j’ are the subscripts that uniquely identify each element in ‘a’. Initializing Two-Dimensional Arrays Multidimensional arrays may be initialized by specifying bracketed values for each row. Following is an array with 3 rows and each row has 4 columns. int a[3][4] = { {0, 1, 2, 3} , /* initializers for row indexed by 0 / {4, 5, 6, 7} , / initializers for row indexed by 1 / {8, 9, 10, 11} / initializers for row indexed by 2 */ }; The nested braces, which indicate the intended row, are optional. The following initialization is equivalent to the previous example: int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11}; Accessing Two-Dimensional Array Elements An element in a two-dimensional array is accessed by using the subscripts, i.e., row index and column index of the array. For example: int val = a[2][3]; The above statement will take the 4th element from the 3rd row of the array. You can verify it in the above figure. Let us check the following program where we have used a nested loop to handle a two-dimensional array: include int main () {
/* an array with 5 rows and 2 columns / int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}}; int i, j; / output each array element's value */ for ( i = 0; i < 5; i++ ) { for ( j = 0; j < 2; j++ ) { printf("a[%d][%d] = %d\n", i,j, a[i][j] ); } } return 0; }
When the above code is compiled and executed, it produces the following result:
As explained above, you can have arrays with any number of dimensions, although it is likely that most of the arrays you create will be of one or two dimensions.
Passing Arrays to Functions
If you want to pass a single-dimension array as an argument in a function, you would have to declare a formal parameter in one of following three ways and all
three declaration methods produce similar results because each tells the compiler that an integer pointer is going to be received. Similarly, you can pass multi-dimensional arrays as formal parameters.
Way-1 Formal parameters as a pointer:
void myFunction(int *param) { . . . } Way-2
Formal parameters as a sized array:
void myFunction(int param[10]) { . . . }
Way-3
Formal parameters as an unsized array:
void myFunction(int param[]) { . . . }
Example
Now, consider the following function, which takes an array as an argument along
with another argument and based on the passed arguments, it returns the average of the numbers passed through the array as follows:
double get Average(int arr[], int size) { int i; double avg; double sum; for (i = 0; i < size; ++i) { sum += arr[i]; } avg = sum / size; return avg; } Now, let us call the above function as follows: include /* function declaration / double getAverage(int arr[], int size); int main () { / an int array with 5 elements / int balance[5] = {1000, 2, 3, 17, 50}; double avg; / pass pointer to the array as an argument / avg = getAverage( balance, 5 ) ; / output the returned value */ printf( "Average value is: %f ", avg ); return 0; }
When the above code is compiled together and executed, it produces the following result:
Average value is: 214.400000
As you can see, the length of the array doesn't matter as far as the function is concerned because C performs no bounds checking for formal parameters.
Return Array from a Function
C programming does not allow to return an entire array as an argument to a function. However, you can return a pointer to an array by specifying the array's name without an index. If you want to return a single-dimension array from a function, you would have to declare a function returning a pointer as in the following example: int * myFunction() { . . . } Second point to remember is that C does not advocate to return the address of a local variable to outside of the function, so you would have to define the local variable as static variable. Now, consider the following function which will generate 10 random numbers and return them using an array and call this function as follows: include /* function to generate and return random numbers */ int * getRandom( ) { static int r[10]; int i; /* set the seed / srand( (unsigned)time( NULL ) ); for ( i = 0; i < 10; ++i) { r[i] = rand(); printf( "r[%d] = %d\n", i, r[i]); } return r; } / main function to call above defined function */ int main () { /* a pointer to an int */ int *p; int i; p = getRandom(); for ( i = 0; i < 10; i++ ) { printf( "*(p + %d) : %d\n", i, *(p + i)); } return 0; }
When the above code is compiled together and executed, it produces the following result:
It is most likely that you would not understand this section until you are through with the chapter ‘Pointers’.
Assuming you have some understanding of pointers in C, let us start: An array name is a constant pointer to the first element of the array. Therefore, in the declaration:
double balance[50];
balance is a pointer to &balance[0], which is the address of the first element of the array balance. Thus, the following program fragment assigns p as the address of the first element of balance: double *p; double balance[10]; p = balance; It is legal to use array names as constant pointers, and vice versa. Therefore, *(balance + 4) is a legitimate way of accessing the data at balance[4].
Once you store the address of the first element in ‘p’, you can access the array elements using *p, *(p+1), *(p+2), and so on. Given below is the example to show all the concepts discussed above: include int main () { /* an array with 5 elements */ double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0}; double *p; int i; p = balance; /* output each array element's value */ printf( "Array values using pointer\n"); for ( i = 0; i < 5; i++ ) { printf("*(p + %d) : %f\n", i, *(p + i) ); } printf( "Array values using balance as address\n"); for ( i = 0; i < 5; i++ ) { printf("*(balance + %d) : %f\n", i, *(balance + i) ); } return 0; }
When the above code is compiled and executed, it produces the following result:
In the above example, p is a pointer to double, which means it can store the address of a variable of double type. Once we have the address in p, *p will give us the value available at the address stored in p, as we have shown in the above
A storage class defines the scope (visibility) and life-time of variables and/or functions within a C Program. They precede the type that they modify. We have four different storage classes in a C program:
auto
register
static
extern
The auto Storage Class
The auto storage class is the default storage class for all local variables
{
int mount;
auto int month;
}
The example above defines two variables within the same storage class. ‘auto’ can only be used within functions, i.e., local variables.
The register storage class is used to define local variables that should be stored in a register instead of RAM. This means that the variable has a maximum size equal to the register size (usually one word) and can't have the unary '&' operator applied to it (as it does not have a memory location).
{
register int miles;
}
The register should only be used for variables that require quick access such as counters. It should also be noted that defining 'register' does not mean that the variable will be stored in a register. It means that it MIGHT be stored in a register depending on hardware and implementation restrictions.
The static Storage Class
The static storage class instructs the compiler to keep a local variable in existence during the life-time of the program instead of creating and destroying it each time it comes into and goes out of scope. Therefore, making local variables static allows them to maintain their values between function calls.
The static modifier may also be applied to global variables. When this is done, it causes that variable's scope to be restricted to the file in which it is declared.
In C programming, when static is used on a class data member, it causes only one copy of that member to be shared by all the objects of its class.
#include <stdio.h>
/* function declaration */
void func(void);
static int count = 5; /* global variable */
main()
{
while(count--)
{
func();
}
return 0;
}
/* function definition */
void func( void )
{
static int i = 5; /* local static variable */
i++;
printf("i is %d and count is %d\n", i, count);
}
When the above code is compiled and executed, it produces the following result:
i is 6 and count is 4
i is 7 and count is 3
i is 8 and count is 2
i is 9 and count is 1
i is 10 and count is 0
The extern Storage Class
The extern storage class is used to give a reference of a global variable that is visible to ALL the program files. When you use 'extern', the variable cannot be initialized, however, it points the variable name at a storage location that has been previously defined.
When you have multiple files and you define a global variable or function, which will also be used in other files, then extern will be used in another file to provide the reference of defined variable or function. Just for understanding, extern is used to declare a global variable or function in another file.
The extern modifier is most commonly used when there are two or more files sharing the same global variables or functions as explained below.
First File: main.c
#include <stdio.h>
int count;
extern void write_extern();
main()
{
count = 5;
write_extern();
}
Second File: support.c
#include <stdio.h>
extern int count;
void write_extern(void)
{
printf("count is %d\n", count);
}
Here, extern is being used to declare count in the second file, whereas it has its definition in the first file, main.c. Now, compile these two files as follows:
$gcc main.c support.c
The executable program a.out. When this program is executed, it produces the following result:
Decision-making structures require that the programmer specifies one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.
Shown below is the general form of a typical decision-making structure found in most of the programming languages:
C programming language assumes any non-zero and non-nullvalues as true, and if it is either zero or null, then it is assumed as false value.
C programming language provides the following types of decision-making statements.
Decision Making in C
if Statement in C
An ifstatement consists of a Booleanexpression followed by one or more statements.
Syntax
The syntax of an if statement in C programming language is:
if(boolean_expression)
{
/* statement(s) will execute if the boolean expression is true */
}
If the Boolean expression evaluates to true, then the block of code inside the if statement will be executed. If the Boolean expression evaluates to false, then the first set of code after the end of the if statement (after the closing curly brace) will be executed.
C programming language assumes any non-zero and non-null values as true and if it is either zero or null, then it is assumed as false value.
Flow Diagram
if statement
Example of if statement
#include
int main ()
{
/* local variable definition */
int a = 10;
/* check the boolean condition using if statement */
if( a < 20 )
{
/* if condition is true then print the following */
printf("a is less than 20\n" );
}
printf("value of a is : %d\n", a);
return 0;
}
When the above code is compiled and executed, it produces the following result:
a is less than 20; value of a is : 10
if else Statement
An if statement can be followed by an optional else statement, which executes when the Boolean expression is false.
Syntax
The syntax of an if else statement in C programming language is:
if(boolean_expression) { /* statement(s) will execute if the boolean expression is true */ } else { /* statement(s) will execute if the boolean expression is false */ } If the Boolean expression evaluates to true, then the if block will be executed, otherwise, the else block will be executed.
C programming language assumes any non-zero and non-null values as true, and if it is either zero or null, then it is assumed as false value.
Flow Diagram
if else statement
Example of if else statement #include <stdio.h> int main () { /* local variable definition */ int a = 100; /* check the boolean condition */ if( a < 20 ) { /* if condition is true then print the following */ printf("a is less than 20\n" ); } else { /* if condition is false then print the following */ printf("a is not less than 20\n" ); } printf("value of a is : %d\n", a); return 0; } When the above code is compiled and executed, it produces the following result:
a is not less than 20; value of a is : 100 if else if else Statement An if statement can be followed by an optional else if else statement, which is very useful to test various conditions using single if else if statement. When using if else if else statements, there are few points to keep in mind:
An if can have zero or one else's and it must come after any else if's. An if can have zero to many else if's and they must come before the else. Once an else if succeeds, none of the remaining else if's or else's will be tested.
Syntax
The syntax of an if else if else statement in C programming language is: if(boolean_expression 1) { /* Executes when the boolean expression 1 is true */ } else if( boolean_expression 2) { /* Executes when the boolean expression 2 is true */ } else if( boolean_expression 3) { /* Executes when the boolean expression 3 is true */ } else { /* executes when the none of the above condition is true */ } Example
#include <stdio.h> int main () { /* local variable definition */ int a = 100; /* check the boolean condition */ if( a == 10 ) { /* if condition is true then print the following */ printf("Value of a is 10\n" ); } else if( a == 20 ) { /* if else if condition is true */ printf("Value of a is 20\n" ); } else if( a == 30 ) { /* if else if condition is true */ printf("Value of a is 30\n" ); } else { /* if none of the conditions is true */ printf("None of the values is matching\n" ); } printf("Exact value of a is: %d\n", a ); return 0; }
When the above code is compiled and executed, it produces the following result:
None of the values is matching Exact value of a is: 100
Nested if Statements It is always legal in C programming to nest if-else statements, which means you can use one if or else if statement inside another if or else if statement(s). Syntax The syntax for a nested if statement is as follows:
if( boolean_expression 1) { /* Executes when the boolean expression 1 is true */ if(boolean_expression 2) { /* Executes when the boolean expression 2 is true */ } } can nest else if else in the similar way as you have nested if statements. Example
#include <stdio.h> int main () { /* local variable definition */ int a = 100; int b = 200; /* check the boolean condition */ if( a == 100 ) { /* if condition is true then check the following */ if( b == 200 ) { /* if condition is true then print the following */ printf("Value of a is 100 and b is 200\n" ); } } printf("Exact value of a is : %d\n", a ); printf("Exact value of b is : %d\n", b ); return 0; }
When the above code is compiled and executed, it produces the following result:
Value of a is 100 and b is 200 Exact value of a is : 100 Exact value of b is : 200 switch Statement A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case. Syntax The syntax for a switch statement in C programming language is as follows: switch(expression){ case constant-expression : statement(s); break; /* optional */ case constant-expression : statement(s); break; /* optional */ /* you can have any number of case statements */ default : /* Optional */ statement(s); } The following rules apply to a switch statement: The expression used in a switch statement must have an integral or enumerated type, or be of a class type in which the class has a single conversion function to an integral or enumerated type.
You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.
The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal.
When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.
When a break statement is reached, the switch terminates, and the flow
of control jumps to the next line following the switch statement.
Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached.
A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.
Flow Diagram
switch statement
Example
#include <stdio.h> int main () { /* local variable definition */ char grade = 'B'; switch(grade) { case 'A' : printf("Excellent!\n" ); break; case 'B' : case 'C' : printf("Well done\n" ); break; case 'D' : printf("You passed\n" ); break; case 'F' : printf("Better try again\n" ); break; default : printf("Invalid grade\n" ); } printf("Your grade is %c\n", grade ); return 0; } When the above code is compiled and executed, it produces the following result: Well done Your grade is B Nested switch Statements It is possible to have a switch as a part of the statement sequence of an outer switch. Even if the case constants of the inner and outer switch contain common values, no conflicts will arise. Syntax
The syntax for a nested switch statement is as follows:
switch(ch1) { case 'A':
printf("This A is part of outer switch" ); switch(ch2) { case 'A': printf("This A is part of inner switch" ); break; case 'B': /* case code */ } break; case 'B': /* case code */ } Example #include <stdio.h> int main () { /* local variable definition */ int a = 100; int b = 200; switch(a) { case 100: printf("This is part of outer switch\n", a ); switch(b) { case 200: printf("This is part of inner switch\n", a ); } } printf("Exact value of a is : %d\n", a ); printf("Exact value of b is : %d\n", b ); return 0; }
When the above code is compiled and executed, it produces the following result: This is part of outer switch This is part of inner switch Exact value of a is : 100 Exact value of b is : 200 The ? : Operator: We have covered conditional operator ? : in the previous chapter which can be used to replace if else statements. It has the following general form: Exp1 ? Exp2 : Exp3; Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon. The value of a ? expression is determined like this:
1. Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire ? expression.
2. If Exp1 is false, then Exp3 is evaluated and its value becomes the value of
You may encounter situations when a block of code needs to be executed several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.
C Programming languages provide various control structures that allow for more complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times. Given below is the general form of a loop statement in most of the c programming languages:
LOOPS
C programming language provides the following types of loops to handle looping
requirements.
LoopType Description
while loop Repeats a statement or group of statements while a
given condition is true. It tests the condition before
executing the loop body.
for loop Executes a sequence of statements multiple times and
abbreviates the code that manages the loop variable.
do...while loop It is more like a while statement, except that it tests the condition at the end of the loop body. nested loops You can use one or more loops inside any other while, for, or do..while loop.
while Loop
A while loop in C programming repeatedly executes a target statement as long as a given condition is true. Syntax
The syntax of a while loop in C programming language is:
while(condition) { statement(s); } Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any nonzero value. The loop iterates while the condition is true.
When the condition becomes false, the program control passes to the line immediately following the loop.
Flow Diagram
While Loop
Here, the key point to note is that a while loop might not execute at all. When the condition is tested and the result is false, the loop body will be skipped and
the first statement after the while loop will be executed. Example #include <stdio.h> int main () { /* local variable definition */ int a = 10; /* while loop execution */ while( a < 20 ) { printf("value of a: %d\n", a); a++; } return 0; } When the above code is compiled and executed, it produces the following result: value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15 value of a: 16 value of a: 17 value of a: 18 value of a: 19
for Loop
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.
Syntax
The syntax of a for loop in C programming language is:
for ( init; condition; increment ) { statement(s); } Here is the flow of control in a ‘for’ loop:
1. The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
2. Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and the flow of control jumps to the next statement just after the for loop.
3. After the body of the for loopexecutes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition.
4. The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the for loop terminates. Flow Diagram
for Loop
Example #include <stdio.h> int main () { /* for loop execution */ for( int a = 10; a < 20; a = a + 1 ) { printf("value of a: %d\n", a); } return 0; } When the above code is compiled and executed, it produces the following result: value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15 value of a: 16 value of a: 17 value of a: 18 value of a: 19 do…while Loop Unlike for and while loops, which test the loop condition at the top of the loop, the do while loop in Cprogramming checks its condition at the bottom of the loop. A do while loop is similar to a while loop, except the fact that it is guaranteed to execute at least one time.
Syntax The syntax of a do...while loop in C programming language is: do { statement(s); }while( condition );
Notice that the conditional expression appears at the end of the loop, so the
statement(s) in the loop executes once before the condition is tested. If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop executes again. This process repeats until the given condition becomes false. Flow Diagram
do while loop
Example #include <stdio.h> int main () { /* local variable definition */ int a = 10; /* do loop execution */ do { printf("value of a: %d\n", a); a = a + 1; }while( a < 20 ); return 0; } When the above code is compiled and executed, it produces the following result: value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15 value of a: 16 value of a: 17 value of a: 18 value of a: 19 Nested Loops
C programming allows to use one loop inside another loop. The following section shows a few examples to illustrate the concept. Syntax The syntax for a nested for loop statement in C is as follows: for ( init; condition; increment ) { for ( init; condition; increment ) { statement(s); } statement(s); } The syntax for a nested while loop statement in C programming language is as follows: while(condition) { while(condition) { statement(s); } statement(s); } The syntax for a nested do...while loop statement in C programming language is as follows: do { statement(s); do { statement(s); }while( condition ); }while( condition );
A final note on loop nesting is that you can put any type of loop inside any other type of loop. For example, a ‘for’ loop can be inside a ‘while’ loop or vice versa. Example
The following program uses a nested for loop to find the prime numbers from 2 to 100: #include <stdio.h> int main () { /* local variable definition */ int i, j; for(i=2; i<100; i++) { for(j=2; j <= (i/j); j++) if(!(i%j)) break; // if factor found, not prime if(j > (i/j)) printf("%d is prime\n", i); } return 0; }
When the above code is compiled and executed, it produces the following result: 2 is prime 3 is prime 5 is prime 7 is prime 11 is prime 13 is prime 17 is prime 19 is prime 23 is prime 29 is prime 31 is prime 37 is prime 41 is prime 43 is prime 47 is prime 53 is prime 59 is prime 61 is prime 67 is prime 71 is prime 73 is prime 79 is prime 83 is prime 89 is prime 97 is prime Loop Control Statements Loop controlstatements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.
C supports the following control statements.
Control Statement Description
break statement Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch. continue statement Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. goto statement Transfers control to the labeled statement. break Statement The break statement in C programming has the following two usages:
When a break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop.
It can be used to terminate a case in the switch statement (covered in the next chapter). If you are using nested loops, the break statement will stop the execution of the innermost loop and start executing the next line of code after the block. Syntax The syntax for a break statement in C is as follows: break;
Flow Diagram
nested loop
Example #include <stdio.h> int main () { /* local variable definition */ int a = 10; /* while loop execution */ while( a < 20 ) { printf("value of a: %d\n", a); a++; if( a > 15) { /* terminate the loop using break statement */ break; } } return 0; } When the above code is compiled and executed, it produces the following result: value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15 continue Statement The continue statement in C programming works somewhat like the break statement. Instead of forcing termination, it forces the next iteration of the loop to take place, skipping any code in between. For the for loop,continue statement causes the conditional test and increment portions of the loop to execute. For the while and do while loops, continue statement causes the program control to pass to the conditional tests. Syntax The syntax for a continue statement in C is as follows: continue; Flow Diagram
Continue Statement
Example #include <stdio.h> int main () { /* local variable definition */ int a = 10; /* do loop execution */ do { if( a == 15) { /* skip the iteration */ a = a + 1; continue; } printf("value of a: %d\n", a); a++; }while( a < 20 ); return 0; } When the above code is compiled and executed, it produces the following result: value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 16 value of a: 17 value of a: 18 value of a: 19 goto Statement A goto statement in C programming provides an unconditional jump from the ‘goto’ to a labeled statement in the same function. NOTE: Use of goto statement is highly discouraged in any programming language because it makes difficult to trace the control flow of a program, making the program hard to understand and hard to modify. Any program that uses a goto can be rewritten to avoid them.
Syntax The syntax for a goto statement in C is as follows: goto label; .. . label: statement; Here label can be any plain text except C keyword and it can be set anywhere in the C program above or below to goto statement.
Flow Diagram
goto Statement
Example
#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 10;
/* do loop execution */
LOOP:do
{
if( a == 15)
{
/* skip the iteration */
a = a + 1;
goto LOOP;
}
printf("value of a: %d\n", a);
a++;
}while( a < 20 );
return 0;
}
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
The Infinite Loop
A loop becomes an infinite loop if a condition never becomes false. The for loop
is traditionally used for this purpose. Since none of the three expressions that
form the ‘for’ loop are required, you can make an endless loop by leaving the
conditional expression empty.
#include <stdio.h>
int main ()
{
for( ; ; )
{
printf("This loop will run forever.\n");
}
return 0;
}
When the conditional expression is absent, it is assumed to be true. You may
have an initialization and incrementexpression, but C programmers more
commonly use the for(;;) construct to signify an infinite loop.
NOTE: You can terminate an infinite loop by pressing Ctrl + C keys.