I need to make a user enter the N (the number) between 7 and 12 ([7;12]). Then, I need to make the user enter the amount of numbers, which should be equal to N. Then, I need to output the sum of these numbers, find the average, min and max.
It works perfectly, except the minimum. When the count of numbers starts from 1, my program shows me that the minimum is 0. Thank you ahead...
#include <stdio.h>
int main(void) {
int i = 0;
int N;
float numbers;
float sum = 0;
float average, min, max;
printf("Choose a number between 7 and 12: ");
scanf("%d", &N);
if (N >= 7 && N <= 12) {
printf("You have chosen: %d\n", N);
printf("Now choose the amount of N numbers you have chosen: ");
for (i = 0; i < N; i++) {
numbers = N; // the numbers the user enters must be
// strictly == N
scanf("%f", &numbers);
sum = sum + numbers;
average = sum / numbers;
if (numbers < min) {
min = numbers;
}
if (numbers > max) {
max = numbers;
}
}
printf("The sum of your numbers is: %f\n The average of "
"numbers: %f\n The max: %f\n The min: %f\n",
sum, average, max, min);
}
}
The output is:
Choose a number between 7 and 12: 7
You have chosen: 7
Now choose the amount of N numbers you have chosen: 1
2
3
4
5
6
7
The sum of your numbers is: 28.000000
The average of numbers: 4.000000
The max: 7.000000
The min: 0.000000
Your min and max values are used uninitialized. On your platform/compiler, it appears that these are being default initialized to zero, but the C Standard does not require that.
To fix this issue, just initialize those variables (at the time of their declarations) to values that cannot be the final values (like the +/- values of the FLT_MAX constant, defined in <float.h>):
//...
float average, min = FLT_MAX, max = -FLT_MAX;
//...
I would go about this in a completely different fashion. Store the numbers in an array and then sort them. This is an example using integers, but it is very easy to modify for float usage.
#include <stdio.h>
// Bubble sort
void bubbleSort (int *numArray, int numElements) {
int sorted = 0, temp;
while (!sorted) {
// Set this flag here
sorted = 1;
for (int i = 0; i < numElements - 1; i++) {
// Swaps the numbers
if (numArray [i] > numArray [i + 1]) {
temp = numArray [i];
numArray [i] = numArray [i + 1];
numArray [i + 1] = temp;
sorted = 0;
}
}
}
}
float calcAverage (int numArray [], int numElements) {
float avg = 0;
for (int i = 0; i < numElements; i++) avg += numArray [i];
return avg / numElements;
}
int main() {
int numElements = 0;
// Ensure they actually enter a number!
while (numElements < 7 || numElements > 12) {
printf ("Please enter a number between 7 and 12: ");
// Input validation is always important in my opinion.
if (!scanf ("%d", &numElements)) {
printf ("ERROR: NaN value passed! ");
}
else if (numElements < 7 || numElements > 12) printf ("ERROR: Invalid number! ");
// Clear the buffer
while (getchar() != '\n');
}
printf ("You have chosen: %d.\n", numElements);
// Create our array and store our current number.
int numArray [numElements], fGood;
for (int i = 0; i < numElements; i++) {
// Reset this flag at the beginning of the loop
fGood = 0;
while (!fGood) {
printf ("Please enter value %d: ", i + 1);
// Assume it's a good value
fGood = 1;
if (!scanf ("%d", &numArray [i])) {
printf ("ERROR: Invalid value passed! ");
}
while (getchar() != '\n');
}
}
bubbleSort (numArray, numElements);
printf ("Average of entered numbers: %.2f\nMinimum value: %d\nMaximum value: %d\n", calcAverage(numArray, numElements), numArray [0], numArray [numElements - 1]);
return 0;
}
Related
In my code, the program will not allowed the negative number entered, the program will stop reading, then calculate the maximum value, minimum value and average value.
That is my code
#include <stdio.h>
int main(void) {
int age[10] = {0}; // initalized an array
printf("Please enter ages: \n"); // allow user to enter numbers
for (int i = 0 ;i < 10; i++) {
scanf("%d",&age[i]);
if (age[i] < 0) { // if it is negative number, it is should stop reading
break;
}
else if (age[i] >= 0) {
continue;
}
}
int maximum = age[0];
int minimum = age[0];
float average = 0.0;
int length = sizeof(age) / sizeof(age[0]);
for (int j = 0; j < length; j++) {
if (maximum < age[j]) {
maximum = age[j];
}
else if (minimum > age[j]) {
minimum = age[j];
}
average += age[j];
}
average = average / length;
printf("%d\n", maximum);
printf("%d\n", minimum);
printf("%.1f\n", average);
return 0;
}
Please enter ages: 5 -1
expected result: max:5;min:5,average:5;
actual result: max:5;min:-1,average: 0.4;
That was a question that I met, the code should not accept any negative value.
Thank you all.
but if I add age[i] = 0; then break;
The average value will equal to 0.5.
You don't need an array.
You don't need both a loop variable and a length.
It's more appropriate to use ? : for updating minimum/maximum.
You don't need two loops
You need to check the int return value of scanf(), which indicates the number of items successfully scanned, so it should be 1. I'll leave that for you/OP to add (hint: replace for-loop by while-loop to avoid having to add a separate length variable again).
int main(void)
{
printf("Please enter ages: \n");
int minimum = INT_MAX;
int maximum = 0;
int sum = 0;
int count = 0;
for (count = 0; count < 10; count++)
{
int age;
scanf("%d", &age);
if (age < 0)
{
break;
}
sum += age;
minimum = (age < minimum) ? age : minimum;
maximum = (age > maximum) ? age : maximum;
}
if (count > 0)
{
printf("Min: %d\n", minimum);
printf("Max: %d\n", maximum);
printf("Avg: %.1f\n", (float)sum / count);
}
else
{
printf("You didn't enter (valid) age(s).\n");
}
return 0;
}
Your approach is overly complicated and wrong.
You want this:
...
int length = 0; // declare length here and initialize to 0
for (int i = 0; i < sizeof(age) / sizeof(age[0]); i++) {
scanf("%d", &age[i]);
if (age[i] < 0) // if it is negative number, it is should stop reading
break;
length++; // one more valid number
}
// now length contains the number of numbers entered
// the rest of your code seems correct
You also might need to handle the special case where no numbers are entered, e.g: the only thing entered is -1. It doesn'make sense to calculate the average or the largest/smallest number when there are no numbers.
A possible solution could be:
(corrections are written in the commented code)
#include <stdio.h>
int main(void){
int arraySize = 10;
int age[arraySize]; //initialize not required
//the number of existing values inside the array (effective length)
int length = 0;
printf("Please enter ages: \n"); // allow user to enter numbers
for(int i=0; i<arraySize; i++){
scanf("%d",&age[i]);
// if it is negative number, it is should stop reading
if(age[i]<0){ break; }
//the else-if is not required
//but, if the compiler goes here,
//it means that the value is acceptable, so
length++;
}
int maximum = age[0];
int minimum = age[0];
float average = 0.0;
for(int j=0; j<length; j++){
if(maximum<age[j]){ maximum = age[j]; }
else if(minimum>age[j]) { minimum = age[j]; }
average += age[j];
}
average = average / length;
printf("%d\n", maximum);
printf("%d\n", minimum);
printf("%.1f\n", average);
return 0;
}
OP's primary problem is the 2nd loop iterates 10 times and not i times (the number of times a non-negative was entered.
For fun, let us try a non-floating point solution as it really is an integer problem.
An array to store values is not needed.
#include <limits.h>
#include <stdio.h>
int main(void) {
// Keep track of 4 things
int min = INT_MAX; // Set min to the max int value.
int max = INT_MIN;
long long sum = 0; // Use wide type to cope with sum of extreme ages.
int count = 0;
#define INPUT_N 10
printf("Please enter ages: \n");
for (count = 0; count < INPUT_N; count++) {
int age;
if (scanf("%d", &age) != 1) {
fprintf(stderr, "Missing numeric input.");
return EXIT_FAILURE;
}
if (age < 0) {
break;
}
if (age < min) min = age;
if (age > max) max = age;
sum += age;
}
if (count == 0) {
fprintf(stderr, "No input.");
return EXIT_FAILURE;
}
printf("Maximum: %d\n", max);
printf("Minimum: %d\n", min);
// Could use FP and
// printf("Average: %.1f\n", 1.0 *sum / count);
// But for fun, how about a non-FP approach?
#define SCALE 10
#define SCALE_LOG 1
sum *= SCALE; // Scale by 10 since we want 1 decimal place.
// Perform a rounded divide by `count`
long long average_scaled = (sum + count/2) / count;
// Print the whole and fraction parts
printf("Average: %lld.%.*lld\n",
average_scaled / SCALE, SCALE_LOG, average_scaled % SCALE);
return 0;
}
First of all, you must record how many positive numbers you enter. Then the value of length will be correct.
Second, for the second for loop, j must be smaller than the number of positive ages. Therefore, you won't add negative age[j] to average.
You can simply modify the second for loop.
#include <stdio.h>
int main(void) {
int age[10] = {0}; // initalized an array
printf("Please enter ages: \n"); // allow user to enter numbers
int length = 0;
for (int i = 0 ;i < 10; i++) {
scanf("%d",&age[i]);
if (age[i] < 0) { // if it is negative number, it is should stop reading
break;
}
else if (age[i] >= 0) {
length++;
continue;
}
}
int maximum = age[0];
int minimum = age[0];
float average = 0.0;
for (int j = 0; j < length; j++) {
if (maximum < age[j]) {
maximum = age[j];
}
else if (minimum > age[j]) {
minimum = age[j];
}
if ( age[j] > 0.0 )
{
average += age[j];
}
}
average = average / length;
printf("%d\n", maximum);
printf("%d\n", minimum);
printf("%.1f\n", average);
return 0;
}
#include <stdio.h>
int main()
{
int i; //counter for the loop
int n; //integer
int series;
printf("Enter an integer number: ");
scanf("%d" , &n);
for(i = 1; i <= n; i++)
{
if (i % 2 == 0)
(series -= i * i);
else
(series += i * i);
}
printf("The value of the series is: %d\n" , series);
return 0;
}
So the the loop is just a basic for loop, using I as the counter for as long as it is less than or equal to n
the series that I have to replicate adds odd numbers and subtracts even numbers so the if condition tests if the number is even or odd. The program compiles fine but when I enter the integer as 5 the sum of the series should be 15, however my program gives the sum 32779. Any help on fixing my program would be appreciated.
you didn't initialize series, so it's a random value in the beginning of the calculation.
#include <stdio.h>
int main()
{
int i = 0; //counter for the loop
int n = 0; //integer
int series = 0;
printf("Enter an integer number: ");
scanf("%d" , &n);
for(i = 1; i <= n; i++)
{
if (i % 2 == 0)
(series -= i * i);
else
(series += i * i);
}
printf("The value of the series is: %d\n" , series);
return 0;
}
#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//
Well, the problem is the above. To sum it up, it compiles, but I guess my main idea is just wrong. What I'm trying to do with that code is:
I want the person to give us the elements of the array, how many he wants to (with a limit of a 100 elements).
After that, I'm checking what array positions are prime numbers.(ex: position 2,3,5,etc. Not the elements itself).
After that, I'm doing the average of the values in the prime numbers position.
That's it. Any ideas? Keep in mind that I'm on the first period of engineering, so I'm not the best in programming.
The code is below:
#include <stdio.h>
#include <windows.h>
int main(void)
{
int k, i, j, d, v[101], sum, prim, f;
float ave;
i = 0;
while ((i < 101) && (j != 0) )
{
i++;
printf("Set the value of the element %d => ", i);
scanf("%d", &v[i]);
printf("To stop press 0 => ");
scanf("%d", &j);
}
k = 0;
prim = 1;
f = i;
sum = 0;
while (f > 2)
{
if (i % (f - 1) == 0)
{
prim = 0;
}
else
{
k++;
sum = sum + v[f];
}
f = f - 1;
}
med = sum / k;
printf("%d, %d, %d", k, soma, i);
printf("The average is => %f \n", ave);
system("pause");
}
For those wondering, this is what i got after the editing in the correct answer:
int main(void)
{
int v[101];
int n = 0;
int k,j = 0;
int i=0;
int sum = 0;
while( i<100 )
{
i++;
printf ("Set the value of the element %d => ", i);
scanf ("%d", &v[i]);
int x,primo=1;
if (i>1){
for (x=2; x*x<=i; x++) {
if (i % x == 0) primo = 0;
}
if(primo==1)
{
sum = sum+ v[i];
n++;
}
}
printf ("To stop press 0 => ");
scanf ("%d", &j);
if(j == 0)
break;
}
float ave =(sum /n);
printf("%d, %d, %d", n,i,sum);
printf("The average is => %f \n", ave);
system("pause");
}
First lets make a readable method to test if a number is prime; this answer from another SO post gives us a good one:
int IsPrime(int number) {
int i;
for (i=2; i*i<=number; i++) {
if (number % i == 0) return 0;
}
return 1;
}
Second, let's clean your code, and compute a running sum of all the prime numbers encountered so far. Also, we will check the return values of scanf (but we should avoid scanf !)
And third, we add some indentation.
int main(void)
{
int n = 0;
int i = 0;
int j = 0;
int k = 0;
int sum = 0;
while( i<101 )
{
i++;
printf ("Set the value of the element %d => ", i);
if(scanf ("%d", &k) != 1)
continue;
if(is_prime(k))
{
sum += k;
++n;
}
printf ("To stop press 0 => ");
if(scanf ("%d", &j) == 1)
if(j == 0)
break;
}
float ave = sum / (double) n;
printf("The average is => %f \n", ave);
system("pause");
}
Well there are a few things to say. First the easy part: if the max number of integers allowed to read is 100 your variable "v" should be v[100]. This is not a char array, so this array don't need to have an extra element (v[100] will be an array of int that goes from v[0] to v[99]; adjust the loop limit too).
Also, you are checking if the number you have is prime in the variable f, but this var is assigned with the variable i and i is not an element of the array. You want to assign f something like v[i] (for i equal to 0 to the count of numbers read minus one). So you will need 2 loops: the one you are using now for checking if the number is prime, and another one that assigns v[i] to f.
Another thing to say is that you are calling scanf two times for reading, you could just read numbers and store it in a temporary variable. If this number is not zero then you store it in the array and keep reading, else you stop the reading.
By last I strongly recommend you set var names that make sense, use single letters only for the index variables; names like temp, array, max and countnumbers should appear in your code. It will be easier for you and everyone else to read your code, and you will reduce the number of mistakes.
Here's the solution to your problem. Very easy stuff.
/* C program to find average of all prime numbers from the inputted array(you can predefine it if you like.) */
#include <stdio.h>
#include <conio.h>
void main()
{
int ar[100], i, n, j, counter;
float avg = 0, numprime = 0;
printf("Enter the size of the array ");
scanf("%d", &n);
printf("\n Now enter the elements of the array");
for (i = 0; i < n; i++)
{
scanf("%d", &ar[i]);
}
printf(" Array is -");
for (i = 0; i < n; i++)
{
printf("\t %d", ar[i]);
}
printf("\n All the prime numbers in the array are -");
for (i = 0; i < n; i++)
{
counter = 0;
for (j = 2; j < ar[i]; j++)
{
if (ar[i] % j == 0)
{
counter = 1;
break;
}
}
if (counter == 0)
{
printf("\t %d", ar[i]);
numprime += 1;
avg += at[i];
}
}
avg /= numprime;
printf("Average of prime numbers is ā„…f", avg);
getch();
}
You just need counter variables like above for all average computations. (Cause we need to know number of prime numbers in the array so we can divide the total of them and thus get average.) Don't worry about typecasting it is being done downwards... This solution works. I've written it myself.
Here is a cut at doing what you wanted. You don't need near the number of variables you originally had. Also, without knowing what you wanted to do with the prime number, I just output when a prime was encountered. Also as previously mentioned, using a function for checking prime really helps:
#include <stdio.h>
// #include <windows.h>
/* see: http://stackoverflow.com/questions/1538644/c-determine-if-a-number-is-prime */
int IsPrime(unsigned int number) {
if (number <= 1) return 0; // zero and one are not prime
unsigned int i;
for (i=2; i*i<=number; i++) {
if (number % i == 0) return 0;
}
return 1;
}
int main(void)
{
int i, v[101], sum, pcnt=0, psum=0;
float ave;
i=0;
printf ("\nEnter array values below, use [ctrl + d] to end input\n\n");
printf ("Set the value of the element %d => ", i);
while((i<101) && scanf ("%d", &v[i]) != EOF ){
sum += v[i];
if (IsPrime (v[i]))
psum += v[i], pcnt++;
i++;
printf ("Set the value of the element %d => ", i);
}
ave=(float)psum/pcnt;
printf("\n\n Number of elements : %d\n",i);
printf(" The sum of the elements: %d\n",sum);
printf(" The number of primes : %d\n",pcnt);
printf(" The average of primes : %f\n\n", ave);
return 0;
}
Sample Output:
Enter array values below, use [ctrl + d] to end input
Set the value of the element 0 => 10
Set the value of the element 1 => 20
Set the value of the element 2 => 30
Set the value of the element 3 => 40
Set the value of the element 4 => 51
Set the value of the element 5 => 11
Set the value of the element 6 => 37
Set the value of the element 7 =>
Number of elements : 7
The sum of the elements: 199
The number of primes : 2
The average of primes : 24.000000
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.