0

Ask user to enter a random number between 1 and 100. Then ask how many numbers s/he wants to display that precedes first number s/he enters.

if user enter 9 and wants 3 numbers that precedes 9, your program should display this:

6 7 8 9

I can not finish it.

#include <stdio.h>
#include <stdlib.h>


int main()
{
   int endnum, pre;


    printf("Enter a random number between 1 and 100: ");
    scanf("%d", &endnum);

    printf("how many numbers he wants to display that precedes first number you entered: ");
    scanf("%d", &pre);

    num = endnum - pre;
    printf (%d, num+1)
    num = num + 1
    while (num <= endnum)


    return 0;
}
Community
  • 1
  • 1

2 Answers2

1

That's not a bad first attempt, you just need to fix one slight logic problem and some minor syntax things.

As per my original pseudo-code from your previous question, you need to have a loop doing the printing. You also need semicolons for statement terminators, quotes around strings, and to print the correct value. So change:

printf (%d, num+1)
num = num + 1
while (num <= endnum)

into:

do {
    printf ("%d ", num);
    num = num + 1;
} while (num <= endnum);

In addition, you'll also need to define num the same way you've defined endnum and pre.

Community
  • 1
  • 1
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
1

You're pretty close. You've got pre and endnum. You just want to loop from pre to endnum (inclusive), and print out each of them.

You can use a while loop if you want to, but to me this situation lends itself more directly to a for loop. Something like:

for (num = endnum - pre; num <= endnum; ++num)
{
    printf("%d ", num);
}

where num is pre-declared as a int.

RyGuyinCA
  • 226
  • 1
  • 6