26.5k views
1 vote
Write a program in C thats read an integer value for x andsums upto 2*x.

1 Answer

4 votes

Answer:

#include<stdio.h>

//main function

int main(){

//initialization of variable

int temp_sum=0;

int x,i;

//display the message

printf("Enter the number:");

scanf("%d",&x);//read the number and store in the variable

//for loop which run 2*num_1 times

for(i=x;i<=2*x;i++){

temp_sum = temp_sum + i; //adding

}

//display the output

printf("The sum is: %d",temp_sum);

return 0;

}

Step-by-step explanation:

Include the library stdio.h for using input/output function in c programming.

Create the main function and declare the variables.

display the message on the screen by output function printf().

read the value enter by the user and store in the variable using scanf().

Then, it takes the for loop statement which runs again and again until the condition not false.

the for loop start from value x enter by the user and the loop goes running 2 * x times.

in the for loop, add the number continuously and after the loop terminate.

the output print on the screen.

Lets dry run the code:

suppose initially, temp_sum=0, x = 4, i = 4.

the for loop start from 4, it check the condition 4 <= 8, condition True.

then,

temp_sum = 0 + 4 which is 4 assign to temp_sum.

then, loop increment the value of i and it becomes 5.

This process continues until the condition not false.

after that print the output store in the temp_sum.

User Vishal Verma
by
7.5k points