Nested if loop in for loop - c

this code just generates a random number to be taken in as the temperature and records it every hour. I am having issues with my for loop on getting the max and min values of my code. It looks correct to me and similar to all the examples I have seen but it's giving me the wrong output.
Thank you
#include <stdio.h>
#include <stdlib.h>
void GetValue(int[], int x);
#define array_size 25
int main() {
int x, max, min, temperature[25];
float sum;
float average;
int array[array_size];
printf("Temperature Conditions on October 9, 2015:\n");
printf("Time of Day \t Temperature in Degrees F\n");
for (x = 0; x < 25; x++) {
//if statements to get min and max
GetValue(temperature, x);
if (temperature[x] > max) {
max = temperature[x];
}
if (temperature[x] < min) {
min = temperature[x];
}
printf("%d \t \t \t %d\n", x,temperature[x]);
}
//prints statements
printf("\nMaximum Temperature for the day: %d Degrees F\nMinimum Temperature for the day: %d Degrees F\n", temperature[12],max, min);
//adds up all temps
sum=0;
for (x=0;x<25;x++){
sum=(sum+temperature[x]);
}
//prints and creates average
average=sum/25;
printf("Average Temperature for the day: %.2f Degrees F\n",average);
return 0;
}
//gets values and puts them into array
void GetValue(int value[], int x) {
value[x] = (rand()%(100-60+1))+60;
}

You invoked undefine behavior by using values of uninitialized variables having automatic storage duration, which is indeterminate.
Use values of variables only after assigning some value to them.
Format your code properly.
Match format specifier and data for printf().
Avoid using magic number. Use the #defined number for number of elements in this case.
Corrected code:
#include <stdio.h>
#include <stdlib.h>
void GetValue(int[], int x);
#define array_size 25
int main(void) {
int x, max = 0, min = 0, temperature[array_size];
float sum;
float average;
printf("Temperature Conditions on October 9, 2015:\n");
printf("Time of Day \t Temperature in Degrees F\n");
for (x = 0; x < array_size; x++) {
//if statements to get min and max
GetValue(temperature, x);
// in the first iteration, there won't be a valid number in max and min
if (x == 0 || temperature[x] > max) {
max = temperature[x];
}
if (x == 0 || temperature[x] < min) {
min = temperature[x];
}
printf("%d \t \t \t %d\n", x, temperature[x]);
}
//prints statements
printf("\nMaximum Temperature for the day: %d Degrees F\nMinimum Temperature for the day: %d Degrees F\n", max, min);
//adds up all temps
sum=0;
for (x=0;x<array_size;x++){
sum=(sum+temperature[x]);
}
//prints and creates average
average=sum/array_size;
printf("Average Temperature for the day: %.2f Degrees F\n", average);
return 0;
}
//gets values and puts them into array
void GetValue(int value[], int x) {
value[x] = (rand()%(100-60+1))+60;
}

Related

Calculating average miles walked per day with while loop

I am unable to get the input to be added and get the correct output for the average.
The code below is as far as I have made it. Any help would be greatly appreciated!
#include <stdio.h>
int main() {
/* variable definition: */
int days;
float avg, miles;
/* Initialize */
days=1;
// Loop through to input values
while(days<=7) {
printf("Enter the number of miles for each day walked.");
// use %lf for double, %f for float
scanf("%f", &miles);
days++;
}
avg = miles / days;
printf("average is %f\n " , avg );
return 0;
} // end main
As John3136 said, you aren't keeping track of the total miles walked. You scan in miles, but you don't keep track of the sum of the miles. Your average is simply your last entered miles divided by 7.
Here is a proposed solution:
int main(void)
{
// variable definition
int days = 0;
float avg = 0, miles = 0;
// Loop through to input values
while(days < 7)
{
printf("Enter the number of miles for each day walked: ");
scanf("%f", &miles);
avg += miles;
days++;
}
avg /= days;
printf("average is %.2f\n " , avg);
return 0;
}
With help from Jonathan Leffler here is an enhanced version of the previous code:
#include <stdio.h>
int main(void)
{
// variable definition
int days = 0;
double miles = 0.0, total_miles = 0.0;
// Loop through to input values
while(days < 7)
{
printf("Enter the number of miles for day %d: ", days + 1);
if(!scanf("%lf", &miles))
return -1;
total_miles += miles;
days++;
}
printf("Total miles: %.2lf / %d Days = %.2lf Average miles per day.\n",
total_miles, days, (days > 0) ? total_miles / days : 0.0);
return 0;
}

2 For loops one result

I need your wisdom. Looks not a big problem but I need a way.
First, I will share code. This code is correct but I need some addition, inside for loops have criteria if voltages are bigger than percentage it's ok but all be correct I need just one writing. I have 2 loops but need just one prompt.
If it is confusing I can share original question. Thank you guys.
I put original question:
Voltage readings are obtained from an electrical substation once every hour for six hours (so there are six
readings). Write a C program to perform the following checks on the substation:
a) display all voltages that differ from the average by more than 10% of the average.
b) display all pairs of consecutive hours where the change from the voltage at one hour
to the next is greater than 15% of the average.
Example 1
Enter 6 voltages: 210.1 223.2 189.6 206.2 235.1 215.0
The average is 213.2 volts.
10% = 21.3 volts.
15% = 32.0 volts.
The following problems occurred:
1. Voltage at hour 3 was 189.6 volts (difference of 23.6 volts).
2. Voltage at hour 5 was 235.1 volts (difference of 21.9 volts).
3. Voltage change from hour 2 to hour 3 was 33.6 volts.
Example 2
Enter 6 voltages: 233.1 201.0 221.5 240.2 222.7 208.1
The average is 221.1 volts.
10% = 22.1 volts.
15% = 33.2 volts.
No problems were encountered.
#include <stdio.h>
#include <math.h>
#include <string.h>
int i;
float volt[6];
float avg, avg10, avg15, total, a, b;
int main () {
total= 0 ;
avg = 0;
printf("Enter 6 Volts of Machine\n");
for ( i=0; i<6; i++) {
printf("Type %d. volt", i+1);
scanf("%f",&volt[i]);
total = total + volt[i];
}
avg = total/6;
avg10 = (avg * 10) / 100;
avg15 = (avg * 15) / 100;
printf("------------------------------------------\n");
printf("The machine Avarage Voltage is %.2f\n", avg);
printf("The Machine Avarage is%.2f\n", avg10);
printf("The Machine 15 Avarage is%.2f\n\n\n", avg15);
for (i=0;i<6;i++) {
a = fabs(volt[i] - avg);
if( a > avg10 ) {
printf("\nVoltage at hour %d was %.2f volts (diffrence of %.2f volts)\n\n", i+1, volt[i], a);
}
}
for (i=0; i<5; i++) {
b = fabs(volt[i+1] - volt[i]);
if( b > avg15) {
printf("\nVoltage change from hour %d to hour %d was %.2f\n\n", i+1, i+2, b);
}
}
If you need just one loop try something like this:
for (i=0;i<6;i++)
{
if((a = fabs(volt[i] - avg)) > avg10 )
{
printf("\nVoltage at hour %d was %.2f volts (diffrence of %.2f volts)\n\n", i+1, volt[i], a);
}
if((i < 5 && (b = fabs(volt[i+1] - volt[i])) > avg15 )
{
printf("\nVoltage change from hour %d to hour %d was %.2f\n\n", i, i+1, b);
}
}
If you want to print out a message when no problems were encountered, you must remember if any or how many errors were reported. You cannot print out such messages inside the loop, of course, because saying "No errors occurred" eight times and reporting thre errors is a bit of a contradiction.
Your expected out put shows an enumeration of errors, so it is a good idea to keep a count of errors. Proceed as follows:
Whenever you print an error message, increase the count of errors.
Before you do so, check whether this is the frst error that is reported. If so, print the caption ("The following errors occurred")
If you have checked everything and no errors have occurred, print the success message.
Or, in code:
int nerror = 0;
for (i = 0; i < n; i++) {
double v = fabs(volt[i] - avg);
if (v > avg10) {
if (nerror == 0) {
puts("The following problems occurred:");
}
nerror++;
printf("%d. Voltage at hour %d was %.2f volts "
"(diffrence of %.2f volts)\n",
nerror, i + 1, volt[i], v);
}
}
for (i = 1; i < n; i++) {
double diff = fabs(volt[i - 1] - volt[i]);
if (diff > avg15) {
if (nerror == 0) {
puts("The following problems occurred:");
}
nerror++;
printf("%d. Voltage change from hour %d to "
"hour %d was %.2f\n",
nerror, i, i + 1, diff);
}
}
if (nerror == 0) puts("No problems were encountered.");
Thank you for everyone my question was solved. Happy coding!
Code is :
#include <stdio.h>
#include <math.h>
int i;
float volt[6];
float avg, avg10, avg15, total, a, b;
int main () {
int voltageproblem1 = 0;
int voltageproblem2 = 0;
total= 0 ;
avg = 0;
printf("Enter 6 Volts of Machine\n");
for ( i=0; i<6; i++) {
printf("Type %d. volt", i+1);
scanf("%f",&volt[i]);
total = total + volt[i];
}
avg = total/6;
avg10 = (avg * 10) / 100;
avg15 = (avg * 15) / 100;
printf("------------------------------------------\n");
printf("The machine Avarage Voltage is %.1f\n", avg);
printf("The Machine Avarage is%.1f\n", avg10);
printf("The Machine 15 Avarage is%.1f\n\n\n", avg15);
for (i=0;i<6;i++) {
a = fabs(volt[i] - avg);
if( a > avg10 ) {
printf("\nVoltage at hour %d was %.1f volts (diffrence of %.1f volts)\n\n", i+1, volt[i], a);
voltageproblem1 =1;
}
}
for (i=0; i<5; i++) {
b = fabs(volt[i+1] - volt[i]);
if( b > avg15) {
printf("\nVoltage change from hour %d to hour %d was %.1f\n\n", i+1, i+2, b);
voltageproblem2 = 1;
}
}
if ((voltageproblem1==0)&&(voltageproblem2==0)) {
printf("No problems were encountered.\n\n");
}
}

Random numbers in array, max, min, average

So I'm making a ghetto weather report by creating a random number generator anywhere from 60-100 and storing 25 of these in an array. Then I have a function that calculates max, min, and average along with printing all of this out.
I got it to run without error, but all I'm getting are a bunch of zeros in my display, which means I'm messing up big time somewhere in the calculation, any suggestions?
Also I'm trying to get down calling user-defined functions which is why I have several.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int sum = 0;
int min = 0;
int max = 0;
int temp[25];
int i = 0;
float avg = 0;
int main () {
srand( (unsigned) time(NULL) );
for (i=0; i < 25; i++) {
get_value(i);
sum += temp[i];
}
calc_results(temp[25]);
return 0;
};
int get_value(void) {
return((rand() % (100 - 60 + 1)) + 60);
};
int calc_results(int temp_number[], int number) {
avg = ((sum)/(25));
max = temp[0];
for(i=1;i<25;i++){
if(max<temp[i])
max=temp[i];
};
min =temp[0];
for(i=1;i<25;i++){
if(min>temp[i])
min=temp[i];
};
printf("Temperature Conditions on October 9, 2015 : \n");
printf("Time of day Temperature in degrees F \n");
printf(" 0 %d\n",temp[0]);
printf(" 1 %d\n",temp[1]);
printf(" 2 %d\n",temp[2]);
printf(" 3 %d\n",temp[3]);
printf(" 4 %d\n",temp[4]);
printf(" 5 %d\n",temp[5]);
printf(" 6 %d\n",temp[6]);
printf(" 7 %d\n",temp[7]);
printf(" 8 %d\n",temp[8]);
printf(" 9 %d\n",temp[9]);
printf(" 10 %d\n",temp[10]);
printf(" 11 %d\n",temp[11]);
printf(" 12 %d\n",temp[12]);
printf(" 13 %d\n",temp[13]);
printf(" 14 %d\n",temp[14]);
printf(" 15 %d\n",temp[15]);
printf(" 16 %d\n",temp[16]);
printf(" 17 %d\n",temp[17]);
printf(" 18 %d\n",temp[18]);
printf(" 19 %d\n",temp[19]);
printf(" 20 %d\n",temp[20]);
printf(" 21 %d\n",temp[21]);
printf(" 22 %d\n",temp[22]);
printf(" 23 %d\n",temp[23]);
printf(" 24 %d\n",temp[24]);
printf(" 25 %d\n",temp[25]);
printf("Maximum Temperature for the day: %d Degrees F\n", max);
printf("Minimum Temperature for the day: %d Degrees F\n", min);
printf("Average Temperature for the day: %.1f Degrees F\n", avg);
};
firstly dude use loop to print 25 printf statements... ur code would be a bit smaller...
do the following changes and it should work pretty okay...
time_t t;
srand((unsigned) time(&t)); // this is a more standard way of using srand
also you have passed and int in get_value() whose parameter is void...
do this in the for loop in main
temp[i]=get_value();
also declare your functions on above of your code...
you dont need calc_results() like this...
do it
void calc_results(void)
and no neeed of passing temp since its already global...no need of passing number type integer since you are not using any such thing...no need of using return type as int since you dont need to return any integer...
final suggestion... Get a good book on functions
so your final code would look something like this:-
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int get_value(void);
void calc_results(void);
int sum = 0;
int min = 0;
int max = 0;
int temp[25];
int i = 0;
float avg = 0;
int main () {
time_t t;
srand((unsigned) time(&t));
for (i=0; i < 25; i++) {
temp[i]=get_value();
sum += temp[i];
}
calc_results();
return 0;
};
int get_value(void) {
return((rand() % (100 - 60 + 1)) + 60);
};
void calc_results(void) {
avg = ((sum)/(25));
max = temp[0];
for(i=1;i<25;i++){
if(max<temp[i])
max=temp[i];
};
min =temp[0];
for(i=1;i<25;i++){
if(min>temp[i])
min=temp[i];
};
printf("Temperature Conditions on October 9, 2015 : \n");
printf("Time of day Temperature in degrees F \n");
for(int j=0;j<25;j++){
printf(" %d %d\n",i,temp[i]);
}
printf("Maximum Temperature for the day: %d Degrees F\n", max);
printf("Minimum Temperature for the day: %d Degrees F\n", min);
printf("Average Temperature for the day: %.1f Degrees F\n", avg);
};
also Dont use global variables unless local variables fail...this would be at great help when you do some big codes and file handling
Just chance this line
get_value(i);
To
temp[i]=get_value(i);
Because you have to store the random values in temp[i] then you can calculate the other values.
And while you passing the array. You should do this--
calc_results(temp);
You can print all array value by a for loop. Like this:
int cnt;
for(cnt = 0; cnt<=25; cnt++)
{
printf(" %d %d\n",cnt,temp[cnt]);
}
You aren't assigning temp[i] any value?
for (i=0; i < 25; i++) {
temp[i] = get_value(i);
sum += temp[i];
}

Minmax numbers array

This program gets 5 numbers only from the user then
Store them in an array. Get the min, max, and the average of the numbers inputted. Here's the code I made:
#include <stdio.h>
#include <conio.h>
int main()
{
int num[5];
int min, max=0;
int counter;
float average, total;
max = num[0];
min = num[2];
for(counter=0; counter<=4; counter++)
{
printf("Enter a number: ");
scanf("%d", &num[counter]);
if(num[counter]>max)
{
max = num[counter];
}
if (num[counter]<min)
{
min = num[counter];
}
}
total = max+min;
average = total/2;
printf("The maximum number is: %d\n", max);
printf("The minimum number is: %d\n", min);
printf("The average is: %d", average);
getch();
return 0;
}
FInally fixed my error with the min and max and now I'm having trouble with the average. I should only get the average of the min and max numbers but it keeps on showing an average of zero. Can someone help? Thankkyouuu.
//get memory address and store value in it.
void getValue(int *ptr)
{
printf("Enter a number: ");
scanf("%d", ptr);
}
int main()
{
//initialized n=5 as per your requirement. You can even get the value at run time.
int min, max, counter,n=5;
int num[n];
float average,total;
getValue(num); //get num[0]
min=max=total=num[0]; //Initialize min,max,total with num[0]
for(counter=1; counter<n; counter++)
{
getValue(num+counter); //get num[counter]
num[counter]>max?max = num[counter]:max; //find max
num[counter]<min?min = num[counter]:min; //find min
total+=num[counter]; // total = total + num[counter]
}
average = total/n;
printf("The maximum number is: %d\n", max);
printf("The minimum number is: %d\n", min);
printf("The total is: %f\n", total);
printf("The average is: %f\n", average);
return 0;
}
Your calculation of average is wrong; you need to use total/num (remember use float):
total += num[counter];
max and min were incorrectly initialized: num[0], num[2] may be anything when you initialize them.
Aside from your calculation of average being wrong (it's not just total/2), you need to use the correct format specifier in the printf:
printf("The average is: %g", average);
You are using %d which tells printf to expect an integer, but you're giving it a float.
1 Min and max should be initialized
int min = INT_MAX;
int max = INT_MIN;
2 You need to keep a running total of your numbers
int total = 0;
...
// inside loop
scanf("%d", &num[counter]);
total += num[counter];
3 At the end print the average, recommend going to floating point.
printf("The average is: %.1f", (double)total/counter);

finding min & max

i wrote the code but i dont get max value how to find max value
#include <stdio.h>
int main(void)
{
double temp[0];
float max,min;
float i;
short c,j,k;
float sum=0;
float nu[c];
printf("Number of values :");
scanf("%f",&i);
for (c=1;i>=c;c++)
{
printf("values=");
scanf("%f",&nu[c]);
nu[c]=temp[0];
for (j = 0; i>=j; j++)
{
if (temp[0]> nu[c])
{
// nu[c]=temp[0];
max = temp[0];
}
}
sum = sum + nu[c];
}
printf("sum = %f \n",sum);
printf("maximum value = %f\n",max);
}
If you run your compiler with a -Wall (as you should always do), you should have seen the problems :
gcc -Wall -o foo foo.c
foo.c: In function 'main':
foo.c:35:14: warning: unused variable 'k'
foo.c:33:14: warning: unused variable 'min'
foo.c:62:1: warning: control reaches end of non-void function
foo.c:37:4: warning: 'c' is used uninitialized in this function
Here is the source code of a program that works :
#include <stdio.h>
int main(void)
{
float max = 0; // hypothesis : numbers keyed by the users are > 0
float min = 0; // hypothesis : numbers keyed by the users are > 0
int i, c;
float sum = 0;
float nu[100]; // hypothesis : no more than 100 numbers keyed by user
// hypothesis : float type is enough to store numbers keyed by user
printf("Number of values :");
scanf("%d",&i);
for (c = 0; c < i; c++)
{
printf("values=");
scanf("%f",&(nu[c]));
if (nu[c] > max) {
max = nu[c];
}
if (min == 0) {
min = nu[c];
} else if(nu[c] < min) {
min = nu[c];
}
sum = sum + nu[c];
}
printf("sum = %f \n",sum);
printf("maximum value = %f \n", max);
printf("minimum value = %f \n", min);
return 0;
}
You need a single for loop and not nested for loop.
Get input using the first for loop
Assign first element of the input array to variable, call this max
Compare each element of the array using a for loop again
If you get a value greater than max then change max to this value using the below code
if(max< a[i])
max=a[i];
At the end of these steps you can get max value.
Try to put these steps into a C code and it should be fine. There are some problems with the code you have written. I have written a small snippet for you to get input for number of elements and store them into your array for floats.
int number_of_elements;
printf("Enter the number of elements:\n");
scanf("%d", &number_of_elements);
for(i=0;i<number_of_elements;i++)
scanf("%f",&a[i]);
Here's the code with some helpful pointers:
#include <stdio.h>
int main(void)
{
double temp[0];
float max,min;
float i;
short c,j,k; // k isn't used anywhere.
float sum=0;
float nu[c]; // c isn't set at this point so the
// runtime couldn't create an
// array anyway.
printf("Number of values :");
scanf("%f",&i);
for (c=1;i>=c;c++)
{
printf("values=");
scanf("%f",&nu[c]);
// You should set min/max to nu[c]
// if c is 1 regardless.
nu[c]=temp[0]; // Why are you scanning into nu[c]
// then immediately overwriting?
for (j = 0; i>=j; j++) // Why figure out the max *every*
{ // time you enter a value?
if (temp[0]> nu[c])
{
// nu[c]=temp[0];
max = temp[0];
}
}
sum = sum + nu[c];
}
printf("sum = %f \n",sum);
printf("maximum value = %f\n",max);
}
I'd also suggest you go back to my original answer and create your code from that. It really is a much cleaner way of doing it than trying to fiddle around with arrays.
Let me emphasise that: if you're using an array, you're doing it the hard way!
Or this
#include <stdio.h>
int main(void)
{
float temp;
int val,i,j,k;
double sum = 0;
double number[val];
printf("Enter the number of values: ");
scanf("%d", &val);
double number[val];
for(i=1; i <= val ;i++)
{
printf("enter a value: ");
scanf("%lf", &number[i]);
sum = sum + number[i];
}
for(i=1;i<=val;i++)
{
for(j=i+1;j<=val;j++)
{
if(number[i] > number[j])
{
temp=number[i];
number[i]=number[j];
number[j]=temp;
}
}
}
printf("Sum = %.lf\n", sum);
printf ("Maximum element: %f\n",number[val]);
printf ("Minimum element: %lf\n", number[1]);
}
remove the temp (cant see the point of it)
set max to some initial value (e.g. first element of the array)
and change if statement to:
if (nu[c]> max)
{
max = nu[c];
}
This may not solve your question but nu[c] seems bad allocated to me since c value is undefined

Resources