The output for average is not correct - c

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

Related

Incorrect calculations of averages

I have this super simple code for calculating averages of given even and odd numbers, until the user gives 0. (I would use for loop but we can't).
I'm having a really strange problem with program rounding results like 25/2 is 2.00000. Sorry if this question is stupid but I just can't find a problem.
What am I doing completely wrong?
#include <stdio.h>
#include <stdlib.h>
void funkcja()
{
int sumaNiep = 0;
int sumaPa = 0;
int userInput = 1;
int i = 0;
while(userInput != 0)
{
//wprow zmiennej
printf("%d. Podaj calkowita liczbe: ", i+1);
scanf("%d", &userInput);
//jesli parzysta
if (userInput % 2 == 0)
{
sumaPa += userInput;
} else {
sumaNiep += userInput;
}
i++;
}
double sredniaNiep = sumaNiep/(i-1);
double sredniaPa = sumaPa/(i-1);
printf("\nsrednia parzysta %d / %d : %lf", sumaPa, i, sredniaPa);
printf("\nsrednia parzysta %d / %d : %lf", sumaNiep, i, sredniaNiep);
}
int main()
{
funkcja();
}
The problem is that you do an integer division at the end.
You should break out of the loop if the user enters 0 and make at least one operand a double when you do the division. You also need to count the number of evens and odds:
#include <stdio.h>
#include <stdlib.h>
void funkcja() {
int sumaNiep = 0;
int sumaPa = 0;
int userInput = 1;
int iPa = 0;
int iNiep = 0;
int i = 0;
while(1) {
printf("%d. Podaj calkowita liczbe: ", ++i);
if(scanf(" %d", &userInput) != 1 || userInput == 0) break; // break out
// jesli parzysta
if(userInput % 2 == 0) {
sumaPa += userInput;
++iPa; // count evens
} else {
sumaNiep += userInput;
++iNiep; // count odds
}
}
if(iPa) { // avoid div by zero
double sredniaPa = (double)sumaPa / iPa; // double div
printf("srednia parzysta %d / %d : %lf\n", sumaPa, iPa, sredniaPa);
}
if(iNiep) { // avoid div by zero
double sredniaNiep = (double)sumaNiep / iNiep; // double div
printf("srednia parzysta %d / %d : %lf\n", sumaNiep, iNiep, sredniaNiep);
}
}
The problem was I divided by the number of all digits (odd and even) to calculate both averages. Here is improved code:
#include <stdio.h>
#include <stdlib.h>
void funkcja()
{
int sumaNiep = 0;
int sumaPa = 0;
int userInput = 1;
int i_p = 0, i_np = 0;
while(userInput != 0)
{
//wprow zmiennej
printf("%d. Podaj calkowita liczbe: ", i_p+i_np+1);
scanf("%d", &userInput);
//jesli parzysta
if (userInput % 2 == 0)
{
sumaPa += userInput;
if (userInput != 0)
{
i_p++;
}
} else {
sumaNiep += userInput;
i_np++;
}
}
if (i_np != 0)
{
double sredniaNiep = sumaNiep/(i_np);
printf("\nSrednia nieparzysta %d / %d : %lf", sumaNiep, i_np, sredniaNiep);
}
if (i_p != 0)
{
double sredniaPa = sumaPa/(i_p);
printf("\nSrednia parzysta %d / %d : %lf", sumaPa, i_p, sredniaPa);
}
}
int main()
{
funkcja();
}

Average score facing some technical issues

I have followed everything in the book, yet my average score fails me, every single time. I have debugged my program multiple times, in vain.
My minimal executable code:
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#define MAX_TESTS 5
#define MAXQUESTION 10000
bool myread(const char * format, void * address) {
char buffer[1024];
fgets(buffer, sizeof buffer, stdin);
return sscanf(buffer, format, address) == 1;
}
struct struc {
int a;
int b;
int c;
int add;
int grade;
};
int sj(int n) {
int t;
t = rand() % n;
return t;
}
void ctm_i(struct struc * t) {
{
t -> a = sj(101);
t -> c = sj(4);
if (t -> c == 1) {
t -> b = sj(101 - (t -> a));
t -> add = (t -> a) + (t -> b);
} else {
t -> b = sj((t -> a) + 1);
t -> add = (t -> a) - (t -> b);
}
t -> grade = 0;
}
}
void tcm_i(struct struc * t, int n) {
int ad;
printf(" ***********************************************************************"
"*********\n");
printf(" ......................................................................."
".........\n");
printf(" Question %d\n\n", n + 1);
printf(" You have 3 attempts for this question\n\n");
if (t -> c == 1)
printf(" %d+%d= ", t -> a, t -> b);
else
printf(" %d-%d= ", t -> a, t -> b);
myread(" %d", & ad);
if (ad == t -> add)
{
t -> grade = 10;
printf(" You earned 10 marks\n\n");
} else {
printf("\n Incorrect, you have 2 attempts remaining\n\n");
printf(" ");
myread(" %d", & ad);
if (ad == t -> add)
{
t -> grade = 7;
printf(" You earned 7 marks\n\n");
} else {
printf("\n Incorrect, you have 1 attempt remaining\n\n");
printf(" ");
myread(" %d", & ad);
if (ad == t -> add)
{
t -> grade = 5;
printf(" You earned 5 marks\n\n");
} else {
t -> grade = 0;
printf("\n Failure, 0 mark\n\n");
printf("\n The correct answer is %d\n\n", t -> add);
}
}
}
printf(" ......................................................................."
".........\n");
printf(" ***********************************************************************"
"*********\n");
}
void quiz(char name[]) {
int rounds = 0;
int highest = 0;
int lowest = INT_MAX;
float allScore = 0;
float avg = 0.0;
int i, j, g = 0;
struct struc test[MAX_TESTS];
srand((unsigned) time(NULL));
for (;;) {
rounds++;
for (i = 0; i < MAX_TESTS; i++) // generate all questions
{
ctm_i( & test[i]);
for (j = 0; j < i; j++)
if (test[i].a == test[j].a && test[i].b == test[j].b && test[i].c == test[j].c)
//if question is already present
ctm_i( & test[i]); //then re-generate
}
printf("\n Are you ready? Press Enter key to continue. ");
myread("", NULL);
for (i = 1; i <= 5; i++) {
printf(" *******************************************************************"
"**"
"***********\n");
printf(" ..................................................................."
".."
"...........\n");
}
// Take quiz
for (i = 0; i < MAX_TESTS; i++)
tcm_i( & test[i], i);
printf(" End\n\n");
bool done = false;
bool unsure = true;
bool showS = true;
while (unsure) {
unsure = false;
puts("\n");
if (showS) {
puts(" Enter 'S' to show results");
}
puts(" Enter 'P' to play another round");
puts(" Enter 'R' to return to main menu");
char choice;
printf(" ");
myread(" %c", & choice);
printf("\n");
if (choice == 'r' || choice == 'R') {
done = true;
} else {
///////////////////////// Changes /////////////
g = 0;
// calculate total score for current round
for (i = 0; i < MAX_TESTS; i++) {
g += test[i].grade; //add score of each question
}
allScore += g; //add current round's score to total
avg = allScore / rounds; //average of all rounds
if (g > highest) {
highest = g;
}
if (g < lowest) {
lowest = g;
}
if (choice == 'S' || choice == 's') {
showS = false;
if (rounds == 1) {
printf(" Final score: %d/100\n", g); //display round score
printf(" ****** Player: %s ******\n", name);
} else {
printf(" Round %d score: %d/100\n", rounds, g); //display round score
printf(" Highest score: %d/100\n", highest);
printf(" Lowest score : %d/100\n", lowest);
printf(" Average score: %f/100\n", avg);
printf(" ****** Player: %s ******\n", name);
}
unsure = true;
} else if (choice == 'P' || choice == 'p') {
/// nothing to be done here
//we will display next test
} else {
puts(" Invalid input!");
unsure = true;
}
////////////////////////////////////
}
}
if (done)
break;
}
}
int main() {
char i1 = '1';
char name[25]; // ig;
printf("\n Welcome");
printf("\n");
while (i1 != 0) {
printf("\n");
//printf(" **********************Welcome %s! *********************\n", name);
printf(" ************************ Main Menu of Maths Quiz ***************************\n");
printf(" * 1.Enter Quiz *\n");
printf(" * 2.Quit *\n");
printf(" ****************************************************************************\n");
printf(" Please choose one from 1-2:\n");
printf(" ");
myread(" %c", & i1);
switch (i1) {
case '1':
printf("\n Enter Quiz:\n");
quiz(name); // calling quiz function defined in file "maincode.c"
break;
case '2':
printf(" Quit.\n\n");
}
}
return 0;
}
Hope that fulfilled the definition of an MRE.
So I have snipped off some bombastic lines, and the ones left are the important ones, I think.
The problem is in your function quiz, and in particular in the while (unsure) loop. In this loop, you add the most recent score to the running total:
allScore += g; //add current round's score to total
This should happen once per round played. But if the user inputs "S" or something invalid, your program sets
unsure = true;
which means the loop will run again, before the next round is played. It then adds the most recent score a second time to the grand total.
The most logical solution would be to move all the calculations of totals, maximum, minimum, average out of the while-loop. The loop serves a different purpose: it is for user interaction and reporting, not for processing results.
possible chance of multiple avg calculation for same round again. Keep flag to track accounting of score, so we will not do the same more than once till the game is not played again.
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#define MAX_TESTS 5
#define MAXQUESTION 10000
bool myread(const char * format, void * address) {
char buffer[1024];
fgets(buffer, sizeof buffer, stdin);
return sscanf(buffer, format, address) == 1;
}
struct struc {
int a;
int b;
int c;
int add;
int grade;
};
int sj(int n) {
int t;
t = rand() % n;
return t;
}
void ctm_i(struct struc * t) {
{
t -> a = sj(101);
t -> c = sj(4);
if (t -> c == 1) {
t -> b = sj(101 - (t -> a));
t -> add = (t -> a) + (t -> b);
} else {
t -> b = sj((t -> a) + 1);
t -> add = (t -> a) - (t -> b);
}
t -> grade = 0;
}
}
void tcm_i(struct struc * t, int n) {
int ad;
printf(" ***********************************************************************"
"*********\n");
printf(" ......................................................................."
".........\n");
printf(" Question %d\n\n", n + 1);
printf(" You have 3 attempts for this question\n\n");
if (t -> c == 1)
printf(" %d+%d= ", t -> a, t -> b);
else
printf(" %d-%d= ", t -> a, t -> b);
myread(" %d", & ad);
if (ad == t -> add)
{
t -> grade = 10;
printf(" You earned 10 marks\n\n");
} else {
printf("\n Incorrect, you have 2 attempts remaining\n\n");
printf(" ");
myread(" %d", & ad);
if (ad == t -> add)
{
t -> grade = 7;
printf(" You earned 7 marks\n\n");
} else {
printf("\n Incorrect, you have 1 attempt remaining\n\n");
printf(" ");
myread(" %d", & ad);
if (ad == t -> add)
{
t -> grade = 5;
printf(" You earned 5 marks\n\n");
} else {
t -> grade = 0;
printf("\n Failure, 0 mark\n\n");
printf("\n The correct answer is %d\n\n", t -> add);
}
}
}
printf(" ......................................................................."
".........\n");
printf(" ***********************************************************************"
"*********\n");
}
void quiz(char name[]) {
int rounds = 0;
int highest = 0;
int lowest = INT_MAX;
float allScore = 0;
float avg = 0.0;
int i, j, g = 0;
struct struc test[MAX_TESTS];
srand((unsigned) time(NULL));
for (;;) {
rounds++;
for (i = 0; i < MAX_TESTS; i++) // generate all questions
{
ctm_i( & test[i]);
for (j = 0; j < i; j++)
if (test[i].a == test[j].a && test[i].b == test[j].b && test[i].c == test[j].c)
//if question is already present
ctm_i( & test[i]); //then re-generate
}
printf("\n Are you ready? Press Enter key to continue. ");
myread("", NULL);
for (i = 1; i <= 5; i++) {
printf(" *******************************************************************"
"**"
"***********\n");
printf(" ..................................................................."
".."
"...........\n");
}
// Take quiz
for (i = 0; i < MAX_TESTS; i++)
tcm_i( & test[i], i);
printf(" End\n\n");
bool done = false;
bool unsure = true;
bool showS = true;
bool acct = false;
while (unsure) {
unsure = false;
puts("\n");
if (showS) {
puts(" Enter 'S' to show results");
}
puts(" Enter 'P' to play another round");
puts(" Enter 'R' to return to main menu");
char choice;
printf(" ");
myread(" %c", & choice);
printf("\n");
if (choice == 'r' || choice == 'R') {
done = true;
} else {
///////////////////////// Changes /////////////
if (false == acct) {
g = 0;
// calculate total score for current round
for (i = 0; i < MAX_TESTS; i++) {
g += test[i].grade; //add score of each question
}
allScore += g; //add current round's score to total
avg = allScore / rounds; //average of all rounds
if (g > highest) {
highest = g;
}
if (g < lowest) {
lowest = g;
}
acct = true;
}
if (showS &&(choice == 'S' || choice == 's')) {
showS = false;
if (rounds == 1) {
printf(" Final score: %d/100\n", g); //display round score
printf(" ****** Player: %s ******\n", name);
} else {
printf(" Round %d score: %d/100\n", rounds, g); //display round score
printf(" Highest score: %d/100\n", highest);
printf(" Lowest score : %d/100\n", lowest);
printf(" Average score: %f/100\n", avg);
printf(" ****** Player: %s ******\n", name);
}
unsure = true;
} else if (choice == 'P' || choice == 'p') {
/// nothing to be done here
//we will display next test
} else {
puts(" Invalid input!");
unsure = true;
}
////////////////////////////////////
}
}
if (done)
break;
}
}
int main() {
char i1 = '1';
char name[25]; // ig;
printf("\n Welcome");
printf("\n");
while (i1 != 0) {
printf("\n");
//printf(" **********************Welcome %s! *********************\n", name);
printf(" ************************ Main Menu of Maths Quiz ***************************\n");
printf(" * 1.Enter Quiz *\n");
printf(" * 2.Quit *\n");
printf(" ****************************************************************************\n");
printf(" Please choose one from 1-2:\n");
printf(" ");
myread(" %c", & i1);
switch (i1) {
case '1':
printf("\n Enter Quiz:\n");
quiz(name); // calling quiz function defined in file "maincode.c"
break;
case '2':
printf(" Quit.\n\n");
}
}
return 0;
}
Output:
Enter 'S' to show results
Enter 'P' to play another round
Enter 'R' to return to main menu
s
Round 2 score: 47/100
Highest score: 50/100
Lowest score : 47/100
Average score: 48.500000/100
****** Player: ******

Stop array from printing 0 at end

I made a guessing game where a random number is generated and the user has 10 tries to guess it. At the end of the game, the program prints the array of all tries. When the user guesses correctly in less than 10 tries, the array prints out all tries and prints zeros after so that there are 10 elements in total because of the for loop.
If the number is 62 and it's guessed in 6 tries for example it looks like
Your Tries: 50 90 60 65 63 62 0 0 0 0
I want to make it so that the extra zeros are not printed at the end of the game.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main (int argc, char** argv)
{
int s, n, v, win = 0, lose = 0;
char c;
srand( time(NULL) );
s = rand () % 100 + 1;
int tries = 0;
int a[n];
for (tries = 0; tries < 10; tries++)
{
scanf ("%d", &a[tries]);
if (a[tries] == s)
{
win++;
printf ("\nYou win!\n");
printf ("Your Tries: ");
for (tries = 0; tries < 10; tries++)
{
printf ("%d ", a[tries]);
}
printf ("\nTry Again? ");
scanf (" %c", &c);
if (c == 'n' || c == 'N')
{
printf("Your stats: %d Win, %d Lose", win, lose);
return 0;
}
if (c == 'y' || c == 'Y');
{
tries = 0;
s = rand () % 100 + 1;
scanf ("%d", &a[tries]);
}
}
printf ("The number is %s %d.\n", a[tries] > s ? "less than" : "greater than",
a[tries]);
}
printf ("You input wrong number. You lose. The number is %d.\n", s);
lose++;
printf ("Your Tries: ");
for (tries = 0; tries < 10; tries++)
printf ("%d ", a[tries]);
printf ("\nTry Again? ");
scanf (" %c", &c);
if (c == 'n'|| c == 'N')
{
printf("Your stats: %d Win, %d Lose", win, lose);
return 0;
}
if (c == 'y' || c == 'Y');
{
tries = 0;
s = rand () % 100 + 1;
scanf ("%d", &a[tries]);
}
}
It looks like you print out the last ten numbers using this:
for (tries = 0; tries < 10; tries++) {
printf ("%d ", a[tries]);
}
however it continues to loop even if you have less than ten numbers, a short fix could be to add a variable to store the number of tries, increase it every try and then use it in the for loop to not print too much numbers:
int tries = 0;
int nb_tries = 0;
int a[n];
for (tries = 0, nb_tries = 0; tries < 10; tries++, nb_tries++) {
scanf("%d", &a[tries]);
if (a[tries] == s) {
win++;
printf ("\nYou win!\n");
printf ("Your Tries: ");
for (tries = 0; tries < nb_tries; tries++) {
printf("%d", a[tries]);
}
}
}

How to stop input in programming c language

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;
}

What is the error in the following factorial find C program?

My logic is entered num store into temp variable and find factorial using temp = temp * (num - i) inside while until num is greater than 0 and initially i = 1 , but I get problem that my loop goes in to infinite loop how to solve this problem ?
#include <stdio.h>
int main() {
int num, temp, i;
printf("Enter a Num who's factorial is need to be find : ");
scanf("%d", &num);
printf("num = %d\n", num);
temp = num;
printf("temp = %d\n", temp);
i = 1;
while (num > 0) {
temp = temp * (num - i);
i++;
printf(" i = %d\n ", i);
}
printf("fact = %d \n ", temp);
return 0;
}
Here you are checking num > 0 but never updating value of num inside the loop
Update it to check num - i > 0 or num > i
while(num - i > 0)
{
temp = temp * (num-i);
i++;
printf(" i = %d\n ",i);
}
while(num > 0)
{
num is never updated inside the loop, so num will always be > 0.What you want is
while((num-i) > 0)
i is updated in every run of the loop, so eventually num-i will become 0 and the loop will terminate.
while(num>0) was not updated. So You can use while((num-i)>0) for update loop.Try below C code.
#include <stdio.h>
int main(){
int num,temp,i;
printf("Enter a Num who's factorial is need to be find : ");
scanf("%d",&num);
printf("num = %d\n",num);
temp = num;
printf("temp = %d\n",temp);
i=1;
while((num - i) > 0){
temp = temp * (num-i);
i++;
printf(" i = %d\n ",i);
}
printf("fact = %d \n ",temp);
return 0;
}
You don't require an extra variable i. It is important that you should take care the time and space complexity of a program.
#include <stdio.h>
int main()
{
int num,temp;
printf("Enter a Num who's factorial is need to be find : ");
scanf("%d",&num);
printf("num = %d\n",num);
temp = 1;
while(num > 0)
{
printf(" num= %d\n ",num);
temp = temp * num;
num--;
}
printf("fact = %d \n ",temp);
return 0;
}
You never update num inside the body of the while (num > 0) loop, hence an infinite loop.
You should use a simpler method: a classic for loop with an index i incrementing from 1 to n inclusive. This way you do not modify the value of num and can use it for the final output:
#include <stdio.h>
int main(void) {
int num, res, i;
printf("Enter a number whose factorial to compute: ");
if (scanf("%d", &num) == 1) {
res = 1;
for (i = 1; i <= num; i++) {
res = res * i;
}
printf("%d! = %d\n", num, res);
}
return 0;
}
Notes:
the initial value of i could be changed to 2.
factorials grow very quickly: this program will only handle numbers from 0 to 12. Changing the type of res to unsigned long long will handle up to 20.

Resources