2 For loops one result - c

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

Related

Why am I getting the wrong average in C?

I'm new at this and having some trouble. I'm trying to find the average of the grades that are inputed by the user but I realized that if you use a decimal in any of the grades, it's just being calculated as if they are whole numbers.
#include <stdio.h>
int main(void)
{
unsigned int counter;
float grade;
int total;
float average;
int number;
total = 0;
counter = 1;
printf("Number of scores to enter:\t");
scanf("%d", &number);
printf("\n");
while (counter <= number) {
printf("%s%d%s", "Enter the score for Lab ", counter, ":\t");
scanf("%f", &grade);
total = total + grade;
counter = counter + 1;
}
printf("\n");
average = (float) total / number;
printf("Average lab score: %.1f\n", average);
if (grade>=90) {
puts("Letter grade: A");
}
else if (grade>=80) {
puts("Letter grade: B");
}
else if (grade>=70) {
puts("Letter grade: C");
}
else if (grade>=60) {
puts("Letter grade: D");
}
else {
puts("Letter grade: F");
}
return 0;
}
You are capturing scanf("%f", &grade); as a float and then calculating total = total + grade;.
You have defined int total;. You would need to define it as float total;.
You are moving a float variable into an integer which is truncating the decimals you had previously entered.
There's no need to ask up front how many data points will be entered. Indeed, that is an anti-pattern. Just do something like:
#include <stdio.h>
int
main(void)
{
unsigned int count = 0;
float grade;
float total = 0.0;
float average;
while( scanf("%f", &grade) == 1 ) {
total += grade;
count += 1;
}
average = total / (float) count;
printf("Average lab score: %.1f\n", average);
fputs("Letter grade: ", stdout);
putchar( average >= 90.0 ? 'A' : average >= 80.0 ? 'B' :
average >= 70.0 ? 'C' : average >= 60.0 ? 'D' : 'F');
putchar('\n');
return average >= 60.0;
}
$ echo 78.2 96.5 80 | ./a.out
Average lab score: 84.9
Letter grade: B
Key points: total needs to be a float type. You must check the value returned by scanf. Always. Probably you want to handle bad input more cleanly that this does. This just throws away all data after an error and computes the average based on whatever data was entered prior to the error. A cleaner solution would abort with an error message. Exercise left for the reader.
A reasonable argument can be made that this is an abuse of the ternary operator; however you want to refactor it, don't repeat yourself by hardcoding the string "Letter grade: " multiple times.
Rather than abusing the ternary operator as above, you may prefer something like:
#include <stdio.h>
int
main(void)
{
unsigned int count = 0;
float grade;
float total = 0.0;
float average;
while( scanf("%f", &grade) == 1 ) {
total += grade;
count += 1;
}
average = total / (float) count;
int s = 'A' + (99 - (int)average) / 10;
printf("Average lab score: %.1f\n", average);
printf("Letter grade: %c\n", s > 'D' ? 'F' : s);
return average >= 60.0;
}

Can't Print " * " in C

for some reason I am unable to print out "* " in my program. I want to print out * if the condition is met. the condition is if the rainfall that day is greater than the average.
under the mean column, i am getting weird symbols. i tried debugging to decimals and get -112 for ascii. i dont understand but i tried researching!
I am new to C so please be understanding. Just learned like 2 days ago!!.
Here is my code :
//Assignment one 9/20/2018
//Anthony Lomaistro and David Luong
//luongd5#student.lasalle.edu
//lomaistroa1#student.lasalle.edu
#include <stdio.h>
main() {
int n = 0; //counters for the loops
int x = 0; // counter for the loops
int counter = 0; // counter whenever i need to keep track of increments
int days_input = 0; // how many days we are keeping track of
int number_of_days = 0;
double rainfall_input = 0;
double rainfall_amount = 0; // how much rainfall per day
double rainfall_average = 0; // average of rainfall
double rainfall_total = 0;
double rainfall_counter = 0; // count how many days it rained above the average
int correct = 0;
double rainfall_array[50];//array that contains the user input
char rainfall_condition[50]; // array that contains the *
double sum = 0;
double average = 0;
double percent_days = 0; //rainfall % above average
double valid = 0;
double valid2 = 0;
printf("Welcome to Lomaistro and Luong's Rainfall Program \n");
printf("How many days would you like to keep track of? Please enter a value between 1 and 50: #%d:", n + 1);
//printf(number_of_days);
while (valid == 0) {
scanf_s("%d", &number_of_days);
if ((number_of_days > 50) || (number_of_days <= 0)) { // come back to this, this doesnt do anytihng
printf("Invalid value, please enter in a day that is between 1 and 50 \n");
}
else {
valid = 1;
}
}
//getting the user to enter in the rainfall
for (x = 0; x < number_of_days; x = x + 1) {
valid2 = 0;
while (valid2 == 0) {
printf("Enter rainfall (in inches): ");
scanf_s("%lf", &rainfall_amount);
if ((rainfall_amount >= 0) && (rainfall_amount <= 10)) {
valid2 = 1;
rainfall_array[x] = rainfall_amount;
}
else
printf("Please enter in a valid rainfall amount between 1 and 10");
}
}
//computing average
for (n = 0; n < number_of_days; n = n + 1) {
sum += rainfall_array[n];
average = sum / number_of_days;
}
printf("Mean daily rainfall(in inches): %lf", average);
//seeing if the * should be the array or not
for (n = 0; n < number_of_days; n = n + 1) {
if (rainfall_array[n] > average) {
rainfall_condition[n] = "*";
rainfall_counter = rainfall_counter + 1;
}
else
rainfall_condition[n] = "empty";
}
// print out the thing
printf("\n Days \t Amount \t >Mean \n");
printf("==============================\n");
for (n = 0; n < number_of_days; n = n + 1) {
printf("%d \t %f \t %c \n", n + 1, rainfall_array[n], rainfall_condition[n]);
}
percent_days = rainfall_counter / number_of_days;
percent_days = percent_days * 100;
printf("Number of days that rained above average : %f \n", rainfall_counter);
printf("Percentage of days that rained above average: %f%% \n", percent_days);
system("pause");
}
rainfall_condition is an array of char, but you're putting a pointer to a string literal in there when you use "*". Use '*' for a character literal instead. To be more specific, this line:
rainfall_condition[n] = "*";
Should be:
rainfall_condition[n] = '*';
Turn some warnings on in your compiler; the first line (what you have now) isn't valid C code and you should be seeing a diagnostic message to that effect.
Edit: now that I've read more of the code, it appears you want either a * or an empty in that column? In that case you want to change the variable declaration to:
char *rainfall_condition[50]; // array that contains the *
And then change the print statement to:
printf("%d \t %f \t %s \n", n + 1, rainfall_array[n], rainfall_condition[n]);

Change Calculation Program in C

I'm just beginning studying programming and am trying to write a program that will display how many of each denomination of currency is required for any given amount of change.
I'm studying in Japan, so the currency is yen, but I think the basic code is universal. I've seen other similar programs online, but mine has a few extra features which may be the cause of my problem, but I'm not sure.
First the user inputs whether or not there are two-thousand yen bills in the register or not. (as these bills are not common).
Then you enter the total amount due. Then enter how much was paid. it then calculates the change and how much of each denomination and then displays it.
However, after you enter the amount paid, the cursor goes to the next line and just sits there indefinitely. I don't know what's causing this. My only guess is that it's getting stuck in a loop somewhere.
Does anyone see a problem? (*I switched the text to be printed to English)
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main(void)
{
//入力
int aru;
printf("Are there 2-thousand yen bills in the register?\n 1.) Yes\n 2.) No\n "); //レジに2千円札が入ってますか?\n 1.) 入ってます\n 2.)入ってません
scanf("%d", &aru);
int total, paid;
printf("Enter Total Price ");//お会計を記入して下さい。 
scanf("%d", &total);
printf("Enter Amount Paid ");//お客さんのお支払った合計を記入してください。
scanf("%d", &paid);
//計算
if (paid < total)
{
printf("Insufficiant amount paid\n");//お金を十分にもらいませんでした
}
if (paid > total)
{
int change = paid - total;
int ichi = 0, go = 0, ju = 0, goju = 0;
int hyaku = 0, gohyaku = 0, sen = 0, nisen = 0, gosen = 0;
while (change > 5000)
{
change - 5000;
gosen++;
}
while (change > 2000)
{
if (aru == 1)
{
change - 2000;
nisen++;
}
else
{
nisen = 0; //skips calculating 2000 yen bills if answer was 'no'
}
}
while (change > 1000)
{
change - 1000;
sen++;
}
while (change > 500)
{
change - 500;
gohyaku++;
}
while (change > 100)
{
change - 100;
hyaku++;
}
while (change > 50)
{
change - 50;
goju++;
}
while (change > 10)
{
change - 10;
ju++;
}
while (change > 1)
{
change - 1;
ichi++;
}
//出力
printf(" %d \n", gosen);
printf(" %d \n", nisen);
printf(" %d \n", sen);
printf(" %d \n", gohyaku);
printf(" %d \n", hyaku);
printf(" %d \n", goju);
printf(" %d \n", ju);
printf(" %d \n", go);
printf(" %d \n", ichi);
}
return 0;
}
while (change > 5000) //This is an infinite loop
{
change - 5000; //no change is made to change
gosen++;
}
You might want change -= 5000; instead of change - 5000;
This is at several places in your code.
change-=5000 is equivalent to
change = change-5000;

Nested if loop in for loop

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

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

Resources