Foks
Foks

Reputation: 13

Revert a variable into its original value

The code runs perfectly except for the output for "start". Im running a code that when inputs two numbers, it will add every number in between those two numbers. Example: i select 1 and 7 so 1+2+3+4+5+6+7.

int main() 
{
    int start, end;
    int sum = 0;
    int i;
    start = 0;
    printf("Start integer: ");
    scanf("%d", &start);
    printf("\nEnd integer: ");
    scanf("%d", &end);

    while (1) {
        while(start <= end){
            sum += start;
            ++start;
        }
        break;
    }

    printf("The sum between %d and %d is %d\n", start, end, sum);
    return 0;
}

This is the output

Anyone knows how to get the 8 to a 1?

Upvotes: 1

Views: 310

Answers (4)

user14793387
user14793387

Reputation:

    int main()
{
int start,end;
int sum = 0;
int i; //can be deleted, because its unused
start=0; //can be deleted, because you override it with scanf()
printf("Start integer: ");
scanf("%d", &start);
printf("\nEnd integer: ");
scanf("%d", &end);
int org_start = start; //you need to save the startvalue to print it later
while (1){ //Can be deleted, the next while is enough

    while(start<=end){
        sum += start;
        ++start;
    }
        break;
    }
    

   //you need to print the org_start instead of the normal start
   printf("The sum between %d and %d is %d\n", org_start, end, sum);
return 0;
}

Upvotes: 0

Edmund
Edmund

Reputation: 352

#include <stdio.h>

int main() {
    int start, end, counter;
    int sum = 0;

    printf("Start integer: ");
    scanf("%d", &start);
    printf("\nEnd integer: ");
    scanf("%d", &end);

    counter = start;

    while(counter <= end) {
        sum += counter;
        counter++;
    }

    printf("The sum between %d and %d is %d\n", start, end, sum);

    return 0;
}

Upvotes: 0

Andrew Cina
Andrew Cina

Reputation: 154

You increment start with ++start; so when you try to print it's now some larger value.

If you use a for loop like this you can avoid the problem as well as not have 2 while loops! The first one while(1) is redundant.

for (int i = start; i <= end; i++)
    sum += i;

Upvotes: 1

Omid CompSCI
Omid CompSCI

Reputation: 1902

int main()
{
int start,end, orig_start;
int sum = 0;
int i;
start=0;
printf("Start integer: ");
scanf("%d", &start);
orig_start = start;
printf("\nEnd integer: ");
scanf("%d", &end);

while (1){

    while(start<=end){
        sum += start;
        ++start;
    }
        break;
    }

   printf("The sum between %d and %d is %d\n", orig_start, end, sum);
return 0;
}

Just store the original user input into a temporary variable and use that in your terminal output.

Upvotes: 0

Related Questions