Thread: User enter number sequence (terminated by 0)

  1. #1
    Registered User
    Join Date
    Feb 2013
    Location
    Sweden
    Posts
    171

    Question User enter number sequence (terminated by 0)

    The following program is supposed to let the user enter a sequence of numbers until the user enters 0. Then the program will stop. After that I want to print the array with the numbers that the user have entered.

    But this isn't working well. And I guess it is because when I enter a number sequence and press enter (without even entering the terminating 0) the array is initialized to have all numbers as 0.

    So is that why the program terminates after this?

    The reason to initialize the array with zeros is because I later on need to calculate the sum of the numbers.

    Code:
    #pragma warning(disable:4996)
    #include <stdio.h>
    #define SIZE 100
    
    
    int main() {
    
    
        float numbers[SIZE] = { 0 };
    
    
        int i = 0;
        do {
            printf("Enter a sequence of numbers: ");
            scanf("%f", &numbers[i]); 
            getchar();
            i++;
    
    
        } while (numbers[i] != 0); 
    
    
    
    
        return 0;
    }

  2. #2
    Registered User
    Join Date
    May 2009
    Posts
    4,183
    Code:
    while (numbers[i] != 0);
    You have an off by one logic error

    Try this instead

    Code:
    while (numbers[i-1] != 0);
    Tim S.
    "...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.." Bill Bryson

  3. #3
    Registered User
    Join Date
    Feb 2013
    Location
    Sweden
    Posts
    171
    Don't see how this helps put the entered numbers into the array though.
    I just get an output with 0's which the array is initialized to be.

    Input: 1.0 2.0 0
    Output: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ...

    Code:
    	float numbers[SIZE] = { 0 };
    
    
    	int i = 0;
    	do {
    		printf("Enter a sequence of numbers: ");
    		scanf("%f", &numbers[i]); 
    		getchar();
    		i++;
    
    
    	} while (numbers[i-1] != 0); 
    
    
    	for (int i = 0; i < SIZE; i++) {
    		printf("%d ", numbers[i]);
    	}
    
    
    	getchar();

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 14
    Last Post: 06-26-2015, 03:58 PM
  2. How to restrict user to enter a four digit number?
    By Boston357 in forum C++ Programming
    Replies: 26
    Last Post: 08-22-2014, 12:28 PM
  3. Replies: 2
    Last Post: 08-22-2014, 07:00 AM
  4. How to identify that user has terminated the program
    By abhijitbanerjee in forum C Programming
    Replies: 2
    Last Post: 07-11-2007, 04:43 PM
  5. user can hit enter all day long
    By Ash1981 in forum C Programming
    Replies: 7
    Last Post: 01-01-2006, 05:33 AM

Tags for this Thread