74
Small tricks in for loop
For-loop

We all know working of for loop but it can be used to minimize the size of the program for example :

SYNTAX: for(initialization;condition;increment or decrements)

Initialization part : It works only one once.

Condition part: it works every time when the loop is for increment or decremented.

Increment or decrements part:this part is used for incriminating or decrementing variables. in other words for loop can be used to solve the program in a single line. consider the following part of the program :

To find the reverse of a number :

ex: input: 42139 output :93124

*PROGRAM *

{
    int a,s;
   for(    scanf("%d",&a)  ,  s=0     ;   a!=0     ;    s=s*10+(a%10)   ,   a=a/10)  ;
    printf("%d",s);
     }

In the above program finding reverse of a number is done in a single step.

Explanation: the initialization part always works once thus we are getting input in that part and also initializing the variable once this also takes place once then comes to condition part it always checks condition thus condition is checked there then further in increment and decrements part can not only used to manipulate but can also be used for some other process like i used in the above program by using (,) we can do the step one after other Let me explain u better with another good example:

A program to find the length of the string can be done in single line using for loop:

INPUT:: rangeesh OUTPUT::8

PROGRAM

{ 
char name[100];
for(int i=0,scanf("%s",name);name[i]!='\0';i++);
printf("%d",i);
}

it works the same way which i explained above, thus for loop can be used by the programmers for the efficient use of the memory space in C.

NOTE: the above logic works for C i have tested it and then only explained here.I don't know about other languages,that is whether this trick works or not.

Author

Notifications

?