简体   繁体   中英

Why the absence of curly brackets after FOR loop in finding factorials in C

This is one of the code to find the factorial of a given non negative integer. When I use the curly brackets after FOR loop for this code, the program runs very slowly. I know that for loops can be used without curly brackets for single line of code , but my code consists of two lines within the for loop. Can someone explain the reason for this ?

#include <stdio.h>
void main()
{

  int input,i,fact=1;
  
  //read user input//
  printf("Enter the number :");
  scanf("%d",&input);
  
  for(i=1;i<=input;i++)
  
   fact=fact*i;
   printf("value of factorial %d is %d",input,fact);
  
  
 }

I have used rextester c compiler to analyze the run time of your program and I could see,

without curly brackets running time : 0.18 sec and with curly brackets running time : 0.16 sec , which might vary time to time for approx +/- 0.05 sec. And if you are using or not using a curly brackets for the single line code in a loop which I guess should not affect the run time of the program.

You can use some other compiler and try running your code.

you are absolutely right when saying

for loops can be used without curly brackets for single line of code

more precisely for loop will run only one line of code if not provided with any curly braces

so your code

for(i=1;i<=input;i++)
   fact=fact*i;

printf("value of factorial %d is %d",input,fact);

will be same as

for(i=1;i<=input;i++)
  {
   fact=fact*i;
  }

   printf("value of factorial %d is %d",input,fact);

but here you are putting braces ( {} ) around both fact=fact*i; and printf("value of factorial %d is %d",input,fact);

so just like @Some programmer dude said in comments section, in this case both of these statements will be executed on each iterations of the loop and thus will be comparatively slower than the first one. But still that should not make big of a difference in terms of total execution time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM