Walk-through of a simple c program

1.7k Views Asked by At

I have this question to walk through and show the output when this program is run. The one thing I don't understand is how f is found to be four or even found at all.I know the correct answer is

7 falcon 3

9 RK 4

_
I just dont know how they found the f value to be 4 ,once i have that I can do the rest fine

#include <stdio.h> 
#include <string.h> 

void falcon(int f); 
char a[20]; 

int main() { 
    int i, j; 
    a[3] = 'G'; 
    a[1] = 'K'; 
    i = 3 + 2 * 3; 
    j = 4; 
    a[2] = 'Y'; 
    falcon(j); 
    printf("%d %s %d\n", i, a, j); 
} 

void falcon(int f) { 
    int j; 
    j = 11 % f; 
    printf("%d falcon %d\n", f+3, j); 
    a[2] = '\0'; 
    a[0] = 'R'; 
}
2

There are 2 best solutions below

0
On BEST ANSWER

Let's walk through the program together (with some of the irrelevant bits cut out).

#include <stdio.h> 
#include <string.h> 

void falcon(int f); 
char a[20]; 

int main() {
    int i, j;
    j = 4; 
    falcon(j); // in other words, falcon(4). Now, let's go down to the 
    // falcon function where the first argument is 4.
    printf("%d %s %d\n", i, a, j); 
} 

void falcon(int f) { // Except here we see that in this function,
                     // the first argument is referred to by 'f', 
                     // which, as we saw, is 4.
    int j; 
    j = 11 % f; // here, j is equal to the remainder of 11 divided by
                // f, which is 4.
    printf("%d falcon %d\n", f+3, j);
}
0
On

Now you see why code should not have is and js for variable names except in probably, loops.

Anyways,

char a[20]; on the top says that a is a globally declared character array.

int main()
{ 
   int i, j; // declares two local stack variables, i and j
   a[3] = 'G'; // sets 4th location in 'a'(remember, arrays start at 0) to 'G'{useless}
   a[1] = 'K'; // sets 2nd location in 'a' array to 'K'
   i = 3 + 2 * 3; // i is now 9 {remember, multiplication before addition}
   j = 4;    // j is now 4
   a[2] = 'Y';  // a[2] is now 'Y'
   falcon(j);  // call to falcon, with argument 4, explained next
   printf("%d %s %d\n", i, a, j);  // prints "9 RK 4"
   //return 0; -- this should be added as part of 'good' practices
} 



 void falcon(int f) 
 { 
     // from main(), the value of 'f' is 4
     int j;  // declares a local variable called 'j'
     j = 11 % f;  // j = 11 % 4 = 3 
     printf("%d falcon %d\n", f+3, j); // prints 7 falcon 3
     a[2] = '\0'; // a[2] contains null terminating character, overwrites 'Y'. 
     a[0] = 'R'; // sets a[0] to 'R'. At this moment, printf("%s",a); must yield "RK"
 }