More than one duplicated element in C - c

Let's say I have an array like this:
int array[]={1, 2, 2, 1, 2, 4, 4, 5};
I want to display all duplicate elements only once, display their corresponding frequency and count total duplicate elements. I searched about it a lot but every solution is for an array that has only 2 duplicate elements.
void non_unique_numbers(int arr[], int size){
int i,j;
int frequency[Frequency_size]={0};
for(i=0; i<size; i++){
for(j=0; j<size; j++){
if(arr[i]==arr[j] && i!=j){
++frequency[arr[j]];
printf("Number: %d , Frequency: %d\n", arr[j], frequency[j]);
}
}
}
}
When I run this my output is:
Number: 1 , Frequency: 3
Number: 2 , Frequency: 1
Number: 2 , Frequency: 1
Number: 2 , Frequency: 1
Number: 2 , Frequency: 2
Number: 1 , Frequency: 0
Number: 2 , Frequency: 2
Number: 2 , Frequency: 6
Number: 4 , Frequency: 0
which is meaningless. How can I display every duplicate element once and find out their corresponding frequency?

Rather than nested loops, you need two loops.
One to calculate the frequency. And, another that displays the frequencies and calculates the total number of duplicate numbers.
Here is the refactored code:
Edit: I've removed my broken original code during the second update.
UPDATE:
Yes but it still displays the same element more than once –
goku
Oops, my bad ... Here is one that indexes into the frequency table on the second loop:
#include <stdio.h>
#define Frequency_size 10000
void
non_unique_numbers(int arr[], int size)
{
int i;
int freq;
int totdup = 0;
int frequency[Frequency_size] = { 0 };
// calculate freqency
for (i = 0; i < size; i++)
++frequency[arr[i]];
for (i = 0; i < Frequency_size; i++) {
freq = frequency[i];
if (freq <= 0)
continue;
printf("Number: %d , Frequency: %d\n", i, freq);
if (freq >= 2)
++totdup;
}
printf("The number of duplicated numbers is: %d\n",totdup);
}
UPDATE #2:
Can we make it work for also negative elements? for (i = 0; i < Frequency_size; i++) { freq = frequency[i]; if (freq <= 0) continue; printf("Number: %d , Frequency: %d\n", i, freq); Because of this part it is not working for negative integers –
goku
Yes, we just need to use a second array for the negative number frequencies and index it by the negative of the negative number. (i.e.) we use a corresponding positive index.
Also, some have commented about doing range checks, so I've added that along with some statistics on the out of range values [if any]. I've also updated the if test so that only duplicate numbers are printed.
Once again, I've compiled this but not tested it, but it should be okay:
#include <stdio.h>
#include <string.h>
#define Frequency_size 10000
void
non_unique_numbers(const int *arr, int size)
{
int i;
int freq;
int val;
int totdup = 0;
int pos_badcnt = 0;
int pos_badmax = 0;
int neg_badcnt = 0;
int neg_badmax = 0;
static int freq_pos[Frequency_size];
static int freq_neg[Frequency_size];
// set frequency counts to zero
memset(freq_pos,0,sizeof(freq_pos));
memset(freq_neg,0,sizeof(freq_neg));
// calculate freqency
for (i = 0; i < size; i++) {
val = arr[i];
// handle positive number(s)
if (val >= 0) {
if (val >= Frequency_size) {
++pos_badcnt;
if (val > pos_badmax)
pos_badmax = val;
}
else
++freq_pos[val];
}
// handle negative number(s)
else {
// index frequency array with positive index -- that's the trick
val = -val;
if (val >= Frequency_size) {
++neg_badcnt;
if (val > neg_badmax)
neg_badmax = val;
}
else
++freq_neg[val];
}
}
// for negative numbers, skip 0 and show lowest (most negative) first
for (i = Frequency_size - 1; i >= 1; --i) {
freq = freq_neg[i];
if (freq <= 1)
continue;
printf("Number: %d , Frequency: %d\n", -i, freq);
++totdup;
}
// show positive number frequencies
for (i = 0; i < Frequency_size; i++) {
freq = freq_pos[i];
if (freq <= 1)
continue;
printf("Number: %d , Frequency: %d\n", i, freq);
++totdup;
}
printf("The number of duplicated numbers is: %d\n",totdup);
// show out of range negative number stats
if (neg_badcnt > 0) {
printf("There were %d out of range negative numbers\n",neg_badcnt);
printf("Smallest out of range negative number was %d\n",-neg_badmax);
}
// show out of range positive number stats
if (pos_badcnt > 0) {
printf("There were %d out of range positive numbers\n",pos_badcnt);
printf("Largest out of range positive number was %d\n",pos_badmax);
}
}

You can try this.
void non_unique_numbers(int arr[], int size){
int i,j;
for(i=0; i<size; i++)
{
int frequency=0;
bool wasFoundEarlier=false;
for(j=i; j<size; j++)
{
if(arr[i]==arr[j])
{
frequency++;
}
}
for(int x=0;x<i;x++)
{
if(arr[x]==arr[i])
{
wasFoundEarlier=true;
}
}
if(!wasFoundEarlier)
{
printf("Number: %d , Frequency: %d\n", arr[i], frequency);
}
}
}
This will print the frequency of all the elements.
If you want to print the frequency of only duplicate ones, just change the inner loop
for(j=i+1; j<size; j++)

Related

Find the maximum, minimum, and average values in the array

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;
}

How to find a minimum?

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;
}

Average of prime numbers in an array

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

Most frequent element in a sequence using arrays in C

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.

How to find the sum of Prime Numbers in C within a given range?

I'm very new to programming and I was asked to find the sum of prime numbers in a given range, using a while loop. If The input is 5, the answer should be 28 (2+3+5+7+11). I tried writing the code but it seems that the logic isn't right.
CODE
#include <stdio.h>
int main()
{
int range,test;
int sum = 2;
int n = 3;
printf("Enter the range.");
scanf("%i",range);
while (range > 0)
{
int i =2;
while(i<n)
{
test = n%i;
if (test==0)
{
goto end;
}
i++;
}
if (test != 0)
{
sum = sum + test;
range--;
}
end:
n++;
}
printf("The sum is %i",sum);
return 0;
}
It would be nice if you could point out my mistake and possibly tell me how to go about from there.
first of all, in the scanf use &range and not range
scanf("%i",&range);
Second this instruction is not correct
sum = sum + test;
it should be
sum = sum + n;
and also the
while (range > 0)
should be changed to
while (range > 1)
Because in your algorithm you have already put the first element of the range in the sum sum = 2 so the while should loop range - 1 times and not range times
That's all
OK, my C is really bad, but try something like the following code. Probably doesn't compile, but if it's a homework or something, you better figure it out yourself:
UPDATE: Made it a while loop as requested.
#include <stdio.h>
int main()
{
int range, test, counter, innerCounter, sum = 1;
int countPrimes = 1;
int [50] primesArray;
primesArray[0] = 1;
printf("Enter the range.");
scanf("%i",range);
counter = 2;
while (counter <= range) {
for (innerCounter = 1; innerCounter < countPrimes; innerCounter++) {
if (counter % primesArray[innerCounter] == 0)
continue;
primesArray[countPrimes + 1] = counter;
countPrimes ++;
sum += counter;
}
counter ++
}
printf("The sum is %i",sum);
return 0;
}
I haven't done C in a while, but I'd make a few functions to simplify your logic:
#include <stdio.h>
#include <math.h>
int is_prime(n) {
int i;
for (i = 2; i <= sqrt(n); i++) {
if (n % i == 0) {
return 0;
}
}
return 1;
}
int main() {
int range, i, sum, num_primes = 0;
printf("Enter the range: ");
scanf("%d", &range);
for (i = 2; num_primes < range; i++) {
if (is_prime(i)) {
sum += i;
num_primes++;
}
}
printf("The sum is %d", sum);
return 0;
}
Using goto and shoving all of your code into main() will make your program hard to debug.
Copy - pasted from here.
#include <stdio.h>
int main() {
int i, n, count = 0, value = 2, flag = 1, total = 0;
/* get the input value n from the user */
printf("Enter the value for n:");
scanf("%d", &n);
/* calculate the sum of first n prime nos */
while (count < n) {
for (i = 2; i <= value - 1; i++) {
if (value % i == 0) {
flag = 0;
break;
}
}
if (flag) {
total = total + value;
count++;
}
value++;
flag = 1;
}
/* print the sum of first n prime numbers */
printf("Sum of first %d prime numbers is %d\n", n, total);
return 0;
}
Output:
Enter the value for n:5
Sum of first 5 prime numbers is 28
Try the simplest approach over here. Check C program to find sum of all prime between 1 and n numbers.
CODE
#include <stdio.h>
int main()
{
int i, j, n, isPrime, sum=0;
/*
* Reads a number from user
*/
printf("Find sum of all prime between 1 to : ");
scanf("%d", &n);
/*
* Finds all prime numbers between 1 to n
*/
for(i=2; i<=n; i++)
{
/*
* Checks if the current number i is Prime or not
*/
isPrime = 1;
for(j=2; j<=i/2 ;j++)
{
if(i%j==0)
{
isPrime = 0;
break;
}
}
/*
* If i is Prime then add to sum
*/
if(isPrime==1)
{
sum += i;
}
}
printf("Sum of all prime numbers between 1 to %d = %d", n, sum);
return 0;
}

Resources