0

I would like to write a program that takes a input from the user and calculates the triangular number. There should also be an option to ask the user if he wants to take another input or exit and that needs to be done using while or do...while. I have the following code written but doesn't do what is intended:

#include <stdio.h>
int main(void)
{
    int n, number, triangularNumber;
    char s = 'Y';
    while (s == 'Y') {
        printf("What triangular number do you want? ");
        scanf("%i", &number);
        triangularNumber = 0;
        for (n = 1; n <= number; ++n)
            triangularNumber += n;
        printf("Triangular number %i is %i\n\n", number, triangularNumber);
        printf("Do you want to continue?\n");
        scanf("%c", &s);
    }
    return 0;
}

The above code only does it once after which it exits. How can I make it run the loop again based on the input I give? Thanks in advance.

user3922546
  • 187
  • 1
  • 6
  • 16
  • 1
    when the user presses `y` is it coming in as lower case? this is probably why it bombs out after 1 loop, you could've debugged this quite easily if so – EdChum Oct 06 '14 at 13:57

2 Answers2

2

scanf("%i",&number); generates a newline that is consumed by your scanf("%c",&s);
Rewrite as scanf(" %c",&s) (contains a space before %c) to ignore all whitespace before input.

Sinstein
  • 887
  • 11
  • 42
1

Two problems: First of all there is a difference between small and capital letters, 'y' != 'Y'.

The second problem, and what you are seeing here, is that the first scanf where you read the number, it leaves the newline in the input buffer. Then the second scanf call reads that newline and writes it to the variable s.

The first problem can easily be solved by making sure the contents of the variable s is a capital letter, by using toupper:

while (toupper(s) == 'Y') { ... }

The second problem can be just as easily fixed by asking scanf to read and discard leading whitespace when getting the character, this is done by simply adding a space before the format code:

scanf(" %c", &s);
//     ^
//     |
// Note space here
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621