twice the sum of the integers plus 7 is 31--good-byeI'm trying to understand programming in C. How do you write a program when you input integers?
Heres a simple program that does what you want. It will show you how to ask for user input and then use those values in a simple formula.
Take note of how the formula is structured with the position of the brackets ensuring that the 2x multiplication occurs before the 7+ addition.
void main (void)
{
int input_1=0;
int input_2=0;
int input_3=0;
int total=0;
printf(';Please enter 3 Integers\n';);
printf(';Please enter Integer 1: ';);
scanf(';%d';,%26amp;input_1);
printf(';Please enter Integer 2: ';);
scanf(';%d';,%26amp;input_2);
printf(';Please enter Integer 3: ';);
scanf(';%d';,%26amp;input_3);
/* add the 3 integers together, multiply by 2, add 7 */
total = 2*(input_1 + input_2 + input_3) + 7;
/* print out the total to show its working */
printf (';Twice the Sum of %d, %d, %d plus 7 = %d\n';,
input_1, input_2, input_3, total);
}I'm trying to understand programming in C. How do you write a program when you input integers?
Your question is a bit unclear. If you are asking about how to input data from the user, I can help you with that. The rest of the problem is up to you.
IO is done with printf and scanf (the f is for formatted). Wikipedia has detailed descriptions of the functions, so I don't have to repeat them here.
both printf and scanf take a format string and a list of variables. Printf outputs the format string and any variables. Scanf reads data in and stores it in the variables.
for both routines, %d stand for integer. for example:
int n1, n2;
int temp = 72;
printf(';The temperature is: %d\n';, temp);
// prints The temperature is: 72
// We can use printf without any variables if we wish
printf(';Please enter the first number\n';);
// scanf takes a format string and the address of the variable
// %d means read the input as an integer
scanf(';%d';, %26amp;n1);
printf(';Please enter the second number\n';);
scanf(';%d';, %26amp;n2);
printf(';the sum is %d\n';, n1 + n2)
c programming code samples for beginners
ReplyDeletec example code calculate Area of a Polygon