user7696754 user7696754 - 9 months ago 30
C Question

Printing Hello World Only 3 Times Not 5

I am trying to print hello world 5 times using a new function to do so called: hello_world. I am using a for loop in the hello_world function. This is the result I get:

C:\Users\darce\Desktop\c\functions\cmake-build-debug\functions.exe
Hello, World!
Hello, World!
Hello, World!

Process finished with exit code 0


and here is my code:

#include <stdio.h>

void hello_world(int n) {
for (int i = 0; i < n; i++)
{
puts("Hello, World!");
i++;
}
}

int main ()
{
hello_world(5);
return 0;
}


My question is why is it only printing out 3 times instead of 5? For the param int n I made sure was 5 before I ran it.

Answer Source

Your problem is that you increment i twice. So, it will be 0, then 2, then 4, then 6, which is greater than 5. In order to fix it, simply remove the i++; line after the puts("Hello, World!"); or transform your for loop into a while loop.

Solution 1

#include <stdio.h>

void hello_world(int n) {
    for (int i = 0; i < n; i++)
    {
        puts("Hello, World!");
    }
    /* CAN BE SIMPLIFIED BY REMOVING THE BRACES */

}

int main ()
{
    hello_world(5);
    return 0;
}

Solution 2

#include <stdio.h>

void hello_world(int n) {
    int i = 0;
    while (i < n)
    {
        puts("Hello, World!");
        i++;
    }
}

int main ()
{
    hello_world(5);
    return 0;
}