Skip to content

Instantly share code, notes, and snippets.

@rszewczyk
Last active November 9, 2017 22:18
Show Gist options
  • Save rszewczyk/37f0c9f60aa33f7ec88649f1e0691960 to your computer and use it in GitHub Desktop.
Save rszewczyk/37f0c9f60aa33f7ec88649f1e0691960 to your computer and use it in GitHub Desktop.
CMSC 104 Class 17

Class 17 (11/2/2017) Assignment

Create a file called loops2.c.

Part 1.

Write a program that prompts the user to enter a non negative integer. If the user enters a negative value it should inform the user that the number is not negative and re prompt the user to enter a non negative integer. The program should continue to prompt the user until they enter a valid value and then the program should exit.

You can assume that the user correctly enters an integer - i.e. you don't need to check that it's actually an integer.

Part 2.

Modify the above program as follows. After the user enters a non negative integer, print the result of calculating the factorial of that number.

After you have completed part 2. Submit the assignment to me on Slack. If there is still time in class, and you haven't already done so, complete parts 5 and 6 from the class 16 assignment. If you complete that, modify today's assignment so that it checks that the number the user entered is also an integer (i.e. if they enter a decimal number, reprompt).

#include <stdio.h>
int main()
{
int valueFromUser = -1;
while (valueFromUser < 0)
{
printf("Enter a non negative integer: ");
scanf("%d", &valueFromUser);
if (valueFromUser < 0)
{
printf("%d is negative\n", valueFromUser);
}
}
int cumulativeValue = 1;
if (valueFromUser != 0)
{
int currentValue = 1;
while (currentValue <= valueFromUser)
{
cumulativeValue = cumulativeValue * currentValue;
currentValue = currentValue + 1;
}
}
printf("The factorial of %d is %d\n", valueFromUser, cumulativeValue);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment