Why doesn't this c program print the statement

Thread Starter

John99407

Joined Jul 12, 2019
21
Why doesn't this c program print the statement hello

I think it should be print 11 times because loop executed 11 time

Can someone please explain the reason behind it?

Code:
#include<stdio.h>

int main()
{
    int x;

    for(x=-1; x<=10; x++)
    {
        if(x < 5)
            continue;

        else
            break;

        printf("Hello");
    }
  
return 0;
}
 
Last edited:

WBahn

Joined Mar 31, 2012
24,854
Why?

Your if()..else statement guarantees that the printf() statement is never reached.

At the start of each pass through the loop either the continue statement or the break statement. Look up both of those and see how they effect program execution regarding the loop.
 

Thread Starter

John99407

Joined Jul 12, 2019
21
Thanks @WBahn I think it check only the true and false condition and after that hello should be print

At the start of each pass through the loop either the continue statement or the break statement. Look up both of those and see how they effect program execution regarding the loop.
Code:
#include <stdio.h>

int main()
{
    int x;
 
  for(x=-1; x<=10; x++)
    {

        if(x < 5)
            continue;

        else
            break;
     
    }
  
     printf("hello");

    return 0;
}
It get print "hello "onece because after leaving for loop
 

djsfantasi

Joined Apr 11, 2010
5,704
Thanks @WBahn I think it check only the true and false condition and after that hello should be print



Code:
#include <stdio.h>

int main()
{
    int x;

  for(x=-1; x<=10; x++)
    {

        if(x < 5)
            continue;

        else
            break;
 
     printf("hello");
     } 

    return 0;
}
It get print "hello "onece because after leaving for loop
I think you don’t understand the purpose of the continue and break statements. Read the links I inserted.

While x is less than 5, all the code after the statement to the end of the for loop is skipped and the next loop x will have been incremented. So for x less than 5, the loop does nothing.

Then, x is equal to 5. The if clause is false so the statements in the else are executed. The first statement is break! The for loop is terminated, the printf never gets executed and thus you never see hello!
 

MrChips

Joined Oct 2, 2009
19,420
Don't use continue and break.

Construct if statements as follows:

C:
if ( )
{
   ... your code
}
else
{
   ... your code
}
 

WBahn

Joined Mar 31, 2012
24,854
Thanks @WBahn I think it check only the true and false condition and after that hello should be print
The true/false of the in the if() expression determines whether the 'continue' statement or the 'break' statement is executed. But BOTH of these statements stop execution of the code within the for() loop at that point and the rest of the code is not executed on that pass. The continue statement performs the update portion of the for() statement (the 'x++' in this case) and then starts the next pass starting with the test portion of the for() loop (the 'x<=10' in this case). The break statement, on the other hand, terminates the loop entirely and proceeds to the first statement after the loop.
 

WBahn

Joined Mar 31, 2012
24,854
I think it should be print 11 times because loop executed 11 time

Code:
for(x=-1; x<=10; x++)
You have a "one-off" error in your reasoning here. This for() loop (ignoring any break statement or other such issue) would execute twelve times. It would execute with the values -1, then 0, and then all of the values from 1 up through and including 10.

This is worth pointing out because these types of errors are extremely common -- even for highly experienced programmers -- and so you want to start developing the habits needed to avoid them and, more importantly, detect them.

They are so common that they have special names, including "one-off error" and "fence post error" (Google fence post error to see what that term is referring to -- it's a useful visualization to help you avoid this type of error by getting in the habit of asking yourself what is important, the number sections or the number of posts).
 

dl324

Joined Mar 30, 2015
9,151
I think it should be print 11 times because loop executed 11 time
Try again. What is the value of x when the loop terminates?

Since you're obviously new to coding, you should get into the habit of putting braces around the if statements.
Code:
    if (x < 5) {
      continue;
    } else {
      break;
    }
The style you're using seems to be popular, but I don't care for all of the blank space. If you're getting paid by the line; go for it, but I personally find more compact code is easier to follow.
 

WBahn

Joined Mar 31, 2012
24,854
Don't use continue and break.

Construct if statements as follows:

C:
if ( )
{
   ... your code
}
else
{
   ... your code
}
I generally agree -- while there are certainly reasonable and defensible uses for continue and break, they should generally be avoided.

I have a feeling that this code came from some kind of tutorial or example that is intended to familiarize the reader specifically with these two statements. I don't know that this is a particularly useful example, but perhaps the fact that it uses both and, between then, precludes the execution of the printf() statement is the whole point.
 

djsfantasi

Joined Apr 11, 2010
5,704
I never use continue.
The only place I use break is in a switch-case structure.
Yep! I do the same... The use of continue is tempting, but proper design of code blocks always make it a redundant construct.

And break should only be used as you and I use it. A nice compiler addition would be to generate a warning if it were to be used elsewhere.
 

WBahn

Joined Mar 31, 2012
24,854
I never use continue.
The only place I use break is in a switch-case structure.
I used to be the same way and I still only very seldom use either in any place other than a switch() statement, but judicious use of them can make code more readable and maintainable and sometimes also get better performance. But that comes about by using them specifically when they are a good match to the logic and not just because they provide a convenient hack to make poorly designed code somehow work, which is sadly how they are typically used.
 

WBahn

Joined Mar 31, 2012
24,854
Yep! I do the same... The use of continue is tempting, but proper design of code blocks always make it a redundant construct.

And break should only be used as you and I use it. A nice compiler addition would be to generate a warning if it were to be used elsewhere.
A point I make when I teach C is that the very fact that we need to use the break statement in our switch() statements is a sure indication that the very nature of the switch() construct violates the notion of structured programming consisting purely of combinations of sequences, selections, and iterations. The break statement is nothing but syntactic sugar for a goto statement. But if we write anything beyond the simplest switch() statement as an equivalent structured-programming construct it is messy and ugly and difficult to read and maintain. So we make a compromise and use a prettied-up construct that violates the structured-programming paradigm because there are common situations in which a local deviation from that paradigm actually achieves the goals of structured programming better than structured programming does. If we view the continue and break statements in the context of loop structures the same way and make our decisions regarding when to use them from that perspective, they can be quite effective.
 

djsfantasi

Joined Apr 11, 2010
5,704
Neither is bad and that includes goto.
https://www.scribd.com/document/38873257/Knuth-1974-Structured-Programming-With-Go-to-Statements
Knowing when to use them is the key. Multi-levels of nested conditionals are much worse.
I agree.

That’s why when I find myself in the situation, I’ll define several Boolean variables and map all the possible combinations into a state (byte or integer) variable that I use in a switch...case structure. This technique basically maps each possible set of conditions onto a single variable. The code looks like a state table, and in a self-documenting manner, executes the correct outcome out of the set of possible outcomes.
 

Thread Starter

John99407

Joined Jul 12, 2019
21
Thanks to all of you. I appreciate all of your explantations That was the example in the tutorial I was confused

Code:
#include<stdio.h>

int main()
{
    printf ("Hello");

    main();

    return 0;
}
When I run code It prints Hello continuously.

We are calling main function within main function.

I don't understand why does code prints Hello continuously ?
 

WBahn

Joined Mar 31, 2012
24,854
Thanks to all of you. I appreciate all of your explantations That was the example in the tutorial I was confused

Code:
#include<stdio.h>

int main()
{
    printf ("Hello");

    main();

    return 0;
}
When I run code It prints Hello continuously.

We are calling main function within main function.

I don't understand why does code prints Hello continuously ?
This is an example of recursion -- a function calling itself. What this silly example can't even hint at is that recursion is an extremely powerful tool in the programmer's toolbox. There are languages, such as some in the Lisp-family, that do not have a looping structure at all -- iteration can only be done via recursion.

If you just walk through the code you'll see why it behaves this way (though not how it is able to behave this way).

You start running main() which first prints "Hello" and then you call a function named main(), which first prints "Hello" and then calls a function named main(), which first prints "Hello" and then calls a function ....

Each call puts a new block of memory (called a stack frame) onto the runtime stack that will stay there until that particular call finally returns. Since that will never happen in this case (notice that in the description above you don't see anything about returning zero), the contents of the stack continues to grow. Since the maximum size of the stack has a finite limit, eventually you exceed that limit and, usually, the operating system kills your program. This is known as "blowing the stack" and is a common cause of program crashes (particularly during development).
 

nsaspook

Joined Aug 27, 2009
6,504
I agree.

That’s why when I find myself in the situation, I’ll define several Boolean variables and map all the possible combinations into a state (byte or integer) variable that I use in a switch...case structure. This technique basically maps each possible set of conditions onto a single variable. The code looks like a state table, and in a self-documenting manner, executes the correct outcome out of the set of possible outcomes.
One thing we should remember is these self imposed restrictions are mainly for the benefit of the human when doing abstract programming object manipulations. A good compiler will convert your perfectly structured program into a unstructured spaghetti of tables and goto/branches if they execute the code in the most efficient manner. For low-level programming, sequencing and error exits, programming structure normally takes a seat behind machine mandated structure correctness.
 

djsfantasi

Joined Apr 11, 2010
5,704
A point I make when I teach C is that the very fact that we need to use the break statement in our switch() statements is a sure indication that the very nature of the switch() construct violates the notion of structured programming consisting purely of combinations of sequences, selections, and iterations. The break statement is nothing but syntactic sugar for a goto statement. But if we write anything beyond the simplest switch() statement as an equivalent structured-programming construct it is messy and ugly and difficult to read and maintain. So we make a compromise and use a prettied-up construct that violates the structured-programming paradigm because there are common situations in which a local deviation from that paradigm actually achieves the goals of structured programming better than structured programming does. If we view the continue and break statements in the context of loop structures the same way and make our decisions regarding when to use them from that perspective, they can be quite effective.
I disagree.

Switch...case is a shortcut structure that could be implemented by a series of if...else structures. I’d like it if the break was not required, but it’s inclusion adds flexibility to the construct.

The problem occurs w

While the switch...case construct doesn’t violate structured programming standards, it flexibility allows this to happen. I personally wish hierarchical code could be implemented. It would save memory. Look at the following pseudo-code:
Code:
switch case (myCase)
  case (1,2) {
      //common pre-case code
      case (1){
         //case 1}
      case (2){
          // case 2}
   // common post-case code
   }
// etc...
Ironically, the above structure can be obtained by the judicious use of break statements and stacking case statements with embedded switch...case statements

The following code snippet shows what I mean.

Code:
// Pre-Command test group 1
case (cmd[comPre1]){
   case (cmd-a1)
   case (cmd-b2)
   case(cmd-c...){
         // common pre-stmnts: grp1
         break;
         }
//Pre-Command test group 2
case (cmd[comPre2]){
   case (cmd-d1)
   case (cmd-e2)
   case(cmd-f...){
         // common pre-stmnts: grp2
        break;
         }
// ...

//command groups
switch case
   case (x1){
         // first command statements
         break;
   case (x2){
       // first command statements
       break;
// ...
   case (xn){
      // first command statements
      break;

// Post-Command test group 1
case (cmd[comPost1]){
   case (cmd-a1)
   case (cmd-b2)
   case(cmd-c...){
         // common post-stmnts: grp1
         break;
         }
//Post-Command test group 2
case (cmd[comPost2]){
   case (cmd-d1)
   case (cmd-e2)
   case(cmd-f...){
         // common poststmnts: grp2
        break;
         }
// ...
 
Top