Jagan
Jagan

Reputation: 4897

Find out output of c-program

#include<stdio.h>
void compute(int);
int cube(int);
int main( )
{
        compute(3);
}
void compute(int in)
{
        int res=0,i;
        for(i=1;i<=in;i++);
        {
                res=cube(i);
                printf("%d %d",res,i);
        }
}
int cube(int n)
{
        return (n*n*n);
}

~
output : 64 4

How does it happen ?

Upvotes: 1

Views: 1768

Answers (3)

pmg
pmg

Reputation: 108986

Since you are using C99, you may want to get into the habit of declaring the variable controlling a for loop inside the for statement itself.

    for (int i=1; i<=in; i++);
    {
        /* i is not in scope here */
    }

And, now that I've written that, the idiomatic way to write a loop is to start at 0 and test with <

    for (int i=0; i<in; i++);
    {
        /* i is not in scope here */
    }

Upvotes: 0

Mark Tolonen
Mark Tolonen

Reputation: 178224

Due to a semicolon on your for line, the statement increments i until it is not <= 3, which is 4. Then the code below it runs.

Upvotes: 6

eduffy
eduffy

Reputation: 40252

Semicolon at the end of your for line.

Upvotes: 15

Related Questions