Im trying to get it to stop but im not quite sure how to do that. Im just starting to learn it. I want it to stop when I type -99.
Any help would be greatly appreciated!
this is what I have:
#include <stdio.h>
#define SIZE 5
int main(void)
{
int hot=0, pleasant=0, cold=0;
int sum=0, i, temp;
double average;
for(i=0; i<SIZE; i++)
{
printf("Enter temperature %d> (-99 to stop)",i+1);
scanf("%d",&temp);
sum +=temp;
if(temp >= 85)
{
++hot;
}
else if(temp >= 60 && temp <= 84)
{
++pleasant;
}
else
{
++cold;
}
}
average = (double) sum/SIZE;
printf("The Collection of hot days is %d\n",hot);
printf("The Collection of pleasant days is %d\n",pleasant);
printf("The Collection of cold days is %d\n",cold);
printf("The Average temperature is %.2f\n",average);
return(0);
}
You simply need to break out of the loop:
if (temp == -99)
break;
But there are several other issues with your code, such as the averaging calculation will be wrong if you exit early. Here is a corrected version that also makes use of the other loop control word continue.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *buffer;
size_t buffer_len;
int hot=0, pleasant=0, cold=0;
int sum=0, i=0, temp;
double average;
while(1)
{
printf("Enter temperature %d> (-99 to stop)",i);
buffer = NULL;
getline(&buffer, &buffer_len, stdin);
if (buffer_len == 0 || sscanf(buffer, "%d\n",&temp) != 1)
{
if (buffer)
free(buffer);
printf("Invalid\n");
continue;
}
free(buffer);
if(temp == -99)
break;
sum +=temp;
++i;
if(temp >= 85)
{
++hot;
continue;
}
if(temp >= 60)
{
++pleasant;
continue;
}
++cold;
}
if (i == 0)
{
printf("No temperatures entered\n");
return -1;
}
average = (double)sum / i;
printf("The Collection of hot days is %d\n",hot);
printf("The Collection of pleasant days is %d\n",pleasant);
printf("The Collection of cold days is %d\n",cold);
printf("The Average temperature is %.2f\n",average);
return 0;
}
Related
The average which is the last output should display 60 but I got it wrong. What is the error here? Here is the temperature input 72, 46, 90, 20, 70 85, 60, 40, -1000.
The total hot days should display 2 but on the output I got 3.
#include <stdio.h>
int categorize_days(int temp);
int categorize_days(int temp){
if (temp >= 85){
return 1;
}
else if(temp >=60){
return 2;
}
else{
return 3;
}
}
int main(){
int i, temp, h, p,c, temp_ave=0, type_days;
double ave;
printf("Lets check the whether !\n");
printf("Keep entering the integer temperature, enter -1000 to quit\n\n");
printf("Temperature: ");
scanf("%d", &temp);
while(temp!= -1000){
for(i = 0; i<8; i++ ){
temp_ave =+ temp;
}
type_days = categorize_days(temp);
if( type_days == 1){
printf ("Day: h\n\n");
h++;
}
else if(type_days == 2){
printf ("Day: p\n\n");
p++;
}
else{
printf ("Day: c\n\n");
c++;
}
printf("Temperature: ");
scanf("%d", &temp);
}
printf("End\n\n");
ave = temp_ave/8;
printf("Total Hot days: %d \n", h);
printf("Total Pleasant days: %d \n", p);
printf("Total Cold days: %d \n", c);
printf("Average temperature for 8 days is %f", ave);
}
The first big mistake is here:
for(i = 0; i<8; i++ ){
temp_ave =+ temp; // You are not adding temp to temp_ave, to add you should
} // write temp_ave += temp;
// Anyway this won't help you, cause you are trying to add the same number 8 times.
// So therefore it will give you wrong average, when you are calculating it.
I think this is what you wanted to do.
#include <stdio.h>
int categorize_days(int temp) {
return (temp >= 85 ? 1 : (temp >= 60 ? 2 : 3));
}
int main() {
int temp = 0, h = 0, p = 0, c = 0, cnt = -1;
double ave = 0;
printf("Lets check the whether !\n");
printf("Keep entering the integer temperature, enter -1000 to quit\n\n");
while (temp != -1000) {
ave += temp;
cnt ++;
printf("Temperature: ");
scanf("%d", &temp);
int type_days = categorize_days(temp);
if (type_days == 1) {
printf ("Day: h\n\n");
h++;
}
else if(type_days == 2) {
printf ("Day: p\n\n");
p++;
}
else {
printf ("Day: c\n\n");
c++;
}
}
printf ("End\n\n");
printf ("Total Hot days: %d \n", h);
printf ("Total Pleasant days: %d \n", p);
printf ("Total Cold days: %d \n", c);
printf ("Average temperature for 8 days is %f", ave / cnt);
}
Don't use magic numbers in the code, following and updating becomes tedious. Use #define macros as necessary.
#define HOT_CUTOFF 85 // Fahrenheit
#define COLD_CUTOFF 60 // Fahrenheit
#define INPUT_GUARD -1000
Make use of enum to list out day-types:
enum {
eHotDay = 1,
eColdDay = 2,
eCozyDay = 3
} eDayType;
Then your day_type() would change to :
int day_type (const int temp) {
if (temp >= HOT_CUTOFF)
return eHotDay;
else if (temp <= COLD_CUTOFF) // should be less than or equal to
return eColdDay;
else
return eCozyDay;
}
Always initialise variables before usage. h, p & c are being used without initialisation. Also, temp_ave is misleading name for keeping total.
int i, temp, h, p,c, temp_ave=0, type_days;
Why limit only to 8 inputs when you've -1000 as guard?
Simplified:
#include <stdio.h>
#define HOT_CUTOFF 85 // Fahrenheit
#define COLD_CUTOFF 60 // Fahrenheit
enum {
eHotDay = 1,
eColdDay = 2,
eCozyDay = 3
} eDayType;
//int categorize_days (int temp); // redundant as you're defining the function before usage
//int categorize_days (int temp) {
int day_type (const int temp) {
if (temp >= HOT_CUTOFF)
return eHotDay;
else if (temp <= COLD_CUTOFF) // should be less than or equal to
return eColdDay;
else
return eCozyDay;
}
int main() {
printf ("Keep entering the integer temperature, enter -1000 to quit\n\n");
int total = 0;
int count = 0;
int hot = 0, cold = 0, cozy = 0;
while (1) {
int temp;
if (1 != scanf ("%d", &temp)) {
printf ("ERROR: Invalid input\n");
return 1;
}
if (INPUT_GUARD == temp) break;
total += temp;
++count;
switch (day_type(temp)) {
case eHotDay : ++hot; break;
case eColdDay : ++cold; break;
case eCozyDay : ++cozy; break;
}
}
double avgTemp = 0.0;
if (count)
avgTemp = (double)total / count;
printf ("End\n\n");
printf ("Total Hot days: %d \n", hot);
printf ("Total Pleasant days: %d \n", cozy);
printf ("Total Cold days: %d \n", cold);
printf ("Average temperature for 8 days is %.2lf\n", avgTemp);
return 0;
}
The average which is the last output should display 60 but I got it wrong.
This loop is a mess. Same as temp_ave = +temp;, same as temp_ave = temp;.
for (i = 0; i<8; i++) {
temp_ave =+ temp; // ????????
}
Instead:
temp_ave += temp; // Note +=
temp_ave/8 in an int division. Instead, perform the division per the type of ave avoiding casts.
// ave = temp_ave/8;
ave = temp_ave;
ave /= 8; // Division done per wider of type of `ave` and `int` constant `8`.
The total hot days should display 2 but on the output I got 3.
Enable all warnings.
Initialize h, p, c. #Weather Vane
I need to make a program that will perform the following task:
Enter N natural numbers. Complete the input with 0. Output the number
of the maximal number.
I have already done this, and you can see the code below:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main(void) {
int i = 0, num, max_place = -1;
int max = -2147483647;
printf("Start enter numbers, bruh (please end input with 0):\n");
scanf("%d", &num);
while (num != 0) {
if (num >= max) {
max = num;
max_place = i;
}
i++;
scanf("%d", &num);
}
if (max_place == -1) printf("Numbers were not entered");
else printf("\nMax number was on %d place, bruh", max_place + 1);
return 0;
}
The teacher then made the task more difficult – the program needs to print the maximum number and the next maximum after it of the entered numbers.
How can I do it?
If you can use arrays and sort use that way. if not, this is in your code
int main(void) {
int i = 0, num, max_place = -1, second_max_place = -1;
int max = -2147483647;
int second_max = -2147483647;
printf("Start enter numbers, bruh (please end input with 0):\n");
scanf("%d", &num);
while (num != 0) {
if (num == 0) break;
if (num >= max) {
second_max = max;
second_max_place = max_place;
max = num;
max_place = i;
}
if(num < max && num >= second_max){
second_max = num;
second_max_place = i;
}
i++;
scanf("%d", &num);
}
if (max_place == -1) printf("Numbers were not entered");
else{
printf("\nMax number was on %d place, bruh", max_place + 1);
printf("\nSecond Max number was on %d place, bruh", second_max_place + 1);
}
return 0;
}
Hi im fairly new in programming and started with C language and now im stuck with loops.
The problem is that I try to write a program that has to get an input value of 10 INT numbers that are greater than 20, and after that the program has to determine which of the numbers is the maximum and which is minimum. at the end it has to calculate the average of all numbers.
So now I managed to get only the average calculation to work correctly, and the main problem is the max/min values.
#include<stdio.h>
void main()
{
//Variables
int num, i = 1, cnt = 0, sum = 0, max = 0, min = 0;
float average;
printf("Enter 10 int numbers greater than 20:\n");
//Input check
while (i <= 10)
{
printf("\n%d) ", i);
scanf("%d", &num);
max = num;
min = num;
if (num <= 20)
{
printf("Wrong number! enter an integer greater than 20:\n");
continue;
}
i++;
sum += num;
cnt++;
if (num > max) {
max = num;
}
if (num < min) {
min = num;
}
}
//Average calculation and output
average = sum / (float)cnt;
printf("The maximum number is: %d\n", max);
printf("The minimum number is: %d\n", min);
printf("The average of all numbers is: %.2f\n", average);
}
Here is a quick check game in c that asks for few numbers and then when you enter 0 it shows you the lowest and highest number in the array (number collected)
int main(){
int a, max = 0, min;
char answer;
while(answer != 'n')
{
for(int i = 0; i < 100; i++){
printf("Enter Number:");
if (scanf("%d", &a) == 1)
{
if(a == 0) //check if the input value is 0 then break the loop
break;
else
{
if(a > max)
max = a;
if(a < min)
min = a;
}
}
}
printf("lowest: %d, highest: %d", min, max);
printf("\nWould you like to start over? (j/n): ");
scanf("%s", &answer);
max = 0;
//min=0;
if(answer == 'n')
break;
}
return 0;
}
I have created a code that writes out the sum of all even numbers.
But every time it loops the sum of the last run is saved and added in the sum of the new run. how do i make it have a new loop?
sorry for my bad english, and thx in advance
int main()
{
int number = 0;
int sum = 0;
printf("Welcome to\"Sum Evens\"!");
do
{
printf("\ninput a number: ");
scanf(" %d", &number);
if (number == 0)
{
printf("Goodbye, have a nice day!\n");
break;
}
printf("\nSum:");
if (number % 2 != 0)
{
number -= 1;
}
for (int i = 0; i <= number; i += 2)
{
printf(" %d ", i);
if (i != number)
{
printf("+");
}
sum += i;
}
printf("= %d\n", sum);
} while (number != 0);
system("pause");
return 0;
}
Watch these sort of problems melt away if you declare your variables as close to their first use as possible.
In your case, move int sum = 0; to just before the for loop.
Here is the average program I created.
#include <stdio.h>
#include <stdlib.h>
int main()
{
float f1,f2,f3;
/* Program to calculate averages. */
/*Asks for the numbers.*/
printf(" Please enter three numbers.\n");
printf ("\t" "First number please.\n");
scanf("%f", &f1);
printf ("\t" "Second number please.\n");
scanf ("%f", &f2);
printf("\t" "Third number please.\n");
scanf("%f", &f3);
/* Now it averages it.*/
printf(" Thank you, wait one.\n");
printf(" Excellent, your sum is.\n");
printf("%f""\n", f1+f2+f3);
printf("Your average of the sum is now!!!!\n");
printf("%f", (f1+f2+f3)/3);
return 0;
}
Now would I turn this into a do-while? Or an if else?
If you want to repeat the whole entry and averaging process, you can wrap a loop around the code:
#include <stdio.h>
int main(void)
{
float f1,f2,f3;
while (1)
{
printf("Please enter three numbers.\n");
printf("\tFirst number please.\n");
if (scanf("%f", &f1) != 1)
break;
printf("\tSecond number please.\n");
if (scanf("%f", &f2) != 1)
break;
printf("\tThird number please.\n");
if (scanf("%f", &f3) != 1)
break;
printf("Your sum is %f\n", f1+f2+f3);
printf("Your average is %f\n", (f1+f2+f3)/3);
}
return 0;
}
Note that this code checks the return value from scanf() each time it is used, breaking the loop if there's a problem. There's no need for string concatenation, and a single printf() can certainly print a string and a value.
That's a simple first stage; there are more elaborate techniques that could be used. For example, you could create a function to prompt for and read the number:
#include <stdio.h>
static int prompt_and_read(const char *prompt, float *value)
{
printf("%s", prompt);
if (scanf("%f", value) != 1)
return -1;
return 0;
}
int main(void)
{
float f1,f2,f3;
while (printf("Please enter three numbers.\n") > 0 &&
prompt_and_read("\tFirst number please.\n", &f1) == 0 &&
prompt_and_read("\tSecond number please.\n", &f2) == 0 &&
prompt_and_read("\tThird number please.\n", &f3) == 0)
{
printf("Your sum is %f\n", f1+f2+f3);
printf("Your average is %f\n", (f1+f2+f3)/3);
}
return 0;
}
If you want to get away from a fixed set of three values, then you can iterate until you encounter EOF or an error:
#include <stdio.h>
static int prompt_and_read(const char *prompt, float *value)
{
printf("%s", prompt);
if (scanf("%f", value) != 1)
return -1;
return 0;
}
int main(void)
{
float value;
float sum = 0.0;
int num = 0;
printf("Please enter numbers.\n");
while (prompt_and_read("\tNext number please.\n", &value) == 0)
{
sum += value;
num++;
}
if (num > 0)
{
printf("You entered %d numbers\n", num);
printf("Your sum is %f\n", sum);
printf("Your average is %f\n", sum / num);
}
return 0;
}
You might also decide to replace the newline at the ends of the prompt strings with a space so that the value is typed on the same line as the prompt.
If you want to check whether to repeat the calculation, you can use a minor variant on the first or second versions of the code:
#include <stdio.h>
static int prompt_and_read(const char *prompt, float *value)
{
printf("%s", prompt);
if (scanf("%f", value) != 1)
return -1;
return 0;
}
static int prompt_continue(const char *prompt)
{
printf("%s", prompt);
char answer[2];
if (scanf("%1s", answer) != 1)
return 0;
if (answer[0] == 'y' || answer[0] == 'Y')
{
int c;
while ((c = getchar()) != EOF && c != '\n') // Gobble to newline
;
return 1;
}
return 0;
}
int main(void)
{
float f1,f2,f3;
while (printf("Please enter three numbers.\n") > 0 &&
prompt_and_read("\tFirst number please.\n", &f1) == 0 &&
prompt_and_read("\tSecond number please.\n", &f2) == 0 &&
prompt_and_read("\tThird number please.\n", &f3) == 0)
{
printf("Your sum is %f\n", f1+f2+f3);
printf("Your average is %f\n", (f1+f2+f3)/3);
if (prompt_continue("Do you want to try again?") == 0)
break;
}
return 0;
}
You can do this:
int main()
{
float number, sum=0.0f;
int index=0;
do
{
printf ("\t" "Enter number please.\n"); //Asking for a number from user
scanf("%f", &number); //Getting a number from a user
sum+=number; //Add number entered to the sum
i++;
} while (i < 3);
printf("Excellent, your average is %f\n", sum/3);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main()
{
float f1,f2,f3;
char c='Y';
/* Program to calculate averages. */
/*Asks for the numbers.*/
do
{
printf(" Please enter three numbers.\n");
printf ("\t" "First number please.\n");
scanf("%f", &f1);
printf ("\t" "Second number please.\n");
scanf ("%f", &f2);
printf("\t" "Third number please.\n");
scanf("%f", &f3);
/* Now it averages it.*/
printf(" Thank you, wait one.\n");
printf(" Excellent, your sum is.\n");
printf("%f""\n", f1+f2+f3);
printf("Your average of the sum is now!!!!\n");
printf("%f", (f1+f2+f3)/3);
printf ("Do you wana continue [Y/N]...\n");
scanf("%c", &c);
}while(c!='N'&&c!='n');
return 0;
}