Reputation: 1909
I just started venturing into C coming from PHP. I'm having trouble with the printf()
function when its called from within another function:
#include <stdio.h>
void printloop (int valx) {
int x;
for (x = valx; x < 5; x++) {
printf("Value of x is: %d\n", x);
}
}
int main() {
printloop(5);
return 0;
}
The program will compile and run but there is no output on screen.
Upvotes: 0
Views: 172
Reputation: 101
In your main, your are calling printloop and giving it the value 5. This means that you're making valx = 5 and when you say x = valx
inside of your loop, you're setting x equal to 5 as well. When your loop gets to its conditional, it will never run because because x is equal to 5, not less than it.
Upvotes: 1
Reputation: 346
What's wrong here is that your logic is saying 5 < 5, which is false. Your for
loop is not executing because when your printloop function is invoked at printloop(5);
it is passing the integer value of 5.
void printloop (int valx) {
int x;
for (x = valx; x < 5; x++) {
printf("Value of x is: %d\n", x);
}
Your printloop function is receiving a value of 5, setting x inside of your function to x = 5.
When it is time for your for loop to execute you will have
void printloop (int valx) {
int x = 5;
for (5 = valx; 5 < 5; 5++) {
printf("Value of x is: %d\n", x);
}
}
the for
loop will see 5 < 5, which is false, and thus the loop will not execute.
I think what you want to say is
#include <stdio.h>
void printloop (int valx) {
int x;
for (x = 0; x < valx; x++) {
printf("Value of x is: %d\n", x);
}
}
int main() {
printloop(5);
return 0;
}
Which will output:
Value of x is: 0
Value of x is: 1
Value of x is: 2
Value of x is: 3
Value of x is: 4
I hope this makes sense, and keep up the good work!
Upvotes: 5
Reputation: 187
It's because you passed 5 to the function printloop, and the for loop inside printloop will only run if the given argument is less than 5. You could either change that value or pass an integer smaller than 5.
Upvotes: 0
Reputation: 1
#include <stdio.h>
void printloop (int valx) {
int x;
for (x = valx; x < 5; x++) {<--- **Your problem is here ( x = 5; x < 5; x++)
printf("Value of x is: %d\n", x);
}
}
int main() {
printloop(5);
return 0;
}
You are telling the loop while it is less than 5 (which it is not because of the value you gave to valx) thus it doesn't print anything because it doesn't go into the loop
Upvotes: 0
Reputation: 44376
When you invoke the printloop
function with 5
the for loop essentially becomes
for (x = 5; x < 5; x++) {
//...
}
And x < 5
will never be true.
I guess what you meant was something like
for (x = 0; x < valx; x++) {
//...
}
Upvotes: 6