Problems with a program [C arrays] - c

My friend and I are trying to build a program together, but it just doesn't seem to be working. Neither of us have much experience with C, so we just can't spot the issue... Any advice or help would be much appreciated!
Apologies for the slightly awkward lyrics?
[Edit] The problem is that when we input values, we get ridiculous figures like 4586368.
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
void main()
{
int room[20] = {};
int i;
int rooms = 0;
char option = 0;
int lights = 0;
int hrsUsed = 0;
int Telly = 0;
int TVWatt =0;
int sumTV;
int TVuse = 0;
int Computer = 0;
int compWatt = 0;
int compUsed = 0;
int compTotal;
int kwH_lights;
int fridge = 0;
int washLoad = 0;
int dryerLoad = 0, dishLoad = 0, cookLoad = 0;
int showeruse = 0;
int total_kWh;
printf("Enter number of rooms");
scanf_s("%d", &rooms);
for(i=0;i<rooms;i++)
{
printf("input average wattage of lights");
scanf_s("%d", &lights);
lights=lights/1000;
printf("input number of hours use/day (average)");
scanf_s("%d", &hrsUsed);
kwH_lights=((lights*hrsUsed)*365);
printf("input number of TVs");
scanf_s("%d", &Telly);
printf("input average wattage");
scanf_s("%d", &TVWatt);
printf("input average use a day");
scanf_s("%d", &TVuse);
sumTV=((Telly*(TVWatt/1000))*TVuse)*365;
}
printf("Input number of fridge/freezer");
scanf_s("%d",&fridge);
fridge=(fridge*2)*365;
printf("input number of Computers and/or video game consoles in the house");
scanf_s("%d", &Computer);
for(i=0;i<Computer;i++) {
printf("input wattage");
scanf_s("%d", &compWatt);
printf("input average hrs used/day");
scanf_s("%d", &compUsed);
compTotal=((compWatt/1000)*compUsed)*365;
}
printf("Input average number of washing machine loads /day");
scanf_s("%d",&washLoad);
washLoad=washLoad*365;
printf("Input average number of clothes dryer loads/day");
scanf_s("%d",&dryerLoad);
dryerLoad=(dryerLoad*3)*365;
printf("Input average number of dishwasher loads/day");
scanf_s("%d",&dishLoad);
dishLoad=(dishLoad*1.5)*365;
printf("Input average cooking load/day");
scanf_s("%d",&cookLoad);
cookLoad=(cookLoad*7)*365;
printf("Input average hrs/day of shower usage");
scanf_s("%d",&showeruse);
showeruse=(showeruse*7)*365;
total_kWh=((kwH_lights)+(sumTV)+(fridge)+(compTotal)+(dryerLoad)+(dishLoad)+(cookLoad)+(showeruse));
printf("Total= %d", &total_kWh);
}

You should change this:
printf("Total= %d", &total_kWh);
to that:
printf("Total= %d", total_kWh);
Same is true for all your other integer variables.

There were quite a few mistakes in your code:
you printed the memory-address instead of result value (don't use & with printf if your variable is a plain int)
the computer for-loop had no curly brackets (so only the printf statement was looped)
results were not summed up (in all loops you've just overwritten your inputs from the last loop)
the rooms[] Array was never used - a few other variables also (possible error source, if you wanted to use them and just forgot it)
the result from a multiplication with 1.5 will hold a double value - you should cast that back to int (dishLoad)
The bold mistake is probably that one, why your values were wrong...
Also notice: The 'average number of washing machine loads/clothes dryer loads/ dishwasher loads' should better be asked by week or month... Or should hold Floating Point values: Because everyone I know don't use the washing machine and clothes dryer every day multiple times. So now you can't enter something like once a week (which would be an factor of 0.14, but is not enterable cause all values are stored as int).
Here Comes the code with everything fixed, I could found:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
int main(int argc, char** argv){
int i = 0;
int rooms = 0;
int lights = 0;
int hrsUsed = 0;
int Telly = 0;
int TVWatt =0;
int sumTV = 0;
int TVuse = 0;
int Computer = 0;
int compWatt = 0;
int compUsed = 0;
int compTotal= 0;
int kwH_lights = 0;
int fridge = 0;
int washLoad = 0;
int dryerLoad = 0, dishLoad = 0, cookLoad = 0;
int showeruse = 0;
int total_kWh = 0;
printf("Enter number of rooms: ");
scanf_s("%d", &rooms);
for(i=0;i<rooms;i++){
printf("A few questions about room %d\n", i+1);
printf("input average wattage of lights: ");
scanf_s("%d", &lights);
lights+=lights/1000;
printf("input number of hours use/day (average): ");
scanf_s("%d", &hrsUsed);
kwH_lights+=((lights*hrsUsed)*365);
printf("input number of TVs: ");
scanf_s("%d", &Telly);
printf("input average wattage: ");
scanf_s("%d", &TVWatt);
printf("input average use a day: ");
scanf_s("%d", &TVuse);
sumTV+=((Telly*(TVWatt/1000))*TVuse)*365;
}
printf("Input number of fridge/freezer: ");
scanf_s("%d",&fridge);
fridge=(fridge*2)*365;
printf("input number of Computers and/or video game consoles in the house: ");
scanf_s("%d", &Computer);
for(i=0;i<Computer;i++){
printf("A few questions about computer %d\n", i+1);
printf("input wattage: ");
scanf_s("%d", &compWatt);
printf("input average hrs used/day: ");
scanf_s("%d", &compUsed);
compTotal += ((compWatt/1000)*compUsed)*365;
}
printf("Input average number of washing machine loads/day: ");
scanf_s("%d",&washLoad);
washLoad=washLoad*365;
printf("Input average number of clothes dryer loads/day: ");
scanf_s("%d",&dryerLoad);
dryerLoad=(dryerLoad*3)*365;
printf("Input average number of dishwasher loads/day: ");
scanf_s("%d",&dishLoad);
dishLoad=(int)((dishLoad*1.5)*365);
printf("Input average cooking load/day: ");
scanf_s("%d",&cookLoad);
cookLoad=(cookLoad*7)*365;
printf("Input average hrs/day of shower usage: ");
scanf_s("%d",&showeruse);
showeruse=(showeruse*7)*365;
total_kWh=((kwH_lights)+(sumTV)+(fridge)+(compTotal)+(dryerLoad)+(dishLoad)+(cookLoad)+(showeruse));
printf("Total= %d\n", total_kWh);
system("Pause");
return 0;
}
I hope it helps you out - if you got any questions left, feel free to ask.

My first step would be to correct the second for loop { } ... fix this and ask again.
[EDIT]
your calculations with usages of int values divided by other ints (compwatt / 1000) ... are you sure your idea of using int is correct?
or:
cookLoad=(cookLoad*7)*365;
why multiplying with 7 AND 365? should not the average / day be multiplied by 365 only?

For more readability of your code, you can employ compound assignment operators as below,
Operator Name Syntax Meaning
-------------------------------------------------
Addition assignment a += b a = a + b
Subtraction assignment a -= b a = a - b
Multiplication assignment a *= b a = a * b
Division assignment a /= b a = a / b

Related

Function gives me a wrong answer

I'm new to C. I've been tasked to run a program that calculates the percentage of students that passed an exam,based on N grade inputs.I don't really understand how functions work in though.This is what I came up with
#include <stdio.h>
#define MAX_N 300
main()
{
int N,grade,i;
float success(N)
{
float sum=0.0;
for (i=0;i<N;i++) {
if (grade>=5) {
sum+=1;
}
float success=sum/N;
return(success);
}
}
printf("How many students? ");
scanf("%d",&N);
printf("Enter grades(0-10) of %d students ",N);
for (i=0;i<N;i++){
scanf("%d",&grade);
}
printf("%f percent of students have passed the exam ",success(N);
return(0);
}
It looks like it should work, however I always get the wrong result.It is stuck on displaying 0.2 or 0.25 for any input I give.Can somebody help?
The problem is that in grade only the last entered data is being stored. Make grade as an array so that all data can be stored.
I guess you are taking multiple value for grade and not taking array for it.
grade should be an array and in loop scanf("%d",&grade[i]); should be implement.
grade should be an array of N integers so that each and every value is stored. You also forgot to multiply success by 100 to get the percentage.
I think I fixed the code:
#include <stdio.h>
#define MAX_N 300
float success(int grade[],int N)
{int i;
float sum=0.0;
for (i=0;i<N;i++) {
if (grade[i]>=5) {
sum+=1;
}
}
float success=sum/N;
return(success*100);
}
int main(){
int N, i;
printf("How many students? ");
scanf("%d",&N);
int grade[N];
printf("Enter grades(0-10) of %d students ",N);
for(i=0;i<N;i++){
scanf("%d", &grade[i]);
}
printf("%f percent of students have passed the exam ", success(grade, N));
return(0);
}
I think you should examine the code I wrote. A little bad code. But it can help.
#include <stdio.h>
int students_success(int *);
int main() {
int n;
printf("How many students?\n");
scanf("%d", &n);
printf("Enter grades(0-10) of %d students\n", n);
int grade;
int pass_std = 0;
for(int i = 0; i < n; ++i) {
scanf("%d", &grade);
pass_std = students_success(&grade);
}
printf("%.2f percent of students have passed exam.\n", (double)pass_std / n);
}
int students_success(int *grade) {
static int pass_std = 0;
if(4 < *grade) {
++pass_std;
}
return pass_std;
}

Printing the average of combined student marks using C

I've made this program below to calculate the average mark of a student.
Everything works well until I use -1, it is supposed to stop the program as is display the average of all students that have been entered, say Goodbye! and then terminate.
I think my calculations might be wrong though because it is printing the wrong result for the average marks of the students.
Thanks in Advance.
#include <stdio.h>
int main(void)
{
float final_mark(int a_mark1, int a_mark2, int lab_mark, int quiz_mark, int exam_mark);
int i, a_mark1, a_mark2, lab_mark, quiz_mark, exam_mark;
float average_mark = 0.0;
do
{
for (i = 0; i < 2; i++)
{
printf("Enter assignment 1 mark (-1 to quit): ");
scanf("%d", &a_mark1);
if(a_mark1 == -1)
{
average_mark += final_mark(a_mark1, a_mark2, lab_mark, quiz_mark, exam_mark);
if ((average_mark > 1 ) && (average_mark < 100 ))
{
printf("The average student mark is %.2f%% \n", average_mark);
}
printf("Goodbye! \n");
return 0;
}
printf("Enter assignment 2 mark: ");
scanf("%d", &a_mark2);
printf("Enter laboratory mark: ");
scanf("%d", &lab_mark);
printf("Enter quiz mark: ");
scanf("%d", &quiz_mark);
printf("Enter exam mark: ");
scanf("%d", &exam_mark);
printf("Student %d final mark: %.2f \n", i + 1, final_mark(a_mark1, a_mark2, lab_mark, quiz_mark, exam_mark));
}
}
while(a_mark1 != -1);
return 0;
}
float final_mark(int a_mark1, int a_mark2, int lab_mark, int quiz_mark, int exam_mark)
{
float final_mark = a_mark1 * 0.1 + a_mark2 * 0.15 + lab_mark * 0.15 + quiz_mark * 0.1 + exam_mark * 0.5;
return final_mark;
}
I think you need to rethink your logic a little bit. Why not use a while loop to control the flow. Then you can bail out of the program immediately if user inputs -1 right away. You should use an array to store the averages for each student, then you can loop through and find the class average as well.
-Your float final_mark function seems a little sketchy without any parenthesis.
-You should put your function prototype outside of main as well. See below changes.
#include <stdio.h>
#define MAX_STUDENTS 10 //define what the max number of students is
float final_mark(int mark1, int mark2, int lab, int quiz, int exam);
int main()
{
int i = 0, mark1 = 0, mark2 = 0,
lab = 0, quiz = 0, exam = 0;
int num_students;
float students_avg[MAX_STUDENTS] = {0}; //array to hold averages for students
float average = 0;
while (i < MAX_STUDENTS) {
printf("Enter assignment 1 mark (enter -1 to quit):\n");
scanf("%d", &mark1);
if (mark1 == -1)
break; //no more students, break out of while loop
printf("Enter assignment 2 mark: ");
scanf("%d", &mark2);
printf("Enter laboratory mark: ");
scanf("%d", &lab);
printf("Enter quiz mark: ");
scanf("%d", &quiz);
printf("Enter exam mark: ");
scanf("%d", &exam);
average = final_mark(mark1, mark2, lab, quiz, exam);
students_avg[i] = average; //add this average to array
printf("Student # %d average was %.2f\n", i, students_avg[i]);//debug info
i++;
}
num_students = i; //how many students grades did we read?
average = 0; //reset to 0 so we can use below
for (i = 0; i < num_students; i++)
average += students_avg[i];
if (num_students > 0)
printf("Class average is %.2f\n", average/num_students);
else
printf("Goodbye!\n");
return 0;
}
float final_mark(int mark1, int mark2, int lab, int quiz, int exam)
{
//we can just return the calculation
return ((mark1 * 0.1) + (mark2 * 0.15) + (lab * 0.15) + (quiz * 0.1) + (exam * 0.5));
}
Just erase two lines above printf("GOODBYE! \n"); you will get what you want.
maybe you have to initialized mark s variables to 0. and a_mark1 to 0 too if the user enter -1

New to programming. Need help adjusting code to allow for undetermined number of students

Need help adjusting code to allow for undetermined number of students. Tried to modify with help I received last week, but it seems like I am not doing it correctly.
#include <stdio.h>
int main ()
{
/* variable definition: */
char StudentName[100];
float ExamValue, Sum, Avg;
int students,exams;
// Loop through 5 Students
for (students=0; students <5 ; students++)
{
// reset Sum to 0
Sum =0.0;
printf("Enter Student Name \n");
scanf("%s", StudentName);
// Nested Loop for Exams
for (exams=0; exams < 3; exams++)
{
printf ("Enter exam grade: \n");
scanf("%f", &ExamValue);
Sum += ExamValue;
}
Avg = Sum/3.0;
printf( "Average for %s is %f\n",StudentName,Avg);
}
return 0;
}
Not sure how I need to go about changing the code. Any help will be greatly appreciated
Not sure I understand correctly, I understood you want to loop an undertemined amount of students.
I will assume you want to stop if certain keyword is added as a student name, let's say "quit".
Without changing your structure much, it would look like this.
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
int main (){
char StudentName[100];
float ExamValue, Sum, Avg;
int students,exams;
bool in = true;
while (in) {
Sum =0.0;
printf("Enter Student Name \n");
scanf("%s", StudentName);
if( strcmp(StudentName, "Quit") == 0 || strcmp(StudentName, "quit") == 0){
in = false;
break;
}
for (exams=0; exams < 3; exams++){
printf ("Enter exam grade: \n");
scanf("%f", &ExamValue);
Sum += ExamValue;
}
Avg = Sum/3.0;
printf( "Average for %s is %f\n",StudentName,Avg);
}
return 0;
}

Retaining input values in C?

I have asked for the user to enter in several values to calculate an average, however I'd like to also calculate a gradient which uses the inputted values. How do I name these values so I can use them again? Thank you.
Here is what I have thus far:
#include <stdio.h>
int main () {
int n, i;
float num[1000], total=0, mean;
printf("Enter the amount of x-values:");
scanf("%d", &n);
while (n <= 0 || n > 1000) {
printf("Print error. The number should in range of 0 to 1000.\n");
printf("Please try to enter the amount again: ");
scanf("%d", &n);
}
for (i = 0; i < n; ++i) {
printf("%d. Input x-value:", i+1);
scanf("%f", &num[i]);
total += num[i];
}
mean=total/n;
printf("The mean of all the x-values entered is %.2f to 2 decimal places", mean);
{
float num[1000], total=0, mean;
printf("Enter the amount of y-values:");
scanf("%d", &n);
while (n <= 0 || n > 1000) {
printf("Print error. The number should in range of 0 to 1000.\n");
printf("Please try to enter the amount again: ");
scanf("%d",&n);
}
for (i = 0; i < n; ++i) {
printf("%d. Input y-value:", i+1);
scanf("%f", &num[i]);
total += num[i];
}
mean = total / n;
printf("The mean of all the y-values entered is %.2f to 2 decimal places", mean);
return 0;
}
}
Naming the variable is really up to you, but `int gradient[NUM_ELEMENTS]; seems appropriate. It is an array, which also seems appropriate if it's purpose is to assist in finding the gradient from a series of numbers.
Steps could be:
1) use printf to ask user for values, specify spaces or commas between values. You can also specify a limit of values. Example printf("enter 5 numbers separated by commas\n:");
2) use scanf or similar to read values from standard input (the terminal) into the array: scanf("%d,%d,%d,%d,%d", &gradient[0], &gradient[1], &gradient[2], &gradient[3], &gradient[4]);
3) use the array an a function that will compute the gradient.
Simple example:
(where gradient computation, error checking, bounds checking etc. is all left to you)
int get_gradient(int a[5]);
int main(void) {
int gradient[5];
int iGradient=0;
printf("enter 5 numbers separated by commas");
scanf("%d,%d,%d,%d,%d", &gradient[0], &gradient[1], &gradient[2], &gradient[3], &gradient[4]);
iGradient = get_gradient(gradient);
return 0;
}
int get_gradient(int a[5])
{
return [do computation here using array a];
}
Edit:
The above example works only if you know the number of elements at compile time. It uses an int array that has been created on the stack. If you do not know how big of an array you will need until run-time, for example if user input determines the size, then the array size needs to be determined at run-time. One options is to create the variable needed on the heap. (read about stack and heap here) The following uses some techniques different from the simpler version above to get user input, including a function I called get_int(), which uses scanf() in conjunction with strtol(). Here's the example:
int main(void) {
char input[80]={0};
char **dummy={0};
long *gradient = {0};
int iGradient=0;
int arraysize;
int i;
char* fmt = "%[^\n]%*c";
printf("how many numbers will be entered?");
scanf(fmt, input);
arraysize = strtol(input, dummy, 10);
gradient = calloc(arraysize, sizeof(long));
if(gradient)
{
for(i=0;i<arraysize;i++)
{
gradient[i] = get_int();
}
iGradient = get_gradient(gradient, arraysize);
//free gradient when done getting result
free(gradient);
}
return 0;
}
int get_gradient(int *a, int num)
{
int grad = 0, i;
//do something here to compute gradient
return grad;
}
long get_int(void)
{
char input[80]={0};
char **dummy={0};
char* fmt = "%[^\n]%*c";
printf("Enter integer number and hit return:\n");
scanf(fmt, input);
return strtol(input, dummy, 10);
}

Finding biggest and smallest numbers using user input

Well it is a problem about finding the biggest and smallest number in a group of numbers, but we do not know how many numbers the user wants-
So far this is what i have done:
#include <stdio.h>
#include <conio.h>
int main()
{
int num;
int i;
int maxi=0;
int minim=0;
int cont = 0;
printf ("\nQuantity of numbers?: ");
scanf ("%d", &num);
while (num>0)
{
printf ("\nEnter number:");
scanf ("%d", &i);
if (num>i)
minim=i++;
else
if (i>num)
max=i++;
cont++;
}
printf ("\nBiggest number is es: %d", maxi);
printf ("\nSmallest number is: %d", minim);
getch();
return 0;
}
I did my program to ask how many numbers the user will want to put and i made the program to read them, BUT when it reads the biggest or/and smallest numbers it will sometimes changes biggest with small and it will not read negative numbers.
How do i do to make my program better?
You're comparing against the wrong values.
do
{
printf("Enter a number.\n");
scanf("%i", &input);
if min > input
min = input
if max < input
max = input
} while (input > 0);
#include <stdio.h>
#include <conio.h>
#include <limits.h>
int main(){
int num;
int i;
int maxi=0;
int minim=INT_MAX;
int cont = 0;
printf ("\nQuantity of numbers?: ");
scanf("%d", &num);
if(num > 0){
while (num>0){
printf ("\nEnter number:");
if(scanf("%d", &i) == 1 && !(i<0)){
if(minim > i)
minim = i;
if (maxi < i)
maxi = i;
++cont;
--num;
} else {
//fprintf(stderr, "redo input!\n")
;
}
scanf("%*[^\n]%*c");
}
printf ("\nBiggest number is : %d", maxi);
printf ("\nSmallest number is : %d\n", minim);
}
getch();
return 0;
}
You should initialize mini to the largest possible int, i.e. INT_MAX and maxi to the smallest possible int, i.e., INT_MIN. This way, even if the first number is negative, it will be considered for maxi, and if the first number is positive it will still be considered for mini. The constants INT_MAX and INT_MIN are included in <climits> or <limits.h>.
Also, you are comparing the current entered number with num, which is the counter of numbers entered by user, not one of the values he wants to compare. A better modified code would be :
#include<limits.h>
#include<stdio.h>
int main()
{
int num;
int maxi=INT_MIN; //initialize max value
int mini=INT_MAX; //initialize min value
int temp;
scanf("%d", &num); //take in number of numbers
while(num--) //loop "num" times, num decrements once each iteration of loop
{
scanf("%d", &temp); //Take in new number
if(temp>maxi) //see if it is new maximum
maxi=temp; //set to new maximum
if(temp<mini) //see if new minimum
mini=temp; //set to new minimum
}
printf("\nMaxi is:\t%d\nMini is:\t%d\n", maxi, mini); //print answer
return 0;
}

Resources