Build a program which reads from the user an array with n elements and finds the element with the smallest value.Then the program finds the number of the elements which have an equal value with this minimum.The found element with the smallest value along with the number of the elements which have an equal value with the minimum of the array should be displayed on screen..
I wrote this code :
#include <stdio.h>
int main() {
int n = 1, min = 0, count = 0;
int number[n];
printf("Enter the size of array you want");
scanf("%i", &n);
int x;
for (x = 0; x < n; x++) {
int num;
printf("\nEnter a Integer");
scanf("%i", &num);
number[x] = num;
if (number[x] < min)
min = number[x];
}
int i;
for (i = 0; i < n; i++) {
if (min = number[i])
count++;
}
printf("%s%i", "\nThe smallest Integer you entered was ", min);
printf("%s%i", "\nNumber of times you entered this Integer: ", count);
return 0;
}
But the problem is that when I run this,and I add the integers,it doesnt find the smallest value and how time its repeated correctly!
Where am I wrong?
Assuming your compiler has support for variable length arrays, you need to re-order the calls
int number[n];
scanf("%i", &n);
so that you know the value for n before declaring the array
scanf("%i", &n);
int number[n];
After that, you should initialise min to a larger value to avoid ignoring all positive values
int min = INT_MAX;
(You'll need to include <limits.h> for the definition of INT_MAX)
Finally,
if (min = number[i])
assigns number[i] to min. Use == to test for equality.
Your compiler should have warned you about "assignment in conditional statement" for this last point. If it didn't, make sure you have enabled warnings (-Wall with gcc, /W4 with MSVC)
you are checking array element <0 in line:
if (number[x] < min/*as u specified min =0 before*/),...
so the minimum is set to be zero and there is no replacement actually happening..
The full solution:
#include <stdio.h>
int main() {
int n = 1, min = 0, count = 0;
int number[n];
printf("Enter the size of array you want");
scanf("%i", &n);
int x,y;
for (y = 0; y < n; y++)
{
printf("\nEnter a Integer");
scanf("%i", &number[y]);
}
min=number[0];
for (x = 0; x < n; x++) {
if (number[x] < min)
min = number[x];
}
int i;
for (i = 0; i < n; i++) {
if (min == number[i])
count++;
}
printf("%s%i", "\nThe smallest Integer you entered was ", min);
printf("%s%i", "\nNumber of times you entered this Integer: ", count);
return 0;
}
for (i = 0; i < n; i++) {
if (min = number[i])
count++;
}
Replace min = number[i] with min == number[i].
1.Only After the user input the array size, then you can determine the size of the array number.As the size of the array are uncertain, you should use malloc to allocate the array dynamically.
2.you should set min to the first element of the array. As the min of user input may be great than zero, if you set min to zero, then it will return zero even though the minimum is great than zero
3.you should use == but not = to test the equality of two numbers.
4.last, you should use free to make the memory available and avoid memory leak.
Below is the full program:
#include <stdio.h>
int main() {
int n = 1, min = 0, count = 0;
int* number;
printf("Enter the size of array you want");
scanf("%i", &n);
number = (int*)malloc(sizeof(int)*n);
int x;
for (x = 0; x < n; x++) {
int num;
printf("\nEnter a Integer");
scanf("%i", &num);
number[x] = num;
if( x == 0 || number[x] < min )
min = number[x];
}
int i;
for (i = 0; i < n; i++) {
if (min == number[i])
count++;
}
printf("%s%i", "\nThe smallest Integer you entered was ", min);
printf("%s%i", "\nNumber of times you entered this Integer: ", count);
free(number);
number = NULL;
return 0;
}
In your code
if (min = number[i])
you assigned number[i] to min. You should write
if (min == number[i])
instead.
There are couple of things wrong on your code. First you defined array number[1]. Secondly min in initialised to min = 0.
I suggest defined the array for a maximum possible size, like number[100]. And read the numbe of inputs n from the user, and only use the first n elements of the array. For the second issue, define min as the maximum number represented by int type.
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;
}
I'm taking my first ever programming class and most of it is self taught. So please bear with me.
After the users input numbers, such as 10, 20, 100, 3, 4 there should be an output to read
"the index of the largest elmeent in list1 array is _
The largest element in list1 array is 100" "
Here is my code so far. I know how to get the output of the largest array but not the first line or how to name my array. Thanks so much in advance.
#include<stdio.h>
int main()
{
int i;
float arr[5];
printf("Please enter five numbers:\n ");
for (i = 0; i < 5; ++i)
{
scanf_s("%f", &arr[i]);
}
for (i = 1; i < 5; ++i)
{
if (arr[0] < arr[i])
arr[0] = arr[i];
}
printf("Largest element = %.2f", arr[0]);
return 0;
}
This code here will give you the biggest element is the array but it also changes the order in which the elements were entered. Instead of taking the biggest element to the 0th position of the array,you can simply use an integer to store the index of the biggest element.Your program can be modified like this :
#include<stdio.h>
int main()
{
int i,temp=0;
float arr[5];
printf("Please enter five numbers:\n ");
for (i = 0; i < 5; ++i)
{
scanf_s("%f", &arr[i]);
}
for (i = 1; i < 5; ++i)
{
if (arr[temp] < arr[i])
temp=i;
}
printf("Largest element = %.2f", arr[temp]);
printf("Index = %d",temp);
return 0;
}
Hope the answer was useful.
Your approach to find the max element in an array is fine. But it alters the original array. If it okay with you, then go ahead with it, else if you would like to keep the array in tact as well as find the max element with the index, then check the code which I have attached below. If you intend to keep the methodology same, then just add a variable, which you should update as and when you find a higher number, as follows:
int max_index; //declare before
if (arr[0] < arr[i]) {
max_index = i;
arr[0] = arr[i];
}
If you are interested to keep the array unchanged and find out the max element with its index, the code would be as follows:
#include<stdio.h>
int main()
{
int i, max_index;
float arr[5], max;
printf("Please enter five numbers:\n ");
for (i = 0; i < 5; ++i)
{
scanf("%f", &arr[i]);
}
max = arr[0];//start off assuming that the 1st element is the max
for (i = 0; i < 5; i++)//now compare it with the rest of the array, updataing the max all along
{
if (arr[i] > max) {
max = arr[i];
max_index = i;
}
}
printf("Largest element = %.2f at index %d", max, max_index);
return 0;
}
Hope this helps.
You know, that you can get the element if you know its index. This means, you can store the index of the "known biggest" element, and you can refer to the biggest element using the stored index.
int imax = 0;
for (i = 1; i < 5; ++i)
{
if (arr[imax] < arr[i])
imax = i;
}
printf("Largest element = %.2f at index %i\n", arr[imax], imax);
.
use this code in place of last loop
I have searched many websites for this question. They are doing it by some different approach.
This code is just not giving output if I input first element of array as largest i.e. a[0].
I think some minor change is required.
can anyone please tell me?
#include <stdio.h>
int main() {
int a[10], n;
int largest1, largest2, i;
printf("enter number of elements you want in array");
scanf("%d", &n);
printf("enter elements");
for (i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
largest1 = a[0];
for (i = 0; i < n; i++) {
if (a[i] > largest1) {
largest1 = a[i];
}
}
largest2 = a[0];
for (i = 1; i < n; i++) {
if (a[i] > largest2 && a[i] < largest1)
largest2 = a[i];
}
printf("First and second largest number is %d and %d ", largest1, largest2);
}
(I'm going to ignore handling input, its just a distraction.)
The easy way is to sort it.
#include <stdlib.h>
#include <stdio.h>
int cmp_int( const void *a, const void *b ) {
return *(int*)a - *(int*)b;
}
int main() {
int a[] = { 1, 5, 3, 2, 0, 5, 7, 6 };
const int n = sizeof(a) / sizeof(a[0]);
qsort(a, n, sizeof(a[0]), cmp_int);
printf("%d %d\n", a[n-1], a[n-2]);
}
But that isn't the most efficient because it's O(n log n), meaning as the array gets bigger the number of comparisons gets bigger faster. Not too fast, slower than exponential, but we can do better.
We can do it in O(n) or "linear time" meaning as the array gets bigger the number of comparisons grows at the same rate.
Loop through the array tracking the max, that's the usual way to find the max. When you find a new max, the old max becomes the 2nd highest number.
Instead of having a second loop to find the 2nd highest number, throw in a special case for running into the 2nd highest number.
#include <stdio.h>
#include <limits.h>
int main() {
int a[] = { 1, 5, 3, 2, 0, 5, 7, 6 };
// This trick to get the size of an array only works on stack allocated arrays.
const int n = sizeof(a) / sizeof(a[0]);
// Initialize them to the smallest possible integer.
// This avoids having to special case the first elements.
int max = INT_MIN;
int second_max = INT_MIN;
for( int i = 0; i < n; i++ ) {
// Is it the max?
if( a[i] > max ) {
// Make the old max the new 2nd max.
second_max = max;
// This is the new max.
max = a[i];
}
// It's not the max, is it the 2nd max?
else if( a[i] > second_max ) {
second_max = a[i];
}
}
printf("max: %d, second_max: %d\n", max, second_max);
}
There might be a more elegant way to do it, but that will do, at most, 2n comparisons. At best it will do n.
Note that there's an open question of what to do with { 1, 2, 3, 3 }. Should that return 3, 3 or 2, 3? I'll leave that to you to decide and adjust accordingly.
The problem with your code is a logic problem (which is what most coding is about). If the largest number is first then it gets the second largest number wrong ... why?
Well, look at your logic for deciding on the second largest number. You first set it to be equal to the first element in the array and then you go through the array and change the index if the element is greater than the current second largest number (which will never be true because we already set it to be the largest number!).
To solve it you can special case this: check if the largest number was the first and if so then set it to the second element (and then special case the issue of someone asking to find the highest two elements in a one element array, without reading past the end of an array.)
I think the method given in chqrlie's answer to do this all in one pass is best. And logical too: write a program to find the largest number. Second largest number, well that's just the one which was previously the largest!
You need to preserve the index of array members better as they are unique Here is a working code with few changes:
#include<stdio.h>
int main()
{
int a[10],n;
int largest1,largest2,i;
printf("enter number of elements you want in array");
scanf("%d",&n);
printf("enter elements");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
largest1=0;
for(i=0;i<n;i++)
{
if(a[i]>a[largest1])
{
largest1=i;
}
}
if(largest1!=0) // this condition to select another index than the largest
largest2=0;
else
largest2=n-1;
for(i=0;i<n && i != largest1 ;i++)
{
if(a[i]>a[largest2])
largest2=i;
}
printf("First and second largest number is %d and %d ",a[largest1],a[largest2]);
}
Note that when the array is of size 1 values will be the same.
The question is ambiguous: if the array may contain duplicate values, are you supposed to find the 2 largest distinct values or the two largest possibly identical values?
Your code seems to indicate you want the first approach, but you have a problem if the largest value is a[0]. You should use an extra boolean to keep track of whether you have found a different value yet.
You should also test the return value of the different scanf() calls and return 0 from main().
Here is a modified version:
#include <stdio.h>
int main(void) {
int a[10], n, i;
int largest1, largest2, has_largest2;
printf("enter number of elements you want in array: ");
if (scanf("%d", &n) != 1)
return 1;
if (n < 2) {
printf("need at least 2 elements\n");
return 1;
}
printf("enter elements: ");
for (i = 0; i < n; i++) {
if (scanf("%d", &a[i]) != 1) {
printf("input error\n");
return 1;
}
}
largest1 = a[0];
for (i = 1; i < n; i++) {
if (a[i] > largest1) {
largest1 = a[i];
}
}
has_largest2 = largest2 = 0;
for (i = 0; i < n; i++) {
if (a[i] < largest1) {
if (!has_largest2) {
has_largest2 = 1;
largest2 = a[i];
} else
if (a[i] > largest2) {
largest2 = a[i];
}
}
}
if (has_largest2) {
printf("First and second largest number is %d and %d\n",
largest1, largest2);
} else {
printf("All values are identical to %d\n", largest1);
}
return 0;
}
You can do it best in one pass.
largest and largest2 are set to INT_MIN on entry.
Then step through the array. If largest is smaller than the number, largest2 becomes largest, then largest becomes the new number (or smaller than or equal if you want to allow duplicates). If largest is greater then the new number, test largest2.
Note that this algorithm scales to finding the top three or four in an array, before it become too cumbersome and it's better to just sort.
//I think its simple like
#include<stdio.h>
int main()
{
int a1[100],a2[100],i,t,l1,l2,n;
printf("Enter the number of elements:\n");
scanf("%d",&n);
printf("Enter the elements:\n");
for(i=0;i<n;i++)
{
scanf("%d",&a1[i]);
}
l1=a1[0];
for(i=0;i<n;i++)
{
if(a1[i]>=l1)
{
l1=a1[i];
t=i;
}
}
for(i=0;i<(n-1);i++)
{
if(i==t)
{
continue;
}
else
{
a2[i]=a1[i];
}
}
l2=a2[0];
for(i=1;i<(n-1);i++)
{
if(a2[i]>=l2 && a2[i]<l1)
{
l2=a2[i];
}
}
printf("Second highest number is %d",l2);
return 0;
}
There is no need to use the Third loop to check the second largest number in the array. You can only use two loops(one for insertion and another is for checking.
Refer this code.
#include <stdio.h>
int main()
{
int a[10], n;
int i;
printf("enter number of elements you want in array");
scanf("%d", &n);
printf("enter elements");
for (i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
int largest1 = a[0],largest2 = a[0];
for (i = 0; i < n; i++)
{
if (a[i] > largest1)
{
largest2=largest1;
largest1 = a[i];
}
}
printf("First and second largest number is %d and %d ", largest1, largest2);
}
Hope this code will work for you.
Enjoy Coding :)
Find your second largest number without using any String function:
int array[];//Input array
int firstLargest, secondLargest;
int minNumber = -1;//whatever smallest you want to add here
/*There should be more than two elements*/
if (array_size < 2)
{
printf("Array is too small");
return;
}
firstLargest = secondLargest = minNumber;
for (index = 0; index < array_size ; ++index)
{
//Largest number check
if (array[index] > first)
{
secondLargest = firstLargest;
firstLargest = array[index];
}
//It may not larger than first but can be larger than second number
else if (array[index] > secondLargest && array[index] != firstLargest)
{
secondLargest = array[index];
}
//Finally you got your answer
if (secondLargest == minNumber)
{
printf("No Second largest number");
}
else
{
printf("Second Largest Number is %d", secondLargest);
}
Here is an answer with a single for loop.
int array[] = { 10, 15, 13, 20, 21, 8, 6, 7, 9, 21, 23 };
const int count = sizeof(a) / sizeof(a[0]);
int lastMaxNumber = 0;
int maxNumber = 0;
for (int i = 0; i < count; i++) {
// Current number
int num = array[i];
// Find the minimum and maximum from (num, max)
int maxValue = (num > maxNumber) ? num : maxNumber;
int minValue = (num < maxNumber) ? num : maxNumber;
// If minValue is greater than lastMaxNumber, update the lastMaxNumber
if minValue > lastMaxNumber {
lastMaxNumber = minValue;
}
// Updating maxNumber
maxNumber = maxValue;
}
printf("%d", lastMaxNumber);
If you need to find the largest and second largest element in an existing array, see the answers above (Schwern's answer contains the approach I would've used).
However; needing to find the largest and second largest element in an existing array typically indicates a design flaw. Entire arrays don't magically appear - they come from somewhere, which means that the most efficient approach is to keep track of "current largest and current second largest" while the array is being created.
For example; for your original code the data is coming from the user; and by keeping track of "largest and second largest value that the user entered" inside of the loop that gets values from the user the overhead of tracking the information will be hidden by the time spent waiting for the user to press key/s, you no longer need to do a search afterwards while the user is waiting for results, and you no longer need an array at all.
It'd be like this:
int main() {
int largest1 = 0, largest2 = 0, i, temp;
printf("enter number of elements you want in array");
scanf("%d", &n);
printf("enter elements");
for (i = 0; i < n; i++) {
scanf("%d", &temp);
if(temp >= largest1) {
largest2 = largest1;
largest1 = temp;
} else if(temp > largest2) {
largest2 = temp;
}
}
printf("First and second largest number is %d and %d ", largest1, largest2);
}
Try Out with this:
firstMax = arr[0];
for (int i = 0; i<n; i++) {
if (firstMax < arr[i] ) {
secondMax = firstMax;
firstMax = arr[i];
}
}
Although it can be done in one scan but to correct your own code , you must declare largest2 as int.Min as it prevents the largest2 holding the largest value intially.
#include<stdio.h>
int main()
{
int a[10];
int i,b,c;
printf("Enter ten values : \n");
for(i=0; i<10; i++)
{
scanf("%d",&a[i]);
}
b=a[0];
for(i=0; i<10; i++)
{
if(a[i]>b)
{
b=a[i];
}
else
{
b=b;
}
}
if(b==a[1])
{
c=a[2];
}
else
{
c=a[1];
}
for(i=0; i<10; i++)
{
if(a[i]>c && a[i]!=b)
{
c=a[i];
}
else if (b>c)
{
c=c;
}
}
printf("Largest number is %d\nSecond largest number is %d",b,c);
}
If you ever need to find the largest or smallest element in an array, try with bubble sort.
Bubble Sort works on simple concept of shifting the biggest element at the end in every pass it does (in case of increasing order). Since you need the first and second largest element in an array, 2 passes of bubble sort will do the trick. The last element will be the largest and the second last element will be second largest.
I'm providing you with the link that'll help you understand the bubble sort concept.
http://www.codeido.com/2010/10/bubblesort-written-in-c-with-example-step-by-step/
Hope it helps!!!
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.