Home > Enterprise >  Revert a variable into its original value
Revert a variable into its original value

Time:11-24

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?

CodePudding user response:

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;

CodePudding user response:

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.

CodePudding user response:

#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;
}

CodePudding user response:

    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;
}
  •  Tags:  
  • c
  • Related