#include <stdio.h>
int main(void)
{
int num, i, total, average, min, max;
min = num;
max = num;
FILE *ifile;
ifile = fopen("scores.txt", "r");
i = total = 0;
while (fscanf(ifile, "%d", &num) != EOF) {
i++;
total += num;
}
printf("The total of the integers is %d.\n", total);
printf("The number of integers in the file is %d.\n", i);
average = total/i;
printf("The average of the integers is %d.\n", average);
while (fscanf(ifile, "%d", &num) != EOF) {
if (num < min) {
printf ("The minimum is %d\n", min);
} else if (num > max) {
printf ("The maximum is %d\n", max);
}
}
fclose(ifile);
return (0);
}
The part of the code that's wrong is the very end about mins/maxes.
I'm not sure whether to put in a loop for this or to even make min and max variables themselves.
There are at least three issues in your min/max-detection loop:
First, as indicated by chux, min and max are not initialized; hence, when iterating through the numbers, statement if (num < min)... is far from guaranteed to work properly (same for max, of course).
So initialize min with INT_MAX, and initialize max with INT_MIN (both defined in <limits.h>), such that already in the first iteration min and max will be set to values from your file.
Second, the check for if (num < min)... gives you a "local" minimum, i.e. the minimum for all the numbers read so far, but not the "absolute" minimum, as there may come smaller numbers at a later point. So min/max will be valid at the end of the loop, not during the iteration.
Third, if (num < min) ... else if (num > max) is wrong at least if the file contains just one number.
Your code could look like the following:
int min = INT_MAX;
int max = INT_MIN;
while (fscanf(ifile, "%d", &num) != EOF) {
if (num < min)
min = num;
if (num > max)
max = num;
}
// min/max are valid earliest at this point:
printf ("The minimum is %d\n", min);
printf ("The maximum is %d\n", max);
// Note that min/max will not be correct if the file does not contain any number;
// Note further, that fscanf(ifile, "%d", &num) != EOF may result in an endless loop if the file contains characters that "%d" will not read as a valid integral value.
// But this is left to the OP for further improvement :-)
Consider the following modification to your code:
#include <stdio.h>
int main(void) {
int num, i, total, average, min, max;
// open file
FILE *ifile = fopen( "scores.txt", "r" );
// if opening file fails, print error message and exit 1
if (ifile == NULL) {
perror("Error: Failed to open file.");
return 1;
}
// initialize i and total to zero.
i = total = 0;
// read values from file until EOF is returned by fscanf,
// or until an error (hence the comparison "== 1")
while(fscanf(ifile, "%d", &num) == 1) {
// In first round of loop, initialize min and max
// to the number being read (num)
// After min/max have been initialized, they can then
// be compared and modified in the second if statement
// in the remaining loop rounds
if (i == 0) {
min = num;
max = num;
total += num;
++i;
continue;
}
if (num < min) {
min = num;
} else if (num > max) {
max = num;
}
total += num;
++i;
}
// initialize average
average = total/i;
// summary
printf("The sum of all integers in file is %d.\n", total);
printf("The number of integers in file is %d.\n", i);
printf("The average of all integers in file is %d.\n", average);
printf ("The minimum is %d\n", min);
printf ("The maximum is %d\n", max);
fclose(ifile);
return 0;
}
Related
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'm trying to construct a program that will take a users positive input for number of values then scan for the users values and state those values (which can be negative), but if the user enters any letters the program is supposed to skip over them in the list of values. I also can't figure out how to have the program skip over a negative number for the number of values if accidentally inputed (in the first example -4 is accidentally inputed for number of values and skipped, then 4 is used for number of values followed by each value). I would appreciate the help!
Here is what I have so far:
#include <stdio.h>
#include <ctype.h>
int main() {
int i;
double userVal;
double userNum;
double min = 0;
double max = 0;
double sum = 0;
double average;
scanf("%lf", &userVal);
for (i = 1; i <= userVal; ++i) {
scanf("%lf", &userNum);
sum += userNum;
if (i == 1 || min > userNum)
min = userNum;
if (i == 1 || max < userNum)
max = userNum;
}
average = sum / userVal;
printf("The minimum value is %g, the maximum value is %g, and the average value is %g.\n",
min, max, average);
return 0;
}
Picture of output: https://i.stack.imgur.com/8q4YC.png
You can (and should) use the return from scanf. It returns the number of successful scans. It also returns EOF if there was an error.
#include <stdio.h>
#include <stdlib.h>
#include <float.h>
// helper function to read all characters up to and including a new line
void consume_line()
{
int c;
while ((c = getchar()) != '\n') {
// Error??
if (c == EOF) {
// Handle error. Maybe exit program?
puts("ERROR");
exit(0);
}
}
}
int main() {
int count;
double min = DBL_MAX;
double max = DBL_MIN;
double sum = 0;
do {
// Read an int. If failure, discard input
if (scanf("%d", &count) != 1) {
consume_line();
count = -1;
}
} while (count <= 0); // Loop until count > 0
int count2 = count; // Use a copy since count is needed later
while (count2 > 0) {
double userNum;
if (scanf("%lf", &userNum) == 1) {
// Success
sum += userNum;
count2--;
if (min > userNum) min = userNum;
if (max < userNum) max = userNum;
}
else {
// Failure
consume_line();
}
}
double average = sum / count;
printf("The minimum value is %g, the maximum value is %g, and the average value is %g.\n",
min, max, average);
return 0;
}
This is supposed to ask the user to input a number than if the number is positive it outputs the number and adds one to the count and outputs the value of count (just for the most recent input value). if the number input is negative it just asks for a new number and if the input is 0 it outputs the count, minimum, maximum, sum and average for the entire run of the program.
I've gotten most of it working I'm just having trouble with getting the minimum value for the 0 scenario. I also get a runtime error for int min
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main() {
int input = 7;
int count = 0;
int sumInput = 0;
int lastInupt = 0;
int max;
int min;
double avg;
while (input != 0) {
printf("enter a number\n");
scanf("%i", &input);
if (input > 0) {
count++;
printf("\ninput = %i", input);
printf("\ncount = %i\n", count);
/*input1 = input;*/
sumInput += input;
//lastInupt = input;
}
else if (input < 0) {
printf("\ninput = %i", input);
printf("\ncount = %i\n", count);
}
if (input > lastInupt) {
if (input > max) {
max = input;
/*input1 = input;*/
}
}
if (lastInupt > input) {
if (min > input){
min = input;
}
}
/*while (min > 0)
{
if (input < min) {
min = input1;
}
}*/
}
avg = (float)sumInput / (float)count;
printf("you have entered %i positive numbers..\n", count);
printf("Sum of inputs: %i", sumInput);
printf("\nThe maximum # is: %i", max);
printf("\nThe average is: %.2lf", avg);
printf("\nThe minimum # is: %i", min);
getchar();
getchar();
return 0;
}
The code has to keep the same general format this is an assignment for my college.
Consider initializing both min and max and skip the lastInput variable.
int min = INT_MAX;
int max = INT_MIN;
.....
if (input > max)
max = input;
if (min > input)
min = input;
This should ensure that min and max are always initialized, and in the special case where the first and only input is 0 both min and max will get the value 0.
Because you initialize min to MAX_INT (the highest possible value for an int variable) the first iteration min > input will always evaluate to true and min will be updated. Similar for max and MIN_INT
if min and max only should be updated when input !=0 then modify the entire program to
int main() {
int input = 7;
int count = 0;
int sumInput = 0;
int max = INT_MIN;
int min = INT_MAX;
double avg;
while (input != 0) {
printf("enter a number\n");
scanf("%i", &input);
if (input > 0) {
count++;
printf("\ninput = %i", input);
printf("\ncount = %i\n", count);
sumInput += input;
if (input > max ) max = input;
if (input < min ) min = input;
}
else if (input < 0) {
printf("\ninput = %i", input);
printf("\ncount = %i\n", count);
}
}
if(count==0) { // only 0 entered.
printf("inform user she didnt enter any positive numbers");
} else {
avg = (float)sumInput / (float)count;
printf("you have entered %i positive numbers..\n", count);
printf("Sum of inputs: %i", sumInput);
printf("\nThe maximum # is: %i", max);
printf("\nThe average is: %.2lf", avg);
printf("\nThe minimum # is: %i", min);
}
getchar();
getchar();
return 0;
}
Since your runtime error was fixed, I will address the min == 0 issue.
When a 0 is input, it will fail the two first if statements input>0 and input < 0
But it still will try the last two if statements, and of course 0 will be less than the current min, so it will set min to 0 (incorrectly)
What you need to do is put this after the else if(input < 0) block
else{//input is 0
break;
}
So that it will skip checking if input is below min when input is 0. As you want to break from the loop at this point anyway.
I have been tasked with writing a code that reads numbers in from a txt file array and finding the max, min, sum etc. The (200) numbers are in the format:
3.23
19.398
98.73
2.1
...
Sorry if the code is a bit of a mess, I've been trying to piece together a lot of different tutorials to no avail. I basically need to know how to get the code to read the values sequentially, and pull out the max/min values and keep going through the array. (and find sum along the way) How do I format this correctly?
# include <stdio.h>
int main()
{
//char data[200];
int newnum;
int max = 0, min = 99999999999;
int i = 0;
int y[200];
//min=max=newnum;
FILE *fpdata = fopen("data.txt", "r");
if((fpdata = fopen("data.txt", "r")) == 0)
{
printf("File not found. Abort!");
exit(-1);
}
while(fscanf(fpdata,"%f", &y[i++]) != EOF);{
//for(i=0; i < 200; i++)
i--;
printf("i=%d \n", i);
//printf("\n%d%d\n", &y[i++], y);
if(newnum > max)
max = newnum;
if(newnum < min)
min = newnum;
}
printf("The largest number is %d\n", max);
printf("The smallest number is %d\n", min);
fclose(fpdata);
return 0;
}
Any help would be greatly appreciated, I've tried utilizing all possible resources (youtube, other stackoverflow questions) for hours but none explicitly lay out how to format the call in array from the file, read, and pluck values from it.
There are many issues:
You probably want this:
#include <stdio.h>
#include <stdlib.h> // include also stdlib.h
int main()
{
float newnum;
float max = 0, min = 99999999999; // use float type for float numbers
int i = 0;
FILE *fpdata; // callign fopen only once
if ((fpdata = fopen("data.txt", "r")) == 0)
{
printf("File not found. Abort!");
exit(-1);
}
while (fscanf(fpdata, "%f", &newnum) != EOF) { // removed extra ;
printf("i = %d, newnum = %f\n", i++, newnum); // reading into newnum
// correct format specifiers
if (newnum > max)
max = newnum;
if (newnum < min)
min = newnum;
}
printf("The largest number is %f\n", max); // correct format specifiers
printf("The smallest number is %f\n", min);
fclose(fpdata);
return 0;
}
There is still room for improvments though.
Here is the version that first reads all the data into the data array (data is a nicer name than y) and then does the calculation:
#include <stdio.h>
#include <stdlib.h>
int main()
{
float max = 0, min = 99999999999;
float data[200];
FILE *fpdata;
if ((fpdata = fopen("input1.txt", "r")) == 0)
{
printf("File not found. Abort!");
exit(-1);
}
int nbofnumbers = 0;
while (fscanf(fpdata, "%f", &data[nbofnumbers]) != EOF)
{
nbofnumbers++;
}
for (int i = 0; i < nbofnumbers; i++)
{
printf("data[%d] = %f\n", i, data[i]);
if (data[i] > max)
max = data[i];
if (data[i] < min)
min = data[i];
}
printf("The largest number is %f\n", max);
printf("The smallest number is %f\n", min);
fclose(fpdata);
return 0;
}
Some issues with your code:
You scan for float but store data as int
You open the file twice
You have an unintended ; at the end of the while
The loop condition (i.e. != EOF) may cause an infinite loop in the file contains something that can't be parsed as a float. Using == 1 is safer.
Your initialization of max and min can be improved
After fixing that the program could be:
#include <stdio.h>
#include <stdlib.h>
#include <float.h>
int main(void)
{
float newnum;
float max = -FLT_MAX;
float min = FLT_MAX;
FILE *fpdata;
if((fpdata = fopen("data.txt", "r")) == 0)
{
printf("File not found. Abort!");
exit(-1);
}
while(fscanf(fpdata,"%f", &newnum) == 1)
{
printf("%f\n", newnum);
if(newnum > max) max = newnum;
if(newnum < min) min = newnum;
}
printf("The largest number is %f\n", max);
printf("The smallest number is %f\n", min);
fclose(fpdata);
return 0;
}
I am trying to make a program that will convert a number into its prime factorization. For example, 2048=2^11 the program will output 211 (since this value will be used in a different function.). The program then prints the prime factorization and the number in a file. The issue I'm having is having the two functions, digitCount and FdigitCount, run in a loop and read the values from the file and then compare the amount of digits in the prime factorization to the number of digits in the normal number, then if it is less, printing the numbers out.
int digitCount(int n){
int digits = 0;
while(n!=0) {
n/=10; //divides the number by 10 and adds one to the digits until it is no longer divisible by 10.
++digits;
}
return digits;
}
int fdigitCount(int p){ //this function is used the count the digits of the prime factorization.
int fdigits = 0;
while(p!=0) {
p/=10; //divides the number by 10 and adds one to the fdigits until it is no longer divisible by 10.
++fdigits;
}
return fdigits;
}
int main(void) {
FILE* primes = NULL; //file pointer to the file that will contain all the prime factors of a number
int num;
int count;
int digits;
int limit;
int i;
int j=2;
int fdigits;
int frugalNum;
int normNum;
primes = fopen("primes.txt", "w+");
if (primes == NULL){
printf("Could not open primes.txt");
}
printf("Enter a limit: ");
scanf("%d", &limit);
for (i=2; i <= limit; i++){
num = i;
j = i;
count = 0;
if (num%2 == 0){
while (num%2 == 0)
{
num = num/2;
count++;
}
if (count > 1){
fprintf(primes, "2%d", count);
}
else {
fprintf(primes, "2");
}
}
else if(num%2 != 0) {
for (int i = 3; i <= sqrt(num); i = i+2)
{
// While i divides n, print i and divide n
count = 0;
while (num%i == 0)
{
num = num/i;
count++;
}
if (count > 1){
fprintf(primes, "%d%d", i, count);
}
else if (count==1){
fprintf(primes, "%d", i);
}
}
}
if (num > 2){
fprintf (primes, "%d", num);
}
fprintf(primes, " %d", j);
fprintf(primes, "\n");
}
while (!feof(primes)){
fscanf(primes, "%d %d", &frugalNum, &normNum);
if (fdigitCount(frugalNum) < digitCount(normNum)){
printf("%d\n", normNum);
}
}
fclose(primes);
return 0;
}
You shouldn't read the file by looping until feof() returns true. It returns true after you've passed the EOF, and so the last values you read will be garbage. Change your loop to:
while (fscanf(primes, "%d %d", &frugalNum, &normNum) == 2) {
/* Do stuff with frugalNum and normNum */
}
Additionally, I couldn't help noticing that digitCount() and fdigitCount() do exactly the same thing. Why do you need both of them?