by Dinesh Thakur Category: Function and Pointer

A goto statement implements a local jump of program execution, and the longjmp() and setjmp() functions implement a nonlocal, or far, jump of program execution. Generally, a jump in execution of any kind should be avoided because it is not considered good programming practice to use such statements as goto and longjmp in your program.

 A goto statement simply bypasses code in your program and jumps to a predefined position. To use the gotostatement, you give it a labeled position to jump to. This predefined position must be within the same function. You cannot implement gotos between functions. Here is an example of a goto statement:

 

 

void bad_programmers_function(void)

{

int x;

printf(“Excuse me while I count to 5000...\n”);

x = 1;

while (1)

{

printf(“%d\n”, x);

if (x == 5000)

goto all_done;

else

x = x + 1;

}

all_done:

printf(“Whew! That wasn’t so bad, was it?\n”);

}

This example could have been written much better, avoiding the use of a goto statement. Here is an example

of an improved implementation:

void better_function(void)

{

int x;

printf(“Excuse me while I count to 5000...\n”);

for (x=1; x<=5000; x++)

printf(“%d\n”, x);

printf(“Whew! That wasn’t so bad, was it?\n”);

}

As previously mentioned, the longjmp() and setjmp() functions implement a nonlocal goto. When your program calls setjmp(), the current state of your program is saved in a structure of type jmp_buf. Later, your program can call the longjmp() function to restore the program’s state as it was when you called setjmp(). Unlike the goto statement, the longjmp() and setjmp() functions do not need to be implemented in the same function. However, there is a major drawback to using these functions: your program, when restored to its previously saved state, will lose its references to any dynamically allocated memory between the longjmp() and the setjmp(). This means you will waste memory for every malloc() or calloc() you have implemented between your longjmp() and setjmp(), and your program will be horribly inefficient. It is highly recommended that you avoid using functions such as longjmp() and setjmp() because they, like the goto statement, are quite often an indication of poor programming practice.

 

Here is an example of the longjmp() and setjmp() functions:

 

#include <stdio.h>

#include <setjmp.h>

jmp_buf saved_state;

void main(void);

void call_longjmp(void);

void main(void)

{

int ret_code;

printf(“The current state of the program is being saved...\n”);

ret_code = setjmp(saved_state);

if (ret_code == 1)

{

printf(“The longjmp function has been called.\n”);

printf(“The program’s previous state has been restored.\n”);

exit(0);

}

 

printf(“I am about to call longjmp and\n”);

printf(“return to the previous program state...\n”);

call_longjmp();

}

void call_longjmp(void)

{

longjmp(saved_state, 1);

}

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 desirable.

Syntax

a > b >
goto label; label;
………….. ………….
…………. ………….
…………. ………….
Label; goto label;
Statement;

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.



/ * // program to find the sum
/*A program to find the sum of n natural numbers using goto statement */
#include < stdio.h > //include stdio.h header file to your program
main ( ) //start of main
{
int n, sum = 0, I = 0, // variable declaration
printf (“Enter a number”); // message to the user
scanf (“t.d”, &n); //Read and store the number
Loop: I ++; //Label of goto statement
Sum + = I; //the sum value in stored and I is added to sum
If (i < n) goto Loop; //If value of I is less than n pass control to loop
Printf (“\n sum of y.d natural numbers = y.d”, n, sum);
//print the sum of the numbers & value of n
}

Decision Making - Looping

In this tutorial you will learn about C Programming - Decision Making - Looping, The While Statement, The Do while statement, The Break Statement, Continue statement and For Loop.

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

Example program for generating ‘N’ Natural numbers using while loop:

 

# include < stdio.h > //include the stdio.h file
void main() // Start of your program
{
int n, i=0; //Declare and initialize the variables
printf(“Enter the upper limit number”); //Message to the user
scanf(“%d”, &n); //read and store the number
while(I < = n) // While statement with condition
{ // Body of the loop
printf(“\t%d”,I); // print the value of i
I++; increment I to the next natural number.
}
}

In the above program the looping concept is used to generate n natural numbers. Here n and I are declared as integer variables and I is initialized to value zero. A message is given to the user to enter the natural number till where he wants to generate the numbers. The entered number is read and stored by the scanf statement. The while loop then checks whether the value of I is less than n i.e., the user entered number if it is true then the control enters the loop body and prints the value of I using the printf statement and increments the value of I to the next natural number this process repeats till the value of I becomes equal to or greater than the number given by the user.

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);

Here the statement is executed, then expression is evaluated. If the condition expression is true then the body is executed again and this process continues till the conditional expression becomes false. When the expression becomes false. When the expression becomes false the loop terminates.

To realize the usefulness of the do while construct consider the following problem. The user must be prompted to press Y or N. In reality the user can press any key other than y or n. IN such case the message must be shown again and the user should be allowed to enter one of the two keys, clearly this is a loop construct. Also it has to be executed at least once. The following program illustrates the solution.

/* Program to illustrate the do while loop*/
#include < stdio.h > //include stdio.h file to your program
void main() // start of your program
{
char inchar; // declaration of the character
do // start of the do loop
{
printf(“Input Y or N”); //message for the user
scanf(“%c”, &inchar); // read and store the character
}
while(inchar!=’y’ && inchar != ‘n’); //while loop ends
if(inchar==’y’) // checks whther entered character is y
printf(“you pressed u\n”); // message for the user
else
printf(“You pressed n\n”);
} //end of for loop

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 > //include the stdio.h file to your program
void main() // Start of the program
{
int I, num=0; //declare the variables and initialize
float sum=0,average; //declare the variables and initialize
printf(“Input the marks, -1 to end\n”); // Message to the user
while(1) // While loop starts
{
scanf(“%d”,&I); // read and store the input number
if(I==-1) // check whether input number is -1
break; //if number –1 is input skip the loop
sum+=I; //else add the value of I to sum
num++ // increment num value by 1
}} end of the program

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 > //Include stdio.h file
void main() //start of the program
{
int I=1, num, sum=0; // declare and initialize the variables
for (I = 0; I < 5; I++) // for loop
{
printf(“Enter the integer”); //Message to the user
scanf(“%I”, &num); //read and store the number
if(num < 0) //check whether the number is less than zero
{
printf(“You have entered a negative number”); // message to the user
continue; // starts with the beginning of the loop
} // end of for loop
sum+=num; // add and store sum to num
}
printf(“The sum of positive numbers entered = %d”,sum); // print thte sum.
} // end of the program.

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)

Sets up two index variables I and j the former initialized to zero and the latter to 100 before the loop begins. Each time after the body of the loop is executed, the value of I will be incremented by 1 while the value of j is decremented by 10.

Just as the need may arise to include more than one expression in a particular field of the for statement, so too may the need arise to omit on or more fields from the for statement. This can be done simply by omitting the desired filed, but by marking its place with a semicolon. The init_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 > //Include stdio.h file
void main() //start main program
{
int I; //declare variable
int sum=0,sum_of_squares=0; //declare and initialize variable.
for(I=0;I < = 30; I+=2) //for loop
{
sum+=I; //add the value of I and store it to sum
sum_of_squares+=I*I; //find the square value and add it to sum_of_squares
} //end of for loop
printf(“Sum of first 15 positive even numbers=%d\n”,sum); //Print sum
printf(“Sum of their squares=%d\n”,sum_of_squares); //print sum_of_square
}

 



About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.



Search Content





Popular Article