在for循环中添加{ - }:c编程

时间:2013-12-15 11:24:24

标签: c

程序运行良好且清晰,但我只是想问为什么我们在for循环和for循环结束时添加{ - }?程序运行正常而不添加它们但是当我试图在for循环中添加{ - }时,prgram并没有运行正常,我们是不是想在每次循环中添加{ - }?为什么程序在没有它们的情况下运行良好并且没有和它们一起运行?

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

4 个答案:

答案 0 :(得分:1)

没有大括号,一个陈述作为其范围

喜欢

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

相当于

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

答案 1 :(得分:1)

循环在循环后立即执行语句。什么是声明?它可以是:

一段代码以;结尾。

代码块以{开头,以}结尾。

你的for-loop

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

使用语句的第一个定义,但您也可以将其写为

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

它应该可以正常工作。

答案 2 :(得分:1)

非正式:for循环有一个语句体。要使用多个语句,可以将它们嵌套在块语句中。

答案 3 :(得分:0)

如果块中只有一个语句,则大括号是可选的