Home > Mobile >  Sum of N natural numbers in C
Sum of N natural numbers in C

Time:10-19

The exercise asks me to write a program that first prompts the user to type in a sequence of natural numbers and then displays the sum of all the numbers in the sequence entered, assuming that the sequence of numbers ends with the integer value -1 (this value must not be added to the final result) and that the sequence may be empty. I'm supposed to use a while statement in the implementation.

Execution examples (the line 3 4 5 6 -1 is the user input):

Type in a sequence of natural numbers that ends in -1: 
3 4 5 6 -1
The sum is: 
18 

Here's the code I have:

#include <stdio.h>

int main(){
    int aux=0, aux_1=0;
    printf("Escriba una secuencia de numeros naturales que acabe en -1: ");
    while(aux != -1)
    {
        scanf("%d", &aux);
        aux_1 = aux_1   aux;
    }
    printf("\nLa suma es: %d\n", aux_1);
}

I don't know how to solve it in a way that it doesn't add -1 in the final result

CodePudding user response:

Like this? If you first read, then check as the loop condition, then add and read again in the loop:

int main(){
    int aux=0, aux_1=0;
    printf("Escriba una secuencia de numeros naturales que acabe en -1: ");
    scanf("%d", &aux);
    while(aux != -1) {
        aux_1 = aux_1   aux;
        scanf("%d", &aux);
    }
    printf("\nLa suma es: %d\n", aux_1);
}

This way the -1 will not be added at the end.

EDIT: to answer your question in the comments.

#include <stdio.h>

int main(){
    int aux=0, aux_1=0;
    printf("Escriba una secuencia de numeros naturales que acabe en -1: ");
    do {
        scanf("%d", &aux);
        if (aux != -1) aux_1  = aux;
    }
    while(aux != -1);
    printf("\nLa suma es: %d\n", aux_1);
}

CodePudding user response:

#include <stdio.h>

int main(){
    int aux=0, aux_1=0;
    printf("Escriba una secuencia de numeros naturales que acabe en -1: ");
    while(1){
        scanf("%d", &aux);
        if (aux == -1){
         break;
         }
        else
        aux_1  = aux;
    }
    printf("\nLa suma es: %d\n", aux_1);
}

CodePudding user response:

#include <stdio.h>
#include <conio.h>

void main(){
    int n, sum=0;
    printf("Enter the sequence of numbers");
    while(n){
        scanf("%d", &n);
        if (n == -1){
         break;
         }
        else
        sum = sum n;
        
    }
    printf("\n the sum is %d\n", sum);
}
  • Related