How to add a Pause Function to Display Output? - c

I'm fairly beginning in C, and was working on an assignment that asks me to take user inputs between -50 and 100 and then calculate various characteristics of the numbers entered such as average, even/odd, etc. (the program will stop once -999 is entered). I am also supposed to have the program Pause and display the output, and once the user presses any key, the screen will clear and another number will be entered by the user.
Everything else is functioning properly, and the code so far looks like:
#include <stdio.h>
#include <ctype.h>
int main()
{
//used for math
int i = 0;
float num[100], sum = 0.0, average;
//user input number
float x = 0.0;
//used to determine minimum and maximum numbers
unsigned int min, max, buf;
//used for determining prime number
int flag;
//for pause button
char ch;
while (1) {
printf("%d. Enter number: ", i + 1);
scanf("%f", &x);
//establish exit number
if (x == -999)
break;
//make sure number is within range
if (x >= -50 && x <= 100)
{
num[i] = x;
sum += num[i];
i++;
//determin minimum and maximum
if (x >= buf)
{
max = x;
}
if (x <= buf)
{
min = x;
}
buf = x;
}
else
{
printf("invalid number, must enter between -50 and 100\n");
}
}
average = sum / i;
//determine if prime num
if (x / i == 0)
{
flag = 1;
}
//display output
printf("\n Average = %.2f", average);
printf("\n Sum = %.2lf", sum);
printf("\n Numbers entered = %d", i);
printf("\n The highest value entered : %u", max);
printf("\n The lowest value entered : %u", min);
if (x / 2 == 0)
printf("\n%.2f is even.", x);
else
printf("\n%.2f is odd.", x);
//determine prime number
if (flag == 0)
{
printf("\n%.2f is a prime number.", x);
}
if (flag == 1)
{
printf("\n%.2f is not a prime number.", x);
}
printf("\nThank you for using my program, have a nice day :)");
return 0;
}
The pause button is the only thing that is not functioning properly. Would there be anyone that would know the answer of the best way to achieve the described pause button function? Thanks :)
Edit: I don't have the same problem as the "How to Pause in C" question, as I can see the output once -999 is entered, I just need to see the output one the screen is paused.

You can use getchar(); to pause your system. Once the user presses any key it will keep going. For clearing the screen you will need the #include<conio.h> library so that you can use the clrscr();
Here is a function for you to use:
#include<stdio.h>
#include<conio.h>
void func() {
getchar(); // Pauses the system until user presses a key
clrscr(); // Clears the screen
}
You can just call the function for every time you want it to pause and clear the screen. Since getchar(); will pause the system, it won't pass to the clrscr(); unless the user presses a key.

Related

taking the avg in C program

#include <stdio.h>
int main(int argc, char** argv)
{
int n;
int numbers;
int i=0;
int sum=0;
double average;
printf("\nPlease Enter the elements one by one\n");
while(i<n)
{
scanf("%d",&numbers);
sum = sum +numbers;
i++;
}
average = sum/n;
printf("\nSum of the %d Numbers = %d",n, sum);
printf("\nAverage of the %d Numbers = %.2f",n, average);
return 0;
}
i get the output "exited, floating point exception"
im not sure how to fix it.
i found online to add before the while loop
printf("\nPlease Enter How many Number you want?\n");
scanf("%d",&n);
but i dont want that there
Hint: you want the user to be able to signal to your application that they finished entering the elements. So you'd start with n=0 and then increment it each time the user provides a new element, and exit the loop when the user does "something" that you can detect.
For starters, let's say that the user closes the input by pressing Ctrl-Z on Windows, or Ctrl-D on Unix. The input will fail with EOF then - scanf() won't return 1 anymore. So you can check for this:
#include <stdio.h>
int main(int argc, char** argv)
{
int n = 0;
int sum = 0;
printf("\nPlease Enter the elements one by one. ");
#ifdef _WIN32
printf("Press Ctrl-Z to finish.\n");
#else
printf("Press Ctrl-D to finish.\n");
#endif
for (;;)
{
int number;
int result = scanf("%d", &number);
if (result == 1) break;
sum = sum + number;
n ++;
}
double average = (double)sum / n;
printf("\nSum of %d number(s) = %d\n",n, sum);
printf("Average of %d number(s) = %.2f\n",n, average);
return 0;
}
But this also ends the input when anything non-numeric is entered. Due to how scanf() is designed, you need to do something else to skip invalid input - usually by consuming input character-by-character until an end of line is reached. Thus, the variant that would not stop with invalid input, but allow the user another chance, needs to differentiate between scanf() returning EOF vs it returning 0 (invalid input):
#include <stdio.h>
void skip_input_till_next_line(void)
{
for (;;) {
char c;
if (scanf("%c", &c) != 1) break;
if (c == '\n') break;
}
}
int main(int argc, char** argv)
{
int n = 0;
int sum = 0;
printf("\nPlease Enter the elements one by one. ");
#ifdef _WIN32
printf("Press Ctrl-Z to finish.\n");
#else
printf("Press Ctrl-D to finish.\n");
#endif
for (;;)
{
int number;
int result = scanf(" %d", &number);
if (result == EOF) break;
if (result != 1) {
// We've got something that is not a number
fprintf(stderr, "Invalid input. Please try again.\n");
skip_input_till_next_line();
continue;
}
sum = sum + number;
n ++;
}
double average = (double)sum / n;
printf("\nSum of %d number(s) = %d\n",n, sum);
printf("Average of %d number(s) = %.2f\n",n, average);
return 0;
}
As a learner I'd recommend you to think about the pseudo code rather than the actual code.
Answers above are really good. I just want to add few things:
As a programmer you've to teach the hardware what you want it to do. Think:
Have you told your program how many numbers it takes as input? Is it limited or unlimited?
How will your program knows when to stop taking inputs?
I hope you agree that (sum n)/n would throw an error if user
doesn't enter anything or only enters 0?
What will happen if User enters characters instead?
Another important thing is that you need to clearly specify why you don't want to do certain thing in your code? This might help us understand better what are the limitations.
If you think about these things before and ask questions you'll learn better. Community is here to help you.

write a program that will accept an integer value in the range of 5-95 and as a multiple of 5

Im a complete newbie in programming.
I've been instructed to write the program above in the title.
I'm here seeking help from everyone to help me understand and code better.
Can anyone tell me what is wrong with my code? i cant get it to exit the loop
more detailed information on the program:
You are asked to write a simple C program that will accept an integer value in the range
of 5-95 and as a multiple of 5 representing the number of cents to give to a customer in
their change. The program should calculate how many coins of each denomination and
display this to the user. Valid coin values are 50, 20, 10 and 5. Your solution (program
and algorithm) should be modular in nature.
/*This program acts as a coin changer that helps to provide
change user their changes in the highest amount.
*/
#include <stdio.h>
// Delcaration of functions
int coins(int fifty, int twenty, int ten, int five);
int main()
{
// Declare and initialize working storage
int fifty = 0;
int twenty = 0;
int ten = 0;
int five = 0;
int user_input = 0;
int counter = 3;
int coins(int fifty, int twenty, int ten, int five);
// Prompt user for input, prints, and loops for 3 attempts
while (counter > 0)
{
printf("\nPlease enter an amount within the range of 5 to 95\n");
printf("\nPlease enter the amount you wish to change: \n\n");
scanf("%d", &user_input);
if ((user_input < 5) || (user_input > 95))
{
printf("\nInvalid input\n");
printf("\nNumber of attemps: %d\n\n\n\n", counter);
}
counter--;
}
printf("\nYou have exceeded the number of attempts\n");
// Compute number of coins to be given
fifty = user_input / 50;
twenty = user_input / 20;
ten = user_input / 10;
five = user_input / 5;
if (fifty >= 1)
{
printf("\nNumber of fifty cent coins are: %d\n", fifty);
}
else if (twenty >= 1)
{
printf("\nNumber of twenty cent coins are: %d\n", twenty);
}
else if (ten >= 1)
{
printf("\number of ten cent coins are: %d\n", ten);
}
else if (five >= 1)
{
printf("\nNumber of five cent coins are: %d\n", five);
}
return 0;
}
Here is a program that does what you ask. This program could still be improved vastly.
#include <stdio.h>
// Delcaration of functions
int coinReturn(int coinSize, int value)
{
int tmp = 0;
while(value >= coinSize)
{
value-=coinSize;
tmp++;
}
printf("Number of %i cent coins are: %d\n", coinSize,tmp);
return value;
}
int main()
{
// Declare and initialize working storage
int user_input = 0;
int remainingValue;
// Prompt user for input, prints, and loops for 3 attempts
while (1)
{
printf("\nPlease enter an amount within the range of 5 to 95\n");
printf("\nPlease enter a multiple of 5\n");
printf("\nPlease enter the amount you wish to change: \n");
scanf("%d", &user_input);
if ( (user_input < 5 || user_input > 95) || (user_input % 5 != 0))
{
printf("\nInvalid input!\n");
}
else
{
break;
}
}
//Calculate and Print Output
remainingValue = coinReturn(50,user_input);
remainingValue = coinReturn(20,remainingValue);
remainingValue = coinReturn(10,remainingValue);
remainingValue = coinReturn(5,remainingValue);
return 0;
}
I would focus on a couple things if I were you and make sure I learned the concept. These are:
- Break Statements
- Function Declarations and function Definitions
- Modulo
- Flowcharting
This problem can be slightly tricky and flowcharting it when you start is your best bet.

Why does my program not add numbers until -1 is given?

The following code should prompt the user for prices and add that to a total. If the user inputs -1 the adding loop must terminate and the program should print a total and exit. But for some reason this is not happening.
#include <stdio.h>
int main()
{
int price;
int sum;
int exit;
do
{
printf(" Enter a price(-1 to exit)");
scanf("%d", & price);
sum = sum + price++;
printf("the sum of prices is % d ", sum);
}
while (exit != -1);
return 0;
}
Q: Why does my program not add numbers until -1 is given?
You should use if-else statement to resolve it. Like shown below:
while(price != -1)
{
printf(" \nEnter a price(-1 to exit)");
scanf("%d", &price);
if (price == -1)
{
break;
}
else{
sum = sum + price;
printf(" \ntotal sum till now is %d", sum);
}
}
You aren't assigning exit to anything. If you want the user to enter the string -1, the check if price is -1 and break from the loop. If you meant for the user to enter a character with a value of -1, then use fgetc(stdin), and check if the character is -1.
Also, to calculate the sum correctly, you shouldn't be incrementing price with sum = sum + price++;. If this was meant to circumvent the situation where price is -1 and you don't want to subtract from the sum, you should check if exit is -1 inside the loop, and use the break keyword.
It isn't the largest issue, but you should be formatting your code according to conventions (e.g. indenting properly, address-of-operator next to the identifier, etc).
Hello man look now in what is the problem u named a int exit right ?
But you only make exit only int varible and the memory is unfiltered so the computer get a memory from something else and its not a -1 you need to put the %d price in the wile
int price;
do
{
block_of_command
}
While(price!=-1);
Or
int exit;
int price
do
{
scanf("%d",&price);
exit=price;
}
while(exit!=-1);
i updated the code but i dont know how to add all the user inputted prices before exiting. here is my code.
#include<stdio.h>
int main()
{
int price;
int sum = 0;
while(price != -1)
{
printf(" Enter a price(-1 to exit)");
scanf("%d", & price);
if (price == -1)
{
sum = sum + price;
printf(" adds is %d", sum);
break;
}
}
return 0;
}

Receiving non-zero exit status when filling an array dynamically from user input

#include <stdio.h>
int main(void){
int inputNumber;
int counter=0;
int totalValue;
int arr[counter];
int avg;
puts("Please enter any number of positive whole numbers you would like to be averaged. Enter ' -1 ' when you are finished for your result.\n");
while(scanf("%d\n", &arr[counter])){
if(arr[counter] = -1){
break;
}
if(arr[counter] > 0){
totalValue += arr[counter];
++counter;
}
else if(arr[counter]<=0){
puts("Please enter a positive number.");
}
else{
}
}
avg = totalValue/counter;
printf("The average of your entered values is: %d", avg);
return 0;
}
I have attempted many things to try and stop it, and although this may come from a lack of knowledge is there really any way to do this other than creating an enormously large array?
I tried using a dynamic array with calloc() but i was met with the same errors. I am unsure what else is available as an option in this method.
The code is supposed to take the average of "n" user inputted values.
You do not need an array.
Quick & dirty but easier that you wanted to do
int number = 0;
int counter = 0;
int total = 0;
while (number != -1)
{
total += number;
++counter;
scanf("%d", &number);
}
printf("average = %d\n", total / (counter - 1) );

Writing a program to find the largest in a series of numbers.

I am very new to C. I am using A modern Approach to C programming by King 2nd Edition.
I am stuck on chapter 6. Question 1: Write a program that finds the largest in a series of numbers entered by the user. The program must prompt the user to enter the numbers one by one. When the user enters 0 or a negative number, the program must display the largest non negative number entered.
So far I have:
#include <stdio.h>
int main(void)
{
float a, max, b;
for (a == max; a != 0; a++) {
printf("Enter number:");
scanf("%f", &a);
}
printf("Largest non negative number: %f", max);
return 0;
}
I do not understand the last part of the question, which is how to see which non-negative number is the greatest at the end of user input of the loop.
max = a > a ???
Thanks for your help!
So you want to update max if a is greater than it each iteration thru the loop, like so:
#include <stdio.h>
int main(void)
{
float max = 0, a;
do{
printf("Enter number:");
/* the space in front of the %f causes scanf to skip
* any whitespace. We check the return value to see
* whether something was *actually* read before we
* continue.
*/
if(scanf(" %f", &a) == 1) {
if(a > max){
max = a;
}
}
/* We could have combined the two if's above like this */
/* if((scanf(" %f", &a) == 1) && (a > max)) {
* max = a;
* }
*/
}
while(a > 0);
printf("Largest non negative number: %f", max);
return 0;
}
Then you simply print max at the end.
A do while loop is a better choice here because it needs to run at least once.
#include<stdio.h>
int main()
{
float enter_num,proc=0;
for(;;)
{
printf("Enter the number:");
scanf("%f",&enter_num);
if(enter_num == 0)
{
break;
}
if(enter_num < 0)
{
proc>enter_num;
proc=enter_num;
}
if(proc < enter_num)
{
proc = enter_num;
}
}
printf("Largest number from the above is:%.1f",proc);
return 0;
}

Resources