I've been trying to do an error check for my program, for scanf using a while loop, but I am unsure of how to do this.
I want to make sure the user inputs between 4 and 8 for number of judges, and the score doesn't go below 0 or above 10.
could someone please help me out?
Thanks!
#include <stdio.h>
int i,j,k, judges;
float max, min,total;
int main(){
max = 0.0;
min = 10.0;
judges = 0;
total = 0;
printf("Enter number of judges between 4-8: ");
scanf("%d", &judges);
float scores[judges];
for(i = 0; i < judges; i++){
printf("Enter a score for judge %d : ", i + 1);
scanf("%5f", &scores[i]);
}
for(j = 0; j < judges; j++){
if(min > scores[j]){
min = scores[j];
}
if (max < scores[j]){
max = scores[j];
}
}
for(k = 0; k < judges; k++){
total = total + scores[k];
}
total = total-max-min;
printf("max = %4.1f min = %4.1f total = total = %4.1f", min, max,total);
}
Try the following:
// for judge
while (1) {
printf("Enter number of judges between 4-8: ");
scanf("%d", &judges);
if (judges >= 4 && judges <= 8)
break;
else
puts("Judge out of range of 4 and 8.");
}
// for socres
for(i = 0; i < judges; i++){
while (1) {
printf("Enter a score for judge %d : ", i + 1);
scanf("%5f", &scores[i]);
if (scores[i] >= 0.0 && scores[I] <= 10.0)
break;
else
puts("score out of range of 0.0 and 10.0");
}
You just need to use do-while loops around the areas that you are checking. If the condition (in the while part) is not met, the loop will repeat and the user will be prompted again.
do{
printf("Enter number of judges between 4-8: ");
scanf("%d", &judges);
}while(judges < 4 || judges > 8);
Related
I need to input a matrix, where the first element of a row is the student ID number, and the other 12 elements are student points and GPA. Each row represents one student. What the program needs to do is calculate the total point amount, and then sort the matrix so it goes in descending order by the amount of points.
This is my code:
#include <stdio.h>
int main() {
int number_of_students,i,j;
double matrix[50][50],GPA,grades,total,GPA_before;
printf("Number of students: ");
scanf("%d", &number_of_students);
printf("Input students: ");
for(i=0; i<number_of_students; i++){
for(j=0; j<12; j++){
scanf("%lf", &matrix[i][j]);
}
}
printf("Final list: \n");
for(i=0; i<number_of_students; i++){
GPA_before=(matrix[i][2]+matrix[i][3]+matrix[i][4]+matrix[i][5])*2.5;
if(GPA_before==50){
GPA=GPA_before+3;
}
else{
GPA=GPA_before;
}
grades=(matrix[i][6]+matrix[i][7]+matrix[i][8]+matrix[i][9]+matrix[i][10]+matrix[i][11])*0.67;
total=GPA+grades+matrix[i][12];
printf("%d. %g | %g\n",i,matrix[i][1],total);
}
return 0;
}
And this is what I get:
Number of students: 4
Input students: 123456 4.00 4.50 5.00 5.00 5 5 5 4 4 5 15
456789 4.50 5.00 4.00 3.50 3 5 4 5 5 2 10
789321 5.00 5.00 4.50 3.00 5 4 5 3 5 3 15
456987 4.50 4.50 4.50 5.00 4 4 4 5 5 5 25
Final list:
1. 123456 | 80.01
2. 456789 | 68.58
3. 789321 | 75.5
4. 456987 | 89.34
The matrix should be sorted from highest number of points to the lowest, not by ID. It is specified not to sort the list while printing it out, the matrix itself must be sorted.
I would really appreciate the help.
Firstly, I saw a few things in your code that I would like to point out and change, if possible.
You are allocating an 2-D Array of 50 rows and 50 columns. However, you're only utilizing 12 of those columns. So, first thing that I would like you to fix is the use of those extra unnecessary array indexes. So, I wrote the following code:
const int MAX = 50;
const int NUM_INPUTS = 12;
int number_of_students, i, j;
double matrix[MAX][NUM_INPUTS + 1], GPA, grades, total;
Note: I added NUM_INPUTS + 1, that we will use to store the total of that you were calculating in the loop and also printing it too.
Now, another thing I would like to point out, is your use of loops. You're iteration is beginning from the index 1. You're not using the 0th index. So, you'll have to fix each loop from this:
for(i=1; i<=number_of_students; i++){
for(j=1; j<=12; j++){
scanf("%lf", &matrix[i][j]);
}
}
to this:
for (i = 0; i < number_of_students; i++) {
for (j = 0; j < NUM_INPUTS; j++) {
scanf("%lf", &matrix[i][j]);
}
}
Now, this indexing from 0 will cause the code that you wrote for the calculations, to not work properly, so, you will have to fix that too:
for(i=1; i<=number_of_students; i++){
GPA_before=(matrix[i][2]+matrix[i][3]+matrix[i][4]+matrix[i][5])*2.5;
if(GPA_before==50){
GPA=GPA_before+3;
}
else{
GPA=GPA_before;
}
grades=(matrix[i][6]+matrix[i][7]+matrix[i][8]+matrix[i][9]+matrix[i][10]+matrix[i][11])*0.67;
total=GPA+grades+matrix[i][12];
You were using this code in-junction with printf. I used this code to calculate the total and then store it in the index matrix[i][NUM_INPUTS].
Now, I slightly changed your code and loop for storing the total in the matrix itself becomes:
for (i = 0; i < number_of_students; i++) {
GPA = (matrix[i][1] + matrix[i][2] + matrix[i][3] + matrix[i][4]) * 2.5;
if (GPA == 50) {
GPA += 3;
}
grades = (matrix[i][5] + matrix[i][6] + matrix[i][7] + matrix[i][8] + matrix[i][9] + matrix[i][10]) * 0.67;
total = GPA + grades + matrix[i][11];
matrix[i][NUM_INPUTS] = total;
}
Now, this made it easy for me to implement a basic Bubble Sort algorithm to sort your matrix:
int k;
for (i = 0; i < number_of_students; i++) {
for (j = 0; j < number_of_students - 1; j++) {
if (matrix[j][NUM_INPUTS] > matrix[j + 1][NUM_INPUTS]) {
double temp;
for (k = 0; k < NUM_INPUTS + 1; k++) {
temp = matrix[j][k];
matrix[j][k] = matrix[j + 1][k];
matrix[j + 1][k] = temp;
}
}
}
}
Now, since the matrix itself has been sorted, we will simply print the final matrix:
for (i = 0; i < number_of_students; i++) {
printf("%d. %g | %g\n", i + 1, matrix[i][0], matrix[i][NUM_INPUTS]);
}
Note: One more thing you can do (totally for input validation) is write an if statement, that would check if the user input for number of students is in the range of 1 <= number_of_students <= MAX (50), if it is greater than that, it would cause an out-of-bounds exception or a Buffer Overflow.
if(number_of_students > MAX || number_of_students <= 0) {
printf("Invalid number of students");
return 1;
}
I hope you understood what I wrote and would love if you'd upvote as this is my first answer here.
Here's the full source code:
#include <stdio.h>
int main() {
const int MAX = 50;
const int NUM_INPUTS = 12;
int number_of_students, i, j;
double matrix[MAX][NUM_INPUTS + 1], GPA, grades, total;
printf("Number of students: ");
scanf("%d", &number_of_students);
if(number_of_students > MAX || number_of_students <= 0) {
printf("Invalid number of students");
return 1;
}
printf("Input students: ");
for (i = 0; i < number_of_students; i++) {
for (j = 0; j < NUM_INPUTS; j++) {
scanf("%lf", &matrix[i][j]);
}
}
// Firstly calculating the total and storing it in the final index of the matrix:
for (i = 0; i < number_of_students; i++) {
GPA = (matrix[i][1] + matrix[i][2] + matrix[i][3] + matrix[i][4]) * 2.5;
if (GPA == 50) {
GPA += 3;
}
grades = (matrix[i][5] + matrix[i][6] + matrix[i][7] + matrix[i][8] + matrix[i][9] + matrix[i][10]) * 0.67;
total = GPA + grades + matrix[i][11];
matrix[i][NUM_INPUTS] = total;
}
// Sorting this based on total:
for (i = 0; i < number_of_students; i++) {
for (j = 0; j < number_of_students - 1; j++) {
if (matrix[j][NUM_INPUTS] > matrix[j + 1][NUM_INPUTS]) {
double temp;
for (int k = 0; k < NUM_INPUTS + 1; k++) {
temp = matrix[j][k];
matrix[j][k] = matrix[j + 1][k];
matrix[j + 1][k] = temp;
}
}
}
}
printf("Final list:\n");
for (i = 0; i < number_of_students; i++) {
printf("%d. %g | %g\n", i + 1, matrix[i][0], matrix[i][NUM_INPUTS]);
}
return 0;
}
The problem is I can't get the proper GPA. I am suspecting the divisions and type conversions. Below is the exact question I'm trying to do but I would like to learn what am I missing with my code.
https://imgur.com/a/HFrIO - They don't mention about credits so I simply ask it from the user in the program.
Edit: As seen from the question above, it should calculate the GPA but when I try with marks 50, 60, 70 respectively and 3 credits for each course, I get no sense outputs like 0.
(Original assignment wants 30 students and 5 courses but I defined them and changed them to 2 courses 1 student in order to test it in runtime.)
#include <stdio.h>
#define NUMBER_OF_COURSES 2 // Homework asks for 5, change at the end
#define NUMBER_OF_STUDENTS 1 // Homework asks for 30, change at the end
void calculateCourse(int *letterGradePoints, int *credit); // Func. prototype
float calculateStudentGpa(); // Func. prototype
int main()
{
// Store gpa s of students in an array
float studentGpas[NUMBER_OF_STUDENTS];
int i;
for(i = 0; i < NUMBER_OF_STUDENTS; ++i)
{
/*DEBUG*/printf("----\nPROGRAM IS IN MAIN FOR LOOP\n----\n");
studentGpas[i] = calculateStudentGpa();
}
// Print all gpas
for(i = 0; i < NUMBER_OF_STUDENTS; ++i)
{
printf("\nGPA of student %d is : %d ", i + 1, studentGpas[i]);
}
// Find min gpa
int min = studentGpas[0];
for(i = 1; i < NUMBER_OF_STUDENTS; ++i)
if(min > studentGpas[i])
min = studentGpas[i];
// Find max gpa
int max = studentGpas[0];
for(i = 1; i < NUMBER_OF_STUDENTS; ++i)
if(max < studentGpas[i])
max = studentGpas[i];
// Print min and max
printf("Min gpa is : %d Max gpa is : %d", min, max);
return 0;
}
float calculateStudentGpa()
{
/*DEBUG*/printf("\nPROGRAM IS IN calculateStudentGpa FUNCTION");
/* Dealing with a single students gpa */
int credit[NUMBER_OF_COURSES];
int letterGradePoints[NUMBER_OF_COURSES];
int i; int debug = 0;
for(i = 0; i < NUMBER_OF_COURSES; ++i)
{
/*DEBUG*/ if(debug == 0) { /*DEBUG*/printf("\nPROGRAM IS IN calculateStudentGpa FUNCTION for LOOP\n"); debug++; } // Print this one once
calculateCourse(&letterGradePoints[i], &credit[i]);
/*DEBUG*/printf("\nPROGRAM IS IN calculateStudentGpa FUNCTION for LOOP\n");
/*DEBUG*/printf("\n[DEBUG] i in calculateStudentGpa : %d", i);
/*DEBUG*/printf("\n[DEBUG] letterGradePoints[i] in calculateStudentGpa : %d", letterGradePoints[i]);
/*DEBUG*/printf("\n[DEBUG] credit[i] in calculateStudentGpa : %d\n", credit[i]);
}
/*DEBUG*/printf("\nPROGRAM HAS ..PASSED.. calculateStudentGpa FOR LOOP");
float gpa; float up = 0; float down = 0;
/* Either we need to have
* (i = 0; i < NUMBER_OF_COURSES; ++i) AND indexes of arrays as i
* or
* (i = 1; i <= NUMBER_OF_COURSES; ++i) AND indexes of arrays as i - 1
* below in 2 for loops!!!!
*/
for(i = 0; i < NUMBER_OF_COURSES; ++i)
{
up += (letterGradePoints[i] * credit[i]); // Might need (float)
}
for(i = 1; i <= NUMBER_OF_COURSES; ++i)
{
down += credit[i - 1];
}
gpa = up / down;
/* We are done with a single student, we need all 30 students */
return gpa;
}
void calculateCourse(int *letterGradePoints, int *credit)
{
/*DEBUG*/printf("\n--------------------------------------");
/*DEBUG*/printf("\nVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV");
/*DEBUG*/printf("\nPROGRAM IS IN calculateCourse FUNCTION\n");
/* Dealing with a single course */
int labMark, midtermMark, finalMark;
printf("\nEnter lab mark : ");
scanf("%d", &labMark);
printf("Enter midterm mark : ");
scanf("%d", &midtermMark);
printf("Enter final mark : ");
scanf("%d", &finalMark);
float average =
(
(float) (0.5 * finalMark)
+
(float) (0.4 * midtermMark)
+
(float) (0.1 * labMark)
); // Might need (float)
/*DEBUG*/printf("\n[DEBUG] average : %f", average);
// int letterGradePoints; // I decided to use pass by reference in order to return 2 values
if(average >= 0) *letterGradePoints = 0;
if(average >= 50) *letterGradePoints = 1;
if(average >= 60) *letterGradePoints = 2;
if(average >= 70) *letterGradePoints = 3;
if(average >= 80) *letterGradePoints = 4;
/*DEBUG*/printf("\n[DEBUG] letterGradePoints in calculateCourse : %d\n", *letterGradePoints);
// int credit; // I decided to use pass by reference in order to return 2 values
printf("Enter the credit for the course : ");
scanf("%d", credit);
/*DEBUG*/printf("\n[DEBUG] *credit in calculateCourse : %d\n", *credit);
/*DEBUG*/printf("/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\\n");
/*DEBUG*/printf("--------------------------------------\n");
/* We are done with a single course, we need all 5 courses for the gpa */
}
You're printing the GPA as an integer instead of as a floating point number. Change
printf("\nGPA of student %d is : %d", i + 1, studentGpas[i]);
to
printf("\nGPA of student %d is : %f", i + 1, studentGpas[i]);
Look here for a list of format specifiers used by printf.
I am trying to calculate the mean of high and low temperatures entered by a user and the number of days that can be included are between 1 and 4 however, I'm having difficulty understanding how to go about this. The code I wrote yields a completely irrelevant number. Here's my code:
#include <stdio.h>
int main (void)
{
int i;
int limit;
int day[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int high[10],low[10];
printf("---===IPC Temperature Analyzer V2.0===---\n");
printf("Please enter the number of days between 3 and 10, inclusive: ");
scanf("%d", &limit);
while (limit <= 2 || limit >= 11) {
printf("Invalid entry, please enter a number between 3 and 10, inclusive: ");
scanf("%d", &limit);
}
for(i = 0;i < limit; i++) {
printf("Day %d - High: ", day[i]);
scanf("%d", &high[i]);
printf("Day %d - Low: ", day[i]);
scanf("%d", &low[i]);
}
printf("\nDay Hi Low\n");
for (i = 0; i < limit; i++) {
printf("%d %d %d\n", day[i], high[i], low[i]);
}
int max = 0;
int min = 0;
for (i = 0; i < limit; i++) {
if (high[max] < high[i])
max = i;
if (low[min] < low[i])
min = i;
}
printf("\nHighest temperature was: %d on day %d", high[max], day[max]);
printf("\nLowest temperature was: %d on day %d ", low[min], day[min]);
int n;
int avg = high[i] + low[i]/i;
printf("\nEnter a number between 1 and 4 to see the average temperature for the entered number of days, enter a negative number to exit\n");
scanf("%d", &n);
while (n > 4) {
printf("Invalid entry, please enter a number between 1 and 4, inclusive: ");
scanf("%d", &n);
}
while (n < 0) {
printf("Goodbye!\n");
exit(0);
}
for (i = 0; i < n; i++) {
printf ("The average temperature up to day %d is: %d", day[i], avg);
}
return 0;
}
I suppose you misplaced expression int avg = high[i] + low[i]/i, and also the meaning does not seem correct to me:
First: I suppose you want to print the average for each particular day in the loop i : 0..n-1, but you calculate the value only once outside the loop (and you may think of what i at your place means.
Second: You have only two values for each day, i.e. high and low, and not i values, right? So to get the average temperature for a particular day it should be avg = (high[i] + low[i])/2. Also note the braces, which yields a different operator precedence than in your code. And if you want to calculate an "overal" avg up to a particular day, I'd make the formula explicit, e.g. by distinguishing an averageOfDay from an overallAverage.
Third: are you sure avg should be an int? I'd suggest to use float.
float avgSum = 0.0;
for (i = 0; i < n; i++) {
float avgOfDay = (high[i] + low[i])/2.0;
avgSum += avgOfDay;
}
float overallAvg = avgSum/n;
printf ("The average temperature up to day %d is: %f", day[n-1], overallAvg);
#include <stdio.h>
main()
{
int choice, no;
printf("1. Show sum of odd/even number to N term\n");
printf("2. Smallest, largest and average of the supplied numbers\n");
printf("3. Terminate the programs\n\n");
printf("Enter your choice[1|2|3]: ");
scanf("%d", &choice);
if (choice == 1)
{
int i , no , sum = 0, j, sum2 = 0;
printf("\nEnter any number: ");
scanf("%d", &no);
for (i = 2; i <= no; i = i + 2)
{
sum = sum + i;
}
printf("\nSum of all even number between 1 to %d = %d\n", no, sum);
for (j = 1; j <= no; j = j + 2)
{
sum2 = sum2 + j;
}
printf("Sum of all odd number between 1 to %d = %d\n", no, sum2);
}
else if(choice == 2)
{
float max, min, avg, num,counter=0, sum = 1;
printf("\nPlease enter all the number you want![0 to end]: ");
scanf("%f", &num);
max = min = num;
while (num != 0)
{
printf("Please enter all the number you want![0 to end]: ");
scanf("%f", &num);
if (max < num && num > 0)
max = num;
else if (min > num && num > 0)
min = num;
sum = sum + num;
counter++;
}
printf("\nThe smallest and largest of entered numbers are %.2f and %.2f respectively.\n", min, max);
avg = sum / counter;
printf("The sum of entered number is %.2f\n", sum);
printf("The average of entered number is %.2f\n", avg);
}
}
My problem is when i choose number 2 it will show smallest and largest number but the sum show wrongly when i enter large number like 200! But it work fine when i enter small value!?
small number
Big number
picture included
Your sum has never count the first input. With initial value sum = 1,
For your small numbers: your sum = (1 + 1 + 1 + 2) happens to be right.
But for your big numbers: your sum = (1 + 100 + 100 + 200 ) = 400.1 (you can see you missed the first input 100);
Your mistakes:
sum should be initialized as 0;
you did not count the first input (before loop): not calc sum nor counter++
when user finally input 0, you should not continue counter++ because '0' is not a valid input.
Your program has several issues:
You initialise the sum to 1, not to 0 as it ought to be.
You handle the first value and subsequent values differently. This is basically okay, but make sure that the treatment is the same in bothz cases. In your code, you assign min and max for the first value correctly, but miss incrementing the sum and the counter.
Your code doesn't check whethet a valid float has been entered. That means that it will hang if the user enters something that isn't a float. Your program should handle such input as if it were zero.
In theory, you should not divide by counter when it is zero. In practice, that doesn't happen, because you also account for the terminating zero in your counter.
Perhaps it would be better to treat the first value like all other values. You could then either initialise min and max to big and small values (for example ±FLT_MAX from <float.h>) or you could check count == 0 inside the loop to implement diferent behaviour for the first and the following values.
In that case, you could break out of an infinite loop when invalid input or zero was given. This might seem complicated, but leads to simpler code:
#include <stdio.h>
#include <float.h>
int main(void)
{
float max = -FLT_MAX; // minimum possible float value
float min = FLT_MAX; // maximum possible float value
float sum = 0.0f;
int count = 0;
for (;;) {
float num;
printf("Please enter all the number you want![0 to end]: ");
if (scanf("%f", &num) < 1 || num == 0) break;
if (max < num) max = num;
if (min > num) min = num;
sum += num;
count++;
}
if (count) {
float avg = sum / count;
printf("%d values\n", count);
printf("Smallest: %.2f\n", min);
printf("Largest: %.2f\n", max);
printf("Sum: %.2f\n", sum);
printf("Average: %.2f\n", avg);
}
return 0;
}
#include <stdio.h>
main()
{
int choice = 0;
for (;choice != 3;)
{
printf("_____________________________________________________________\n\n");
printf("1. Show sum of odd/even number to N term\n");
printf("2. Smallest, largest and average of the supplied numbers\n");
printf("3. Terminate the programs\n\n");
printf("Enter your choice[1|2|3]: ");
scanf("%d", &choice);
printf("_____________________________________________________________\n\n");
if (choice == 1)
{
int i, no, sumc1 = 0, j, sum2c1 = 0;
printf("\nEnter any number: ");
scanf("%d", &no);
for (i = 2; i <= no; i = i + 2)
{
sumc1 = sumc1 + i;
}
printf("\nSum of all even number between 1 to %d = %d\n", no, sumc1);
for (j = 1; j <= no; j = j + 2)
{
sum2c1 = sum2c1 + j;
}
printf("Sum of all odd number between 1 to %d = %d\n\n\n", no, sum2c1);
}
else if (choice == 2)
{
float counter, num, large, small, num2, sum = 0, avg;
printf("\nEnter first number[Enter 0 to stop]: ");
scanf("%f", &num);
num2 = num;
large = num;
small = num;
for (counter = 0; num != 0; counter++)
{
printf("Enter another number [Enter 0 to stop]: ");
scanf("%f", &num);
if (num > large && num > 0)
large = num;
if (num<small && num > 0)
small = num;
sum = sum + num;
}
sum = sum + num2;
avg = sum / counter;
printf("\nThe largest number is %.2f\n", large);
printf("The smallest number is %.2f\n", small);
printf("The sum of entered numbers are %.2f\n", sum);
printf("The average of entered number are %.2f\n\n\n", avg);
}
}
}
I just figured out the main problem thanks to all, although some of replies gave me full code, i have to use just simple code because i only started to learn the basic. thanks.
this code might be useful for someone.
//uniten.encik//
I'm doing an online course on "Programming, Data Structure & Algorithm". I've been given an assignment to "find the most frequent element in a sequence using arrays in C (with some constraints)". They've also provided some test-cases to verify the correctness of the program. But I think I'm wrong somewhere.
Here's the complete question from my online course.
INPUT
Input contains two lines. First line in the input indicates N,
the number of integers in the sequence. Second line contains N
integers, separated by white space.
OUTPUT
Element with the maximum frequency. If two numbers have the
same highest frequency, print the number that appears first in the
sequence.
CONSTRAINTS
1 <= N <= 10000
The integers will be in the range
[-100,100].
And here's the test cases.
Test Case 1
Input:
5
1 2 1 3 1
Output:
1
Input:
6
7 7 -2 3 1 1
Output:
7
And here's the code that I've written.
#include<stdio.h>
int main()
{
int counter[201] = {0}, n, i, input, maximum = 0;
scanf("%d", &n);
for(i = 1; i <= n; i++) {
scanf("%d", &input);
if(input < -100 && input < 100)
++counter[input];
}
maximum = counter[0];
for (i = 1; i < 201; i++) {
if (counter[i] > maximum) {
maximum = counter[i];
}
}
printf("%d", maximum);
return 0;
}
Please tell me where I'm wrong. Thank you.
EDIT:
I've modified the code, as suggested by #zoska. Here's the working code.
#include<stdio.h>
int main()
{
int counter[201] = {0}, n, i, input, maximum = 0;
scanf("%d", &n);
for(i = 1; i <= n; i++) {
scanf("%d", &input);
if(input < 100 && input > 0)
++counter[input + 100];
else
++counter[input];
}
maximum = counter[0];
for (i = 0; i < 201; i++) {
if (counter[i] > maximum) {
maximum = i - 100;
}
}
printf("%d", maximum);
return 0;
}
Additionally to problem pointed out by Paul R is:
You are printing maximum occurrences of number, not the number itself.
You're going to need another variable, which will store the number with maximum occurences. Like :
maximum = count[0];
int number = -100;
for (i = 0; i < 201; i++) {
if (counter[i] > maximum) {
maximum = counter[i];
number = i - 100;
}
}
printf("number %d has maximum occurences: %d", number, maximum);
Also you should iterate through an array from 0 to size-1:
So in all cases of your loops it should be :
for(i = 0; i < 201; i++)
Otherwise you won't be using count[0] and you will only have a range of -99...100.
Try below code
#include<stdio.h>
int main()
{
int counter[201] = {0}, n, i, input, maximum = 0;
scanf("%d", &n);
for(i = 1; i <= n; i++) {
scanf("%d", &input);
if(input >= -100 && input <= 100)
++counter[input + 100];
}
maximum = counter[0];
int index = 0;
for (i = 0; i < 201; i++) {
if (counter[i] >= maximum) {
index = i;
maximum = counter[i];
}
}
printf("number %d occured %d times\n", index-100, maximum);
return 0;
}
I would prefer checking in one loop itself for the maximum value just so that the first number is returned if i have more than one element with maximum number of occurances.
FInd the code as:
#include<stdio.h>
int main()
{
int n,input;
scanf("%d",&n);
int count[201] ={0};
int max=0,found=-1;
for(int i=0;i<n;i++)
{
scanf("%d",&input);
count[input+100]++;
if(max<count[input+100])
{
max= count[input+100];
found=input;
}
}
printf("%d",found);
return 0;
}
But, there is also one condition that if the number of occurance are same for two numbers then the number which appers first in sequence should appear.