I'm writing a program to read numbers from a file and then print out the largest and second largest numbers in that file.
What am I doing wrong? Thanks for the help.
#include <stdio.h>
#include <stdlib.h>
#define SIZE 50
int main()
{
int values[SIZE],
largest,
second_largest,
newest;
int count = 0;
int i;
FILE *input_file_ptr;
input_file_ptr = fopen("data.c","r");
if (input_file_ptr == NULL)
{
printf("The data file couldn't be opened.\n");
return 0;
}
else /*read the file into the array*/
{
while (fscanf(input_file_ptr;"%d", &newest)==1)
{
values[count] = newest;
count++;
}
}
/*search for the largest element*/
switch(count)
{
case 0: printf("No largest or second largest.");
break;
case 1: printf("The largest number is %d.\n",values[0]);
printf("There is not a second largest.\n");
break;
case 2: if (values[0]< values[1])
{
printf("Largest is %d, second largest is %d.",
values[1],values[0]);
break;
}
else (values[0]> values[1])
{
printf("Largest is %d, second largest is %d.",
values[0],values[1]);
break;
}
default: break;/*cases larger than 2*/
}
largest = values[0];
second_largest = values[0];
for (i=1; i < 50; i++)
{
{ if (values[i]>largest)
largest = values[i];
else if (values[i]== largest)
largest = second_largest;
else if (values[i]> second_largest)
second_largest = values[i];
}
if (largest == second_largest)
{
printf("The largest and second largest are the same");
printf(" number: %d.\n",largest);
}
else if (largest != second_largest)
{
printf("The largest number is: %d.\n",largest);
printf("The second largest number is: %d.\n",second_largest);
}
}
return 0;
}



LinkBack URL
About LinkBacks



