darksphere
darksphere

Reputation: 59

adding { - } in a for loop : c programming

the program runs fine and clear, but i just wanted to ask why didnt we add { - } in the beggining and end of the for loop ? the program runs fine without adding them but when i tried to add { - } in the for loop the prgram didnt run fine, arent we suppose to add { - } in ever begging and end of every loop ? and why did the program run fine without them and didnt run fine with them ?

int c, first, last, middle, n, search, array[100];

   printf("Enter number of elements\n");
   scanf("%d",&n);

   printf("Enter %d integers\n", n);

   for ( c = 0 ; c < n ; c++ )
      scanf("%d",&array[c]);

   printf("Enter value to find\n");
   scanf("%d",&search);

   first = 0;
   last = n - 1;
   middle = (first+last)/2;

   while( first <= last )
   {
      if ( array[middle] < search )
         first = middle + 1;    
      else if ( array[middle] == search ) 
      {
         printf("%d found at location %d.\n", search, middle+1);
         break;
      }
      else
         last = middle - 1;

      middle = (first + last)/2;
   }
   if ( first > last )
      printf("Not found! %d is not present in the list.\n", search);

Upvotes: 0

Views: 108

Answers (4)

tommyo
tommyo

Reputation: 551

Informally: The for-loop has a one-statement body. To use multiple statements, you nest them in a block-statement.

Upvotes: 1

Humungus
Humungus

Reputation: 585

A loop executes the statement immediately after it in a loop. What is a statement? It can be:

A piece of code ended with ;.

A block of code started with { and ended with }.

Your for-loop

for ( c = 0 ; c < n ; c++ )
  scanf("%d",&array[c]);

uses the first definition of statement, but you could also write it as

for ( c = 0 ; c < n ; c++ )
{
  scanf("%d",&array[c]);
}

and it should work fine.

Upvotes: 1

exexzian
exexzian

Reputation: 7890

Without braces it takes ONE statement as its scope

like

for ( c = 0 ; c < n ; c++ )
 scanf("%d",&array[c]);

Equivalent of

 for ( c = 0 ; c < n ; c++ )
{
  scanf("%d",&array[c]);
}

Upvotes: 1

abasterfield
abasterfield

Reputation: 2292

If there is only one statement in the block the braces are optional

Upvotes: 0

Related Questions