-3

I am using for-loops to read and print the values. As you can see it stores only the last input. Any suggestions?

#include <stdio.h>
int main()
{
    int i;
    for(int a = 0; a < 5; a ++)
    {
        printf("Enter your age: ");
        scanf("%d", &i);
    }
    for(int b = 0; b < 5; b ++)
    {
        printf("Hi I'm %d years old\n", i);
    }
    return 0;
}

And here's the output . .

Enter your age: 11
Enter your age: 22
Enter your age: 33
Enter your age: 44
Enter your age: 55
Hi I'm 55 years old
Hi I'm 55 years old
Hi I'm 55 years old
Hi I'm 55 years old
Hi I'm 55 years old
Infinite Recursion
  • 6,511
  • 28
  • 39
  • 51
  • 4
    Start with Arrays chapters – P0W Oct 17 '14 at 05:07
  • You are new to programming altogether I guess. You are using a single variable to hold a list of variables. –  Oct 17 '14 at 05:09
  • Describe the problem clearly, and please avoid describing yourself (words like noob, beginner etc). On Stack Overflow, the focus is on the content, not on the users. Also, first describe the problem, then include the code. Good Luck. – Infinite Recursion Oct 17 '14 at 05:43

1 Answers1

1

Your problem is that your are only storing the last answer you receive. The simplest solution that I can give you is to use array:

#include <stdio.h>
int main()
{
    int ages[5];
    for(int i = 0; i < 5; i++)
    {
        printf("Enter your age: ");
        scanf("%d", &ages[i]);
    }
    for(int i = 0; i < 5; i++)
    {
        printf("Hi I'm %d years old\n", ages[i]);
    }
    return 0;
}

but really, pick up one of those recommend books and read a bit more

Community
  • 1
  • 1
Amadeus
  • 10,199
  • 3
  • 25
  • 31