My assignment is to find all possible modes for a set of numbers (0 to 100).
We were told to do so using arrays and also to count the frequency that each number occurs.
I've coded for the mode, however, my program does not work is there are multiple modes (example: 1, 2, 7, 7, 9, 10, 7, 2, 2. In this stance, 2 and 7 are both the mode and my program needs to print both of them, but mine doesn't).
I think I might have to make another array set, but I'm not sure? Any advice would be appreciated.
Here is what I have:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main() {
int x, i, c[101], mode;
printf("please enter test scores between 0 and 100\n");
i = 0;
mode = 0;
while (i <= 100) { //setting all values to 0
c[i] = 0;
i = i + 1;
}
scanf("%d", &x); // scanning in the test scores
while ((x >= 0) && (x <= 100)) { // counting how often each score appears
c[x] = c[x] + 1;
if (c[x] >= mode) {
mode = x;
}
scanf("%d", &x);
}
printf("THE MODE(S) ARE %d\n", mode);
i = 0;
while (i <= 100) { //printing all values so long as they've occurred at least once
if (c[i] > 0) {
printf("%d occurs %d times\n", i, c[i]);
}
i = i + 1;
}
}
You have to count the highest frequency of any number and if that frequency equals the frequency of any other number then that number will also be mode.
So the changes that you need to do are:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main ()
{
int x, i, c[101], mode;
printf("please enter test scores between 0 and 100\n");
i = 0;
mode = 0;
while (i <= 100) //setting all values to 0
{
c[i] = 0;
++i;
}
scanf("%d", &x); // scanning in the test scores
while ((x >= 0) && (x <= 100)) // counting how often each score appears
{
c[x] = c[x] + 1;
if (c[x] >= mode)
{mode = c[x];}
scanf("%d", &x);
}
for(i=0;i<=100;i++){//printing all values having highest frequency
if (c[i]==mode)
{
printf("THE MODE(S) ARE %d\n", i);
}
i = 0;
while (i<=100) //printing all values so long as they've occurred at least once
{
if (c[i] > 0)
{
printf("%d occurs %d times\n", i, c[i]);
}
++i;
}
}
Instead of determining the mode in the main entry loop, you should determine the maximum count. Then you can print all values with this count of occurrences in a final loop.
You should also check the return values of scanf().
I would also advise to use an initializer for the array to avoid a loop and to use for loops that more clearly identify the initialization, test and increment of the loop index.
Here is a corrected version of your code:
#include <stdio.h>
int main() {
int x, i, c[101] = { 0 }, max_repeat;
printf("please enter test scores between 0 and 100\n");
max_repeat = 0;
// read the test scores and compute the maximum repeat count
while (scanf("%d", &x) == 1 && x >= 0 && x <= 100) {
c[x] += 1;
if (max_repeat < c[x]) {
max_repeat = c[x];
}
}
printf("The mode(s) are");
for (i = 0; i <= 100; i++) {
if (c[i] == max_repeat) {
printf(" %d", i);
}
}
printf("\n");
return 0;
}
Related
I am trying to find the prime numbers in a range using C language. My code does not give an output and I think there is a logical error here which I cannot figure out. Can anyone please help?
#include <stdio.h>
int main() {
int lowerLevel;
int upperLevel;
int i; //counter variable
int prime = 0;
int flag = 0;
printf("Enter the lower limit and upper limit of the range followed by a comma :");
scanf("%d %d", &lowerLevel, &upperLevel);
for (i = 2; i <= upperLevel; ++i) {
if (i % 2 == 0) {
flag = 1;
break;
}
}
if (flag == 0) {
printf("%d", i);
++i;
}
return 0;
}
Your code does not check for prime numbers, it merely checks that there is at least one even number between 2 and upperlevel, which is true as soon as upperlevel >= 2. If there is such an even number, nothing is printed.
You should instead run a loop from lowerlevel to upperlevel and check if each number is a prime and if so, print it.
Here is a modified version:
#include <stdio.h>
int main() {
int lowerLevel, upperLevel;
printf("Enter the lower limit and upper limit of the range: ");
if (scanf("%d %d", &lowerLevel, &upperLevel) != 2) {
return 1;
}
for (int i = lowerLevel; i <= upperLevel; ++i) {
int isprime = 1;
for (int p = 2; p <= i / p; p += (p & 1) + 1) {
if (i % p == 0) {
isprime = 0;
break;
}
}
if (isprime) {
printf("%d ", i);
}
}
printf("\n");
return 0;
}
This method is simplistic but achieves the goal. More efficient programs would use a sieve to find all prime numbers in the range without costly divisions.
Optimal method with Sieves of Eratosthenes
You should use the sieves of Eratostenes algorithm, it is way more efficient to get the different prime number.
it does so by iteratively marking as composite (i.e., not prime) the multiples of each prime, starting with the first prime number, 2
Basically you consider all numbers prime by default, and then you will set as false the prime number, see below code:
#include <stdio.h>
/// unsigned char saves space compared to integer
#define bool unsigned char
#define true 1
#define false 0
// https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
void printPrimesRange(int lowerLevel, int n) {
if (lowerLevel < 0 || n < lowerLevel) // handle misused of function
return ;
bool isPrime[n + 1];
memset(isPrime, true, n + 1);
int cnt = 0; // NB: I use the counter only for the commas and final .\n, its optional.
if (lowerLevel <= 2 && n >= 2) { // only one even number can be prime: 2
++cnt;
printf("2");
}
for (int i = 3; i <= n ; i+=2) { // after what only odd numbers can be prime numbers
if (isPrime[i]) {
if (i >= lowerLevel) {
if (cnt++)
printf(", ");
printf("%d", i); // NB: it is better to print all at once if you can improve it
}
for (int j = i * 3; j <= n; j+=i*2) // Eratosthenes' Algo, sieve all multiples of current prime, skipping even numbers
isPrime[j] = false;
}
}
printf(".\n");
}
int main(void) {
int lowerLevel;
int upperLevel;
printf("Enter the lower limit and upper limit of the range with a space in-between:"); // space, not comma
scanf("%d %d", &lowerLevel, &upperLevel);
printPrimesRange(lowerLevel, upperLevel);
return 0;
}
Let's follow the logic of your code:
#include <stdio.h>
#include <string.h>
int main() {
int lowerLevel;
int upperLevel;
int i; //counter variable
int prime = 0;
int flag = 0;
printf("Enter the lower limit and upper limit of the range followed by a comma :");
scanf("%d %d", &lowerLevel, &upperLevel);
for (i = 2; i <= upperLevel; ++i) {
if (i % 2 == 0) {
flag = 1;
break;
}
}
if (flag == 0) {
printf("%d", i);
++i;
}
return 0;
}
First of all, you have a loop:
for (i = 2; i <= upperLevel; ++i) {
if (i % 2 == 0) {
flag = 1;
break;
}
}
this loop tries to find a number i that is a multple of 2, because as soon you get one, you jump out of the loop. So your loop can be expressed better as:
for (i = 2; i <= upperLevel && i % 2 != 0; ++i) {
}
/* i > upperLevel || i % 2 == 0 */
if (i <= upperLevel && i % 2 == 0) {
flag = 1;
}
We still need to check if i <= upperLevel && i % 2 == 0 to set the variable flag = 1 if we exited the loop because i was a multiple of 2, but the break; is not necessary because we are already out of the loop.
Now let's check that the first value we initialize i is, indeed 2 (which is a multiple of 2) and the consecuence of this is that the loop is never going to be entered. Se we can eliminate it completely, giving to:
i = 2;
if (i <= upperLevel && i % 2 == 0) {
flag = 1;
}
now, the second clause of the if test is always true, so we can take it off, giving:
i = 2;
if (i <= upperLevel) {
flag = 1;
}
Now, let's append the second part:
i = 2;
if (i <= upperLevel) {
flag = 1;
}
if (flag == 0) {
printf("%d", i);
++i;
}
return 0;
so, the first thing we see here is that your ++i; statement is nonsense, as it is the last statement to be
executed before exiting the program, so we can also take it off.
i = 2;
if (i <= upperLevel) {
flag = 1;
}
if (flag == 0) {
printf("%d", i);
}
return 0;
Now we see that you print the value of i only if the value of flag is zero, but flag only conserves its zero value if the value of i > upperLevel, and as i is fixed, the printing of i only occurs if you input a value of upperlevel that is less than 2.
We can rewrite the above code as this:
if (2 > upperLevel) {
printf("%d", 2);
}
Your program will print 2 only if you provide a value of upperLevel less than 2.
I have started learning C language. I wrote this program to find all prime numbers between the given range but I am unable to get the expected output.
Can anyone tell me what's wrong with this program please?
#include <stdio.h>
#include <conio.h>
void main() {
int min, max, i, j, count = 0;
printf("Enter Your First Number\n");
scanf("%d", &min);
printf("Enter Your Last Number\n");
scanf("%d", &max);
for(i=min; i<=max; i++) {
for(j=1; j<=i; j++) {
if(i % j == 0) {
count++;
}
}
if(count==2) {
printf("%d\t",i);
}
}
getch();
}
I just suggest getting rid of that count variable.
How do you know if a number N is prime? If for every j in the range (2 to N-1) you have N%j != 0.
So:
In the inner loop, use j from 2 to N-1 (instead of from 1 to N as you used tio do). In fact N%1 and N%N will be 0
The first time you find a j so that N % j == 0 break. You are sure it's not prime
Why incrementing count? For a prime number the j counter will be equal to i (because you looped until j<i, and the last j++ made j
equal to i). So just check for j == i and print the prime number i
#include <stdio.h>
#include <conio.h>
int main( void )
{
int min, max, i, j, count = 0;
printf("Enter Your First Number\n");
scanf("%d", &min);
printf("Enter Your Last Number\n");
scanf("%d", &max);
for(i=min; i<=max; i++)
{
// Was for(j=1; j<=i; j++)
for(j=2; j<i; j++)
{
if(i % j == 0)
{
//Was count++;
break;
}
}
//Was if(count==2)
if(j == i)
{
printf("%d\t",i);
}
}
getch();
return 0;
}
Here you are.
#include <stdio.h>
int main( void )
{
printf( "Enter the range of numbers (two unsigned integer numbers): " );
unsigned int first = 0, last = 0;
scanf( "%u %u", &first, &last );
if ( last < first )
{
unsigned int tmp = first;
first = last;
last = tmp;
}
do
{
int prime = first % 2 == 0 ? first == 2 : first != 1;
for ( unsigned int i = 3; prime && i <= first / i; i += 2 )
{
prime = first % i != 0;
}
if ( prime ) printf( "%u ", first );
} while ( first++ != last );
putchar( '\n' );
return 0;
}
The program output might look like
Enter the range of numbers (two unsigned integer numbers): 0 100
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
As for your program then you need re-initialize the variable count before the inner loop
for(i=min; i<=max; i++) {
count = 0;
for(j=1; j<=i; j++) {
if(i % j == 0) {
count++;
}
}
And the inner loop is inefficient.
Need to reset the value of count. It starts at count=0, then for any inputs, the loops will count up. The For each outer loop index, it will go like this:
1 (1%1=0 --> count++, count = 1)
2 (2%1=0 --> count++, and 2%2=0 --> count++, count = 3)
3 (3%1=0 --> count++, and 3%3=0 --> count++, count = 5)
etc... until max is reached.
You can use a simple isprime function to check whether a number is prime or not and then call the function for the given interval.
To find whether a number is prime or not , we can use a simple primality test to check it.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
bool isprime(int n)
{
if(n <= 1) return false;
if(n <= 3) return true;
if(n%2 == 0 || n%3 == 0) return false;
for(int i = 5;i*i <= n;i += 6)
{
if(n%i == 0 || n%(i + 2) == 0)
{
return false;
}
}
return true;
}
int main()
{
int a,b;
printf("Enter the first number :");
scanf("%d",&a);
printf("Enter the second number :");
scanf("%d",&b);
for(int i = a;i <= b;i++)
{
if(isprime(i)) printf("%d ",i);
}
return 0;
}
There is a simple change you should do:
#include <stdio.h>
#include <conio.h>
void main() {
int min, max, i, j, count;
printf("Enter Your First Number\n");
scanf("%d", &min);
printf("Enter Your Last Number\n");
scanf("%d", &max);
for(i=min; i<=max; i++)
{
count=1;
for(j=2; j<=i; j++)
{
if(i % j == 0) {
count++;
}
}
if(count==2) {
printf("%d\t",i);
}
}
}
My answer may be a bit late, but since it's the same issue, i'll write it here in case it helps someone else coming to this thread in the future.
My code is written from the POV of a beginner (No complex functions or data types are used) as this is a code that mostly they will get stuck on.
Working:
User inputs the range.
Using the for loop, each number in the range is sent to the isprime function which returns TRUE or FALSE after checking the condition for being a prime number.
if TRUE : program prints the number.
if FALSE : program skips the number using continue function.
#include<stdio.h>
int isprime(int num);
int main() {
int min, max;
printf("Input the low number: ");
scanf("%d", &min);
printf("Input the high number: ");
scanf("%d", &max);
for(int i = min; i<=max; i++) {
if(isprime(i) == 1) {
printf("%d ", i);
}
else if(isprime(i) == 0){
continue;
}
}
return 0;
}
int isprime(int num) {
int count = 0;
for(int i=2; i<=(num/2); i++) {
if(num % i == 0 ) {
count ++;
}
else{
continue;
}
}
if(count>0){
return 0;
}
else if (count == 0){
return 1;
}
}
test case:
input: 1234
output: 24
input: 2468
output: 2468
input: 6
output: 6
I have this code:
#include <stdio.h>
#include <math.h>
int main() {
int num;
printf("Enter a number: \n");
scanf("%d", &num);
int numberLength = floor(log10(abs(num))) + 1;
int inputNumberArray[numberLength];
int evenNumberCount = 0;
int even[10];//new even no. array
int i = 0;
do {
inputNumberArray[i] = num % 10;
num = num / 10;
i++;
} while (num != 0);
i = 0;
while (i < numberLength) {
if (inputNumberArray[i] % 2 == 0) {
evenNumberCount ++;
even[i] = inputNumberArray[i];
}
i++;
}
printf("array count %d\n", evenNumberCount);
i = 0;
for (i = 0; i < 8; i++) {
printf(" %d", even[i]);//print even array
}
i = 0;
int result = 0;
for (i = 0; i < 10; i++) {
if (evenNumberCount == 1) {
if (even[i] != 0) {
result = even[i];
} else {
break;
}
} else {
if (even[i] != 0) {
result = result + even[i] * pow(10, i);
} else
break;
}
}
printf("\nresult is %d", result);
/*
int a = 0;
a = pow(10, 2);
printf("\na is %d", a);
*/
}
when I enter number 1234, the result/outcome is 4, instead of 24.
but when I test the rest of test case, it is fine.
the wrong code I think is this: result = result + even[i] * pow(10, i);
Can you help on this?
Thanks in advance.
why do you have to read as number?
Simplest algorithm would be
Read as text
Validate
loop through and confirm if divisible by 2 and print live
next thing, have you try to debug?
debug would let you know what are doing wrong. Finally the issue is with indexing.
evenNumberCount ++; /// this is technically in the wrong place.
even[i]=inputNumberArray[i]; /// This is incorrect.
As the user Popeye suggested, an easier approach to accomplish this would be to just read in the entire input from the user as a string. With this approach, you can iterate through each letter in the char array and use the isdigit() method to see if the character is a digit or not. You can then easily check if that number is even or not.
Here is a quick source code I wrote up to show this approach in action:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main()
{
char input[100] = { '\0' };
char outputNum[100] = { '\0' };
// Get input from user
printf("Enter a number: ");
scanf_s("%s", input, sizeof(input));
// Find the prime numbers
int outputNumIndex = 0;
for (int i = 0; i < strlen(input); i++)
{
if (isdigit(input[i]))
{
if (input[i] % 2 == 0)
{
outputNum[outputNumIndex++] = input[i];
}
}
}
if (outputNum[0] == '\0')
{
outputNum[0] = '0';
}
// Print the result
printf("Result is %s", outputNum);
return 0;
}
I figured out the solution, which is easier to understand.
#include <stdio.h>
#include <math.h>
#define INIT_VALUE 999
int extEvenDigits1(int num);
void extEvenDigits2(int num, int *result);
int main()
{
int number, result = INIT_VALUE;
printf("Enter a number: \n");
scanf("%d", &number);
printf("extEvenDigits1(): %d\n", extEvenDigits1(number));
extEvenDigits2(number, &result);
printf("extEvenDigits2(): %d\n", result);
return 0;
}
int extEvenDigits1(int num)
{
int result = -1;
int count = 0;
while (num > 1) {
int digit = num % 10;
if (digit % 2 == 0) {
result = result == -1 ? digit : result + digit * pow(10, count);
count++;
}
num = num / 10;
}
return result;
}
}
You are overcomplicating things, I'm afraid.
You could read the number as a string and easily process every character producing another string to be printed.
If you are required to deal with a numeric type, there is a simpler solution:
#include <stdio.h>
int main(void)
{
// Keep asking for numbers until scanf fails.
for (;;)
{
printf("Enter a number:\n");
// Using a bigger type, we can store numbers with more digits.
long long int number;
// Always check the value returned by scanf.
int ret = scanf("%lld", &number);
if (ret != 1)
break;
long long int result = 0;
// Use a multiple of ten as the "position" of the resulting digit.
long long int power = 1;
// The number is "consumed" while the result is formed.
while (number)
{
// Check the last digit of what remains of the original number
if (number % 2 == 0)
{
// Put that digit in the correct position of the result
result += (number % 10) * power;
// No need to call pow()
power *= 10;
}
// Remove the last digit.
number /= 10;
}
printf("result is %lld\n\n", result);
}
}
Assigned task is to ask for # of values, and then at the end output the minimum, maximum, and average values and at this point I've run out of bug fixes
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
int main()
{
int ErrorDetection = 1;
char valCounter;
int valnumber;
int Incrementer;
int StoredValue;
int MinimumValue = 100;
int MaximumValue = 0;
float Average;
int AddToStored;
int Sum = 0;
printf("MIN, MAX, and MEAN CALCULATOR\n\n");
while (ErrorDetection != 0)
{
printf("How many values are to be entered?\n");
scanf("%s", &valCounter);
if (valCounter > '0' && valCounter < '9') {
ErrorDetection = 0;
}
else {
ErrorDetection = 1;
printf("INPUT ERROR!\n");
}
valCounter = valCounter - 47;
}
for (Incrementer = 1; Incrementer < valCounter; Incrementer++)
{
ErrorDetection = 1;
while (ErrorDetection != 0) {
printf("Value %d: ", Incrementer);
scanf(" %d", &StoredValue);
if (StoredValue > 0 && StoredValue < 9) {
ErrorDetection = 0;
}
else {
ErrorDetection = 1;
printf("INPUT ERROR!\n");
continue;
}
}
if (StoredValue > MaximumValue) {
MaximumValue = StoredValue;
}
if (StoredValue <= MinimumValue) {
MinimumValue = StoredValue;
}
Sum = Sum + StoredValue;
}
valCounter = valCounter - 1;
Average = (float)Sum / (float)valCounter;
printf(
"Minimum value is %d, maximum value is %d, and average value is %g.\n",
MinimumValue, MaximumValue, Average
);
}
If you input a 2 digit number things begin to breakdown, but at the same time I don't know how to go through with errorchecking if I allow multiple digit answers, as I make use of ASCII conversions to check if an input is a number or not.
You have undefined behavior here.
char valCounter;
scanf("%s", &valCounter);
You have declared valCounter as char type but trying to read string type.
Hence change the scanf to.
scanf("%c", &valCounter);
I would suggest you declare valCounter as int
int valCounter;
scanf("%d", &valCounter);
in that case your if will become.
if ((valCounter > 0) && (valCounter < 9))
and you don't need
valCounter = valCounter - 47; //remove
Also your for loop should start from 0 instead of 1
for(Incrementer = 1 ; Incrementer < valCounter; Incrementer++)
should be
for(Incrementer = 0 ; Incrementer < valCounter; Incrementer++)
Your problem is here.
char valCounter;
scanf("%s", &valCounter);
You're telling scanf to read a string, but you're passing it the address of a character. You should be asking for an integer, and giving it the address of an integer.
int valCounter;
scanf("%d", &valCounter)
There's more information here, including reasons why scanf might not be the best idea:
How to scanf only integer?
I would like to get an output of the biggest even number. but when I input 1 2 3 (3 calls to scanf) the output is 4.
#include <stdio.h>
#include <stdlib.h>
int main() {
int ary[100];
int x, y = 0;
int amount;
scanf("%d", &amount);
fflush(stdin);
for (x = 1; x <= amount; x++) {
scanf("%d", &ary[x]);
if (ary[x] % 2 == 0) {
if (ary[0] < ary[x]) {
ary[0] = ary[x];
}
}
}
printf("%d", ary[0]);
getchar();
return 0;
}
Before the loop initialize ary[0] for example the following way (otherwise uninitialized value of ary[0] is used in the program)
ary[0] = 1;
then substitute these if statements
if(ary[x]%2==0)
{
if(ary[0]<ary[x])
for
if( ary[x]%2==0 && ( x == 1 || ary[0]<ary[x] ) )
And at last write
if ( ary[0] != 1 ) printf("%d",ary[0]);
Take into account that this call
fflush(stdin);
has undefined behavior and should be removed.
In fact there is no need to declare an array. Without the array the program can look like
#include <stdio.h>
int main( void )
{
unsigned int n;
int max_even = 1;
printf("How many numbers are you going to enter: ");
scanf("%u", &n);
int x;
for (unsigned int i = 0; i < n && scanf( "%d", &x ) == 1; i++)
{
if ((x % 2) == 0 && (max_even == 1 || max_even < x))
{
max_even = x;
}
}
if (max_even != 1)
{
printf("maximum entered even number is %d\n", max_even);
}
else
{
puts("None even number was enetered");
}
return 0;
}
Its output might look like
How many numbers are you going to enter: 10
0 1 2 3 4 5 6 7 8 9
maximum entered even number is 8
#include <stdio.h>
#include <stdlib.h>
int main() {
int ary[100];
int ary[0 = 0;
int x, y = 0;
int amount;
scanf("%d", &amount);
fflush(stdin);
for (x = 1; x <= amount; x++) {
scanf("%d", &ary[x]);
if (ary[x] % 2 == 0) {
if (ary[0] < ary[x]) {
ary[0] = ary[x];
}
}
}
printf("%d", ary[0]);
getchar();
return 0;
}
Your code does not work because ary[0] is not yet initialized the first time you compare its value to the value read, furthermore it might not be even for the other comparisons.
You should use an indicator telling you whether an even value has been seen.
Here is a solution:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int has_even = 0, max_even = 0, value, amount, x;
if (scanf("%d", &amount) != 1)
return 1;
for (x = 0; x < amount; x++) {
if (scanf("%d", &value) != 1)
break;
if (!has_even || value > max) {
max_even = value;
has_even = 1;
}
}
if (has_even)
printf("%d\n", max_even);
else
printf("no even value\n");
getchar();
return 0;
}