Write a C program that prompts the user for an integer greater than zero. If the user enters
an negative value, inform them and prompt them again. After the user has entered
the correct value calculate the sum of all integers that are less than or equal to
the value entered by the user.
Solve this step by step by getting one piece at a time to work.
As always, the first step is to create the basic shell of a C program:
#include <stdio.h>
int main()
{
return 0;
}
Next, prompt the user for a value, get the value and print a message if the value is
invalid:
#include <stdio.h>
int main()
{
int valueFromUser = 0;
printf("Type an integer that is greater than 0 and press return: ");
scanf("%d", &valueFromUser);
if (valueFromUser < 1)
{
printf("%d is not greater than 0\n", valueFromUser);
}
return 0;
}
Now, handle reprompting the user if the enter an invalid value
#include <stdio.h>
int main()
{
int valueFromUser = 0;
while (valueFromUser < 1)
{
printf("Type an integer that is greater than 0 and press return: ");
scanf("%d", &valueFromUser);
if (valueFromUser < 1)
{
printf("%d is not greater than 0\n", valueFromUser);
}
}
return 0;
}
Now, use the value from the user to set up the next loop that will produce
successive integers up to and including the user's value. For now just
print the value so that you know it's correct:
#include <stdio.h>
int main()
{
int valueFromUser = 0;
while (valueFromUser < 1)
{
printf("Type an integer that is greater than 0 and press return: ");
scanf("%d", &valueFromUser);
if (valueFromUser < 1)
{
printf("%d is not greater than 0\n", valueFromUser);
}
}
int currentValue = 1;
while (currentValue <= valueFromUser)
{
printf("%d\n", currentValue);
currentValue = currentValue + 1;
}
return 0;
}
Now, add code to keep track of the cumulative value and print it when finished.
#include <stdio.h>
int main()
{
int valueFromUser = 0;
while (valueFromUser < 1)
{
printf("Type an integer that is greater than 0 and press return: ");
scanf("%d", &valueFromUser);
if (valueFromUser < 1)
{
printf("%d is not greater than 0\n", valueFromUser);
}
}
int currentValue = 1;
int cumulativeValue = 0;
while (currentValue <= valueFromUser)
{
cumulativeValue = cumulativeValue + currentValue;
currentValue = currentValue + 1;
}
printf("The sum of positive integers up to an including %d is %d\n", valueFromUser, cumulativeValue);
return 0;
}