Looping questions in c and answers


Looping questions and answers with explanation for written test exam and interview in c programming language

(1)

What will be output of following c code?

#include<stdio.h>
extern int x;
int main(){
    do{
        do{
             printf("%o",x);
         }
         while(!-2);
    }
    while(0);
    return 0;
}
int x=8;



Explanation


Output: 10
Explanation:

The variable x is declared as an extern type, prompting the compiler to search for its definition. In this code, the definition is found at the end, where x is assigned a value of 8. Consequently, the value of x is 8.

The code features two do-while loops, known for executing at least once even if the condition is initially false. The printf statement within the outer do-while loop prints the octal number 10, equivalent to the decimal number 8 (%o is used for octal format).

Inside the inner do-while loop, the condition is !-2, which evaluates to 0 (false) in C. Consequently, the program control exits the inner loop. The outer do-while loop's condition is now 0 (false) as well, leading to the program control exiting the outer loop as well.




Hide



(2)
What will be output of following c code?
        
#include<stdio.h>
int main(){
    int i=2,j=2;
    while(i+1?--i:j++)
         printf("%d",i);
    return 0;
}



Explanation


Output: 1
Explanation:

n the first iteration of the while loop with the condition i + 1 ? --i : ++j:

  • 1. i + 1 evaluates to 3 (True), causing the ternary operator to return --i, resulting in 1.
  • 2. In C, 1 is considered true, so the while condition is true, and the printf statement prints 1.

In the second iteration:

  • 1. i + 1 evaluates to 2 (True), causing the ternary operator to return --i, resulting in 0.
  • 2. In C, 0 is considered false, so the while condition is false, and the program control exits the while loop.



Hide



(3)
What will be output of following c code?

#include<stdio.h>
int main(){
    int x=011,i;
    for(i=0;i<x;i+=3){
         printf("Start ");
         continue;
         printf("End");
    }
    return 0;
}



Explanation


Output: Start Start Start
Explantion:

011 is octal number. Its equivalent decimal value is 9. So, x = 9 First iteration: i = 0 i < x i.e. 0 < 9 i.e. if loop condition is true. Hence printf statement will print: Start Due to continue keyword program control will come at the beginning of the for loop and value of variable i will be: i += 3 i = i + 3 = 3 Second iteration: i = 3 i < x i.e. 3 < 9 i.e. if loop condition is true. Hence printf statement will print: Start Due to continue keyword program control will come at the beginning of the for loop and value of variable i will be: i += 3 i = i + 3 = 6 Third iteration: i = 3 i < x i.e. 6 < 9 i.e. if loop condition is true. Hence printf statement will print: Start Due to continue keyword program control will come at the beginning of the for loop and value of variable i will be: i += 3 i = i + 3 = 9 fourth iteration: i = 6 i < x i.e. 9 < 9 i.e. if loop condition is false. Hence program control will come out of the for loop.



Hide





(4)What will be output of following c code?


#include<stdio.h>
int main(){
    int i,j;
    i=j=2,3;
    while(--i&&j++)
         printf("%d %d",i,j);
    return 0;
}




Explanation


Output: 13
Explanation:
Initial value of variable
i = 2
j = 2
Consider the while condition : --i && j++
In first iteration:
--i && j++
= 1 && 2 //In c any non-zero number represents true.
= 1 (True)
So while loop condition is true. Hence printf function will print value of i = 1 and j = 3 (Due to post increment operator)
In second iteration:
--i && j++
= 0 && 3  //In c zero represents false
= 0  //False
So while loop condition is false. Hence program control will come out of the for loop.




Hide





(5)What will be output of following c code?



#include<stdio.h>
int main(){
    static int i;
    for(++i;++i;++i) {
         printf("%d ",i);
         if(i==4) break;
    }
    return 0;
}



Explanation


Output: 24
Explanation:

The default value of a static int variable in C is zero, so the initial value of variable 'i' is 0.

In the first iteration:

  • 1. The for loop initializes with ++i, setting 'i' to 1.
  • 2. The loop condition, ++i, evaluates to 2 (true), resulting in the printf statement printing 2.
  • 3. The loop increments with ++i, updating 'i' to 3.

In the second iteration:

  • 1. The loop condition, ++i, evaluates to 4 (true), and the printf statement prints 4.
  • 2. Although there is an 'if' condition that is also true, the program control exits the for loop due to the break keyword.




Hide



(6)What will be output of following c code?

#include<stdio.h>
int main(){
    int i=1;
    for(i=0;i=-1;i=1) {
         printf("%d ",i);
         if(i!=1) break;
    }
    return 0;
}



Explanation


Output: -1
Explanation:

With an initial value of 1 for variable 'i':

In the first iteration:

  • The for loop initializes 'i' to 0.
  • The loop condition, 'i = -1', is true (non-zero), resulting in the printf function printing the value of 'i' (-1).
  • The if condition is true since 'i' is not equal to 1, causing the program control to exit the for loop due to the break keyword.


Hide



(7)What will be output of following c code?

#include<stdio.h>
int main(){
    for(;;) {
         printf("%d ",10);
    }
    return 0;
}



Explanation


Output: Infinite loop
Explanation:
In a for loop, each part (initialization, condition, and iteration) is optional.



Hide



(8)What will be output of following c code?
        
#include<stdio.h>
int r();
int main(){
    for(r();r();r()) {
         printf("%d ",r());
    }
    return 0;
}
int r(){
    int static num=7;
    return num--;
}



Explanation


Output: 5 2
Explanation:

In the first iteration:

  • 1. Loop initialization: r() = 7
  • 2. Loop condition: r() = 6 (true), leading to the printf function printing r() (5).
  • 3. Loop increment: r() = 4

In the second iteration:

  • 1. Loop condition: r() = 3 (true), resulting in the printf function printing r() (2).
  • 2. Loop increment: r() = 1

In the third iteration:

  • 1. Loop condition: r() = 0 (false), prompting the program control to exit the for loop.




Hide



(9)What will be output of following c code?
        
#include<stdio.h>
#define p(a,b) a##b
#define call(x) #x
int main(){
    do{
         int i=15,j=3;
         printf("%d",p(i-+,+j));
    }
    while(*(call(625)+3));
    return 0;
}



Explanation


Output: 11
Explanation:
First iteration:
p(i-+,+j)
=i-++j   // a##b
=i - ++j
=15 – 4
= 11
While condition is : *(call(625)+ 3)
= *(“625” + 3)
Note: # preprocessor operator convert the operand into the string.
=*(It will return the memory address of character ‘\0’)
= ‘\0’
= 0  //ASCII value of character null character
Since loop condition is false so program control will come out of the for loop.




Hide



(10)

#include<stdio.h>
int main(){
    int i;
    for(i=0;i<=5;i++);
    printf("%d",i)
    return 0;
}



Explanation


Output: 6
Explanation:
A for loop without any body is indeed possible.



Hide



(11)What will be output of following c code?

#include<stdio.h>
int i=40;
extern int i;
int main(){
    do{
         printf("%d",i++);
    }
    while(5,4,3,2,1,0);
    return 0;
}



Explanation


Output: 40
Explanation:

With an initial value of 40 for variable 'i':

In the first iteration, the printf function prints i++ (40).

The do-while condition is (5,4,3,2,1,0), where the comma operator returns 0. As the while condition evaluates to false, the program control exits the for loop.




Hide



(12)What will be output of following c code?

#include<stdio.h>
char _x_(int,...);
int main(){
    char (*p)(int,...)=&_x_;
    for(;(*p)(0,1,2,3,4); )
         printf("%d",!+2);
    return 0;
}
char _x_(int a,...){
    static i=-1;
    return i+++a;
}



Explanation


Output: 0
Explanation:

In C, three continuous dots (...) represent a variable number of arguments.

Considering a pointer to the function x, denoted as 'p':

In the first iteration of the for loop:

  • 1. Initial value: Nothing (In C, it is optional)
  • 2. Loop condition: (*p)(0,1,2,3,4) where p = &_x_
  • 3. This evaluates to _x_(0,1,2,3,4) since * and & cancel each other.
  • 4. The function returns i+++a, equivalent to i + ++a, resulting in -1 + 1 and finally, 0.
  • 5. Although the condition is false, the printf function prints 0, highlighting a quirk in the C language.



Hide



(13)What will be output of following c code?

#include<stdio.h>
int main(){
    int i;
    for(i=10;i<=15;i++){
         while(i){
             do{
                 printf("%d ",1);
                 if(i>>1)
                      continue;
             }while(0);
             break;
         }
    }
    return 0;
}



Explanation


The output is: 1 1 1 1 1 1.

Note : The for loop executes six times. It's important to note that the continue keyword in the do-while loop brings the program control to its while condition (while(0)), which is always false.




Hide



(14)How many times this loop will execute?

#include<stdio.h>
int main(){
    char c=125;
    do
         printf("%d ",c);
    while(c++);
    return 0;
}



Explanation


Output: Finite times
Explanation:

If we increment the char variable 'c', it will follow the sequence: 126, 127, -128, -127, 126, ..., 3, 2, 1, 0. The loop will terminate when 'c' reaches 0.

Hide



(15)What will be output of following c code?
        
#include<stdio.h>
int main(){
    int x=123;
    int i={
         printf("c" "++")
    };
    for(x=0;x<=i;x++){
         printf("%x ",x);
    }
    return 0;
}



Explanation


Output: c++0 1 2 3
Explanation:

The first printf function prints 'c++' and returns 3 to variable 'i'. The for loop executes three times, and the printf function within it prints 0, 1, and 2, respectively.



Hide




Looping tutorial in c

47 comments:

Sankalp said...

very good examples and explanations are very clear.
excellent efforts :)

GUPTA said...

Hey I really apprecicate ur site....Awesome explanations....This is the first page i hv read and really understood....Kudos to u guys !!
:)

blogger.MalapaTi said...

hey i have one doubt in Q:15
how does %x will work i tried with %i also it was working could you please elaborate about this.
thanks in Advance !!
have a Great Day!!

Ravi said...

Yes this all are very important question, and also explanation is very clear and in very nice manner.

Thanx A Lot !!!!

Unknown said...

In question 9

can you explain macro a##b

Unknown said...

very useful page

swarup said...

can u please explain how the return stmt returns 3 value to i variable in 15th question

Priyanka kumari said...

Return type of prinf function is integer which is total numbers of characters its prints. In this example printf("c" "++") it printing three characters 'c','+' and '+' so it will return 3.

Priyanka kumari said...

in printf statement
%x : prints number in hexadecimal format
%i : prints number in integer format
%d : prints number in decimal format

Priyanka kumari said...

## is oken pasting operator.Better go through this link:
Use of # and ## operator in c programming language

Anonymous said...

hi ritesh u r doing great job..

this is helping to lot of guys like us

DHANU said...

GOOD JOB

Anonymous said...

wt is looping

Roja said...

can you explain macro a##b and #x

Ahmed Ismail said...

First: Really it is a great page and it benefit me alot to fresh my memory.
For Q.12:
There is not any bug.
but the compiler evaluated i+++a as following: i++ + a.
So, we have (-1)++ + 0 = -1 .... true and printf() statement is executed.


i+++a is evaluated as i++ + a.

That is due to compiler really do not ignore all white spaces.

for the case: i+++a: it handle the variable i then it looks for the longest possible operator.
we have 2 options: + , ++ / it cannot consider +++ as an operator as there is not an operator (+++)
The longest one is ++.
then the remained operator is +. and then handle the next variable.

To make idea clear:
consider we have:
i = -1;
a =0;
z = i+++++a;

Now the compiler will parse it: i++ ++ + a. and it will bring a compilation error. (Lvalue required as increment operand).

If we modified the expression and added some white space it will work.
z = i++ + ++a;
it works and result will be zero.

Unknown said...

c is very imprtnt sub

enorмous нaвiв said...

At one college, the tuition for a full-time student is $6,000 per semester. It has been announced that the tuition will increase by 2% each year for the next 5 years. Design a program with a loop that displays the projected semesters tuition amount for the next five years.
how would this be done?

Anonymous said...

#include
int main()
{
int semf=6000,prof;//semester fees , projected fees
int i,y=0;

for(i=1;i<=10;i++)
{
semf=(semf+6000*2/100);
prof=semf;
printf(" Tution amount for %d semester %d\n",y=y+1,prof);

}

getch();
return 0;
}

hafeehathim said...

Hi,
can any one explain how does the following while loop work?
while(5,4,3,2,1,0)

varsha said...

can any 1 give me solution for 1+1/3+1/5+....+1/n
plzzzzzzz guys

vykunta@galavili.com said...

ritesh kumar good hard work..

Anonymous said...

printf("%d",!+2); pls explain it and what is comma(,) operator in c and how it works in while loop

Anonymous said...

Is it possible to create a
C program to find the largest and smallest of n numbes inputed by user using while loop?

SOYAM KANNARAJU said...

the way of explanation and way of writing is so ............great..............

Unknown said...

what will be output of following prograam??

for (m=0; m<3; ++m)
t=(m%2)? m:m+2;
printf("%d",t)

anjaneyareddy said...

tanx frnds
and Excellent

Ankit ghiya said...

what is the difference of using %d and %i?
I think both produce same result.
Please clear my doubt about this.

Gopal Singh said...

output will be 2

Unknown said...

answer will be 4

Unknown said...

Question 9:
Could somebody please explain to me how *("625" + 3) return the memory address of character '\0'?
what is this expression mean ("625" + 3) in C?

Unknown said...

Here loop will never execute because the last number is 0.
Suppose if you try this "while(5,4,3,2,1)" the loop will never end because the last number is one.
It means while takes the last number as condition.

Unknown said...

#include

int main()
{
int i,great=0,low=0,a[8];
printf("Enter 8 numbers: ");
for(i=0;i<8;i++)
{
scanf("%d ",&a[i]);
}
great=a[0];
low=a[0];
while(i--)
{
if(greata[i])
{
low=a[i];
}
}
printf("Greatest: %d \n",great);
printf("Lowest : %d \n",low);
return 0;
}

Unknown said...

Here you have to know the operators Associativity. Both '+' & '!' have same priority. The Associativity is from right to left. So first addition will take place. 0+2 is 2. And "!2=0". Any positive number with NOT symbol is equal to zero.

Srujan said...

Agree with this explanation.

Unknown said...

write a c program to generate the customer bill for a point of sale system used in a retail shop. The program must use a predefined list of ANY 5 items, while the user will enter the item code and the quantity for n number of items selected by the customer, to print the the bill including a goods and service tax of 6%. ( I am stuck here creating the predefined list and giving item codes. Can any of you experts can help me out as soon as possible? )

Unknown said...

Is there any1 here who could help me?

Unknown said...

what is the meaning of !-2

Unknown said...

i love you

priyank said...

Can You Improve the Explanation Section..
I didn't find your explanation Too concise and clear

Unknown said...

#include
int main()
{
int semsterfee=6000,projectfee;
int i,y=1;
printf("Tution amount for 1 semester = $6000\n");

for(i=2;i<=10;i++)
{
semsterfee=(semsterfee+6000*2/100);
projectfee=semsterfee;
printf(" Tution amount for %d semester= $%d\n",y=y+1,projectfee);

}

getch();
return 0;
}

Unknown said...

#include
int main()
{
int m,t;
for (m=0; m<3; ++m)
t=(m%2)? m:m+2; // Output is 4
{
printf("output=%d",t);
}

}

Unknown said...

%i : prints number in integer format
%d : prints number in decimal format

Unknown said...

i=Not oprater,its revers the value

Unknown said...
This comment has been removed by the author.
Unknown said...

These are so tricky and so helpful in understanding the concepts! Thank you!

Shaem said...

Pls help me...
when i write a code like this...

#include
int main(void)
{
int count=0;
while (count < 10 && ++count)
printf("count is %d\n", count);
return 0;
}
output :
1 2 3 4 5 6 7 8 9 10
But when i change ++ count by count ++
#include
int main(void)
{
int count=0;
while (count < 10 && count++)
printf("count is %d\n", count);
return 0;
}
output : Nothing.
Pls give me a solution.

Muhammed Shiyadh said...

Good questions