Related
I have this super simple code for calculating averages of given even and odd numbers, until the user gives 0. (I would use for loop but we can't).
I'm having a really strange problem with program rounding results like 25/2 is 2.00000. Sorry if this question is stupid but I just can't find a problem.
What am I doing completely wrong?
#include <stdio.h>
#include <stdlib.h>
void funkcja()
{
int sumaNiep = 0;
int sumaPa = 0;
int userInput = 1;
int i = 0;
while(userInput != 0)
{
//wprow zmiennej
printf("%d. Podaj calkowita liczbe: ", i+1);
scanf("%d", &userInput);
//jesli parzysta
if (userInput % 2 == 0)
{
sumaPa += userInput;
} else {
sumaNiep += userInput;
}
i++;
}
double sredniaNiep = sumaNiep/(i-1);
double sredniaPa = sumaPa/(i-1);
printf("\nsrednia parzysta %d / %d : %lf", sumaPa, i, sredniaPa);
printf("\nsrednia parzysta %d / %d : %lf", sumaNiep, i, sredniaNiep);
}
int main()
{
funkcja();
}
The problem is that you do an integer division at the end.
You should break out of the loop if the user enters 0 and make at least one operand a double when you do the division. You also need to count the number of evens and odds:
#include <stdio.h>
#include <stdlib.h>
void funkcja() {
int sumaNiep = 0;
int sumaPa = 0;
int userInput = 1;
int iPa = 0;
int iNiep = 0;
int i = 0;
while(1) {
printf("%d. Podaj calkowita liczbe: ", ++i);
if(scanf(" %d", &userInput) != 1 || userInput == 0) break; // break out
// jesli parzysta
if(userInput % 2 == 0) {
sumaPa += userInput;
++iPa; // count evens
} else {
sumaNiep += userInput;
++iNiep; // count odds
}
}
if(iPa) { // avoid div by zero
double sredniaPa = (double)sumaPa / iPa; // double div
printf("srednia parzysta %d / %d : %lf\n", sumaPa, iPa, sredniaPa);
}
if(iNiep) { // avoid div by zero
double sredniaNiep = (double)sumaNiep / iNiep; // double div
printf("srednia parzysta %d / %d : %lf\n", sumaNiep, iNiep, sredniaNiep);
}
}
The problem was I divided by the number of all digits (odd and even) to calculate both averages. Here is improved code:
#include <stdio.h>
#include <stdlib.h>
void funkcja()
{
int sumaNiep = 0;
int sumaPa = 0;
int userInput = 1;
int i_p = 0, i_np = 0;
while(userInput != 0)
{
//wprow zmiennej
printf("%d. Podaj calkowita liczbe: ", i_p+i_np+1);
scanf("%d", &userInput);
//jesli parzysta
if (userInput % 2 == 0)
{
sumaPa += userInput;
if (userInput != 0)
{
i_p++;
}
} else {
sumaNiep += userInput;
i_np++;
}
}
if (i_np != 0)
{
double sredniaNiep = sumaNiep/(i_np);
printf("\nSrednia nieparzysta %d / %d : %lf", sumaNiep, i_np, sredniaNiep);
}
if (i_p != 0)
{
double sredniaPa = sumaPa/(i_p);
printf("\nSrednia parzysta %d / %d : %lf", sumaPa, i_p, sredniaPa);
}
}
int main()
{
funkcja();
}
So I'm having this file myFile.txt with the following numbers in it: 1 2 3 4 5 6 7 8 9 0 2 3 4 5 6 6 5 4 3 2 1. I'm trying to write a program that calculates how many times a number from 0 to 9 is repeated, so it would be printed out like that Number %d repeats %d times. Right now I'm stuck at printing out the n number of elements of that file, so in example, if I would like to calculate how many times the 15 first numbers repeat themselves, firstly I would print out those 15 numbers, then the number of times each number repeats. But when I'm trying to print out those 15 numbers, it prints me this: 7914880640-10419997104210821064219560-1975428800327666414848.
Here's the code:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
int main() {
FILE *fp;
fp = fopen("myFile.txt", "r");
char c;
int n, i, count = 0;
for (c = getc(fp); c != EOF; c = getc(fp)) {
if (!(c == ' '|| c == '\n'))
count = count + 1;
}
printf("The amount of numbers is:%d\nTill which element of the list would you like to count the amount of the each element: \n", count);
scanf("%d", &n);
int a[n];
if (n <= count) {
for (i = 0; i < n; i++) {
fscanf(fp, "%d", &a[i]);
}
for (i = 0; i < n; i++) {
printf("%d", a[i]);
}
} else {
printf("Error");
}
fclose(fp);
return 0;
}
That's the final solution.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
int count_occur(int a[], char exist[], int num_elements, int value)
{
int i, count = 0;
for (i = 0; i<num_elements; i++)
{
if (a[i] == value)
{
if (exist[i] != 0)
return 0;
++count;
}
}
return(count);
}
int main()
{
int a[100],track[10];
FILE *fp;
fp = fopen("myFile.txt", "r");
char c,exist[20]= {0};
int n,i,num,count=0,k=0,eval;
for (c = getc(fp); c != EOF; c=getc(fp))
{
if (!(c==' '|| c=='\n'))
count=count+1;
}
rewind(fp);
printf("The amount of numbers is:%d\nTill which element of the list would you like to count the amount of the each element: \n", count);
scanf("%d", &n);
if (n<=count)
{
while(fscanf(fp, "%d", &num) == 1)
{
a[k] = num;
k++;
}
for (i=0; i<n; i++)
{
printf("%d ", a[i]);
}
}
else
{
printf("Error");
}
fclose(fp);
if (n<=count)
{
for (i = 0; i<n; i++)
{
eval = count_occur(a, exist, n, a[i]);
if (eval)
{
exist[i]=1;
printf("\nNumber %d was found %d times\n", a[i], eval);
}
}
}
return 0;
}
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;
}
}
The below program correctly outputs the divisors of the input numbers, but it does not correctly report whether the inputs are prime. For example, when the input is 13, it does not print "The number you entered is a prime number." What's wrong with it?
#include <stdio.h>
#include <stdbool.h>
int main(void)
{
int num;
bool isPrime = true;
printf("Enter a number: ");
while (scanf("%d", &num) == 1)
{
for (int i = 2; i * i <= num; ++i)
{
if (num % i == 0)
{
if (i * i != num)
{
printf("%d ve %d, divides %d\n", i, num / i, num);
}
else
{
printf("%d divides %d.\n", i, num);
}
isPrime = false;
}
}
}
if (isPrime)
{
printf("The number you entered is a prime number.");
}
return 0;
}
the reason is that scanf is in a while loop if there's a valid input but you are checking & printing if it's prime outside of the loop... if you expect this program just get one input and validate it once, then you just need to change that while to if:
#include <stdio.h>
#include <stdbool.h>
int main(void)
{
int num;
bool isPrime = true;
printf("Enter a number: ");
if (scanf("%d", &num) == 1)
{
for (int i = 2; i * i <= num; ++i)
{
if (num % i == 0)
{
if (i * i != num)
{
printf("%d ve %d, divides %d\n", i, num / i, num);
}
else
{
printf("%d divides %d.\n", i, num);
}
isPrime = false;
}
}
}
if (isPrime)
{
printf("The number you entered is a prime number.");
}
return 0;
}
If you expect this program goes in a loop to keep on getting input and validating if it's prime or not, this should do the job:
#include <stdio.h>
#include <stdbool.h>
int main(void)
{
int num;
bool isPrime = true;
while (1)
{
isPrime=true;
printf("Enter a number: ");
if (scanf("%d", &num) == 1)
{
for (int i = 2; i * i <= num; ++i)
{
if (num % i == 0)
{
if (i * i != num)
{
printf("%d ve %d, divides %d\n", i, num / i, num);
}
else
{
printf("%d divides %d.\n", i, num);
}
isPrime = false;
}
}
}
if (isPrime)
{
printf("The number you entered is a prime number.\n");
}
}
return 0;
}
You have missed 2 things !
You should have printed inside the while loop !
In addition to that you didn't change the status of isPrime=true; !
Hope this answers your question !
#include <stdio.h>
#include <stdbool.h>
int main(void)
{
int num;
bool isPrime = true;
while (scanf("%d", &num) == 1)
{
for (int i = 2; i * i <= num; ++i)
{
if (num % i == 0)
{
if (i * i != num)
{
printf("%d ve %d, divides %d\n", i, num / i, num);
}
else
{
printf("%d divides %d.\n", i, num);
}
isPrime = false;
}
}
if (isPrime)
{
printf("The number you entered is a prime number.\n");
}
isPrime=true;
}
return 0;
}
When you entered a prime number, your while loop doesn't break. Try it:
#include <stdio.h>
#include <stdbool.h>
int main(void) {
int num;
bool isPrime = true, finishIt = false;
printf("Enter a number: ");
while (1) {
while (1) {
if (scanf("%d", &num) != 1)
continue;
if (num == 0) {
finishIt = true;
break;
}
int i;
for (i = 2; i * i <= num; ++i) {
if (num % i == 0) {
if (i * i != num) {
printf("%d ve %d, divides %d\n", i, num / i, num);
} else {
printf("%d divides %d.\n", i, num);
}
isPrime = false;
}
}
if (i * i >= num)
break;
}
if (isPrime) {
printf("The number you entered is a prime number.");
}
isPrime = true;
if (finishIt)
break;
}
return 0;
}
I have the code for finding prime numbers within a range.
The problem is to remove the last comma.
#include<stdio.h>
int main()
{
int a,b,i,x,c,f=1;
scanf("%d%d",&a,&b);
for(x=a;x<=b;(x++,f=0))
{
for(i=2;i<x;i++)
{
if(x%i==0)
{
f=1;
}
}
if(f==0)
printf("%d,",x);
}
}
But the output contains an extra comma in the last.
For example
2,3,5,7,
whereas the expected output is
2,3,5,7
Instead of flag you can decide directly what you want to print between numbers
And note that you can break out of the internal loop as soon as f is set to 1
#include<stdio.h>
int main()
{
int a,b,i,x,c,f=1;
const char* delim = "";
scanf("%d%d",&a,&b);
for(x=a; x<=b; (x++,f=0))
{
for(i=2; i<x; i++)
{
if(x%i==0)
{
f=1;
break; //no need to continue the checking
}
}
if(f==0) {
printf("%s%d",delim,x);
delim = ", ";
}
}
putchar('\n');
}
#include<stdio.h>
int main()
{
int a,b,i,x,c,f=1;
char backspace = 8;
scanf("%d%d",&a,&b);
for(x=a;x<=b;(x++,f=0))
{
for(i=2;i<x;i++)
{
if(x%i==0)
{
f=1;
}
}
if(f==0)
printf("%d,",x);
}
printf("\b"); // or printf("%c", backspace);
}
Add another flag, just a simple counter that tells you if you are printing the first time then check the flag to decide what to print, e.g.
#include<stdio.h>
int main()
{
int a,b,i,x,c,first=0,f=1;
scanf("%d%d",&a,&b);
for(x=a;x<=b;(x++,f=0))
{
for(i=2;i<x;i++)
{
if(x%i==0)
{
f=1;
}
}
if(f==0)
{
if(first==0){
printf("%d",x);
}else{
printf(",%d",x);
}
first++
}
}
}
Use a flag to detect the first occurrence of printf() and print the first number as such without any ,. For consecutive number printing precede with ,
#include<stdio.h>
int main()
{
int a,b,i,x,c,f=1,flag=0;//Flag to mark first occurrence
scanf("%d%d",&a,&b);
for(x=a;x<=b;(x++,f=0))
{
for(i=2;i<x;i++)
{
if(x%i==0)
{
f=1;
break;// Once the condition fails can break of the for loop as it fails for the prime number condition at the first case itself
}
}
if(f==0)
{
if(flag==0)
{//Check if it is first time
printf("%d",x);
flag = 1;//If so print without ',' and set the flag
}
else
printf(",%d",x);// On next consecutive prints it prints using ','
}
}
}
This method also avoids the , when only one number is printed.
Eg: When input is 2 and 4. It prints just 3 and not 3,
Simply you need odd number best practice for minimum loop is given below;
#include<stdio.h>
int main()
{
int a,b,i,x,c,f=1;
scanf("%d%d",&a,&b);
while (a < b)
{
if ( (a%2) == 1) {
printf("%d", a);
if ( (a + 1) < b && (a + 2) < b)
printf(",");
}
a = a + 1;
}
}
please check from the site
http://rextester.com/MWNVE38245
Store the result into a buffer and when done print the buffer:
#include <stdio.h>
#include <errno.h>
#define RESULT_MAX (42)
size_t get_primes(int * result, size_t result_size, int a, int b)
{
int i, x, f = 1;
size_t result_index = 0;
if (NULL == result) || (0 == result_size) || ((size_t) -1 == result_size))
{
errno = EINVAL;
return (size_t) -1;
}
for (x = a; x <= b; (x++, f = 0))
{
for (i = 2; i < x; i++)
{
if (x % i == 0)
{
f = 1;
break;
}
}
if (f == 0)
{
result[result_index] = x;
++result_index;
if (result_size <= result_index)
{
fprintf(stderr, "Result buffer full. Aborting ...\n");
break;
}
}
}
return result_index;
}
int main(void)
{
int a = 0, b = 0;
int result[RESULT_MAX];
scanf("%d%d", &a, &b);
{
size_t result_index = get_primes(result, RESULT_MAX, a, b);
if ((size_t) -1 == result_index)
{
perror("get_primes() failed");
}
else if (0 == result_index)
{
fprintf(stderr, "No primes found.\n");
}
else
{
printf("%d", result[0]);
for (size_t i = 1; i < result_index; ++i)
{
printf(", %d", result[i]);
}
}
}
return 0;
}
This example uses a simple fixed-size buffer, if this does not suite your needs replace it by a dynamic one.
This is more of a "language-agnostic" problem: "How do I output a comma-separated list without a final comma?" It is not specifically about prime numbers.
You seem to be thinking of you list as a series of [prime comma] units. It isn't. A better way to think of it is as a single prime as the head of the list, followed by a tail of repeated [comma prime] units.
Some pseudocode to illustrate the general idea:
outputList(theList)
separator = ", "
output(theList.firstItem())
while (theList.hasMoreItems())
output(separator)
output(theList.nextItem())
endwhile
return
/* this is just logic */
for(i=2;i<=n;i++)
{
k=0;
for(j=2;j<=i/2;j++)
{
if(i%j==0)
k=1;
}
if(k==0)
{
c++;
c++;
}
}
System.out.println(c);
for(i=2;i<=n;i++)
{
k=0;
for(j=2;j<=i/2;j++)
{
if(i%j==0)
k=1;
}
if(k==0)
{
System.out.print(i);
b++;
if(b!=c-1)
{
System.out.print(",");
b++;
}
}
}
}
}
//comma separated values
#include <bits/stdc++.h>
using namespace std;
int Prime(int a, int n){
bool prime[n+1];
memset(prime,true,sizeof(prime));
for(int p=2;p*p<=n;p++){
if(prime[p]==true){
for(int i=p*p ; i<=n; i+=p ){
prime[i] = false;
}
}
}
for(int i = 2;i<= n;i++){
if(i==2) cout<<i; // here is the logic first print 2 then for other numbers first print the comma then the values
else if(prime[i]) cout<<","<<i;
}
}
int main(){
int a =2 ;
int n = 30;
Prime(a , n);
}
#include <stdio.h>
int main()
{
int i, j, n, count;
scanf("%d", &n);
for(i=2; i<n; i++)
{
count=0;
for(j=2; j<n; j++)
{
if(i%j==0)
count++;
}
if(count==1)
printf("%d," i);
}
printf("\b \b");
}
\b is a nondestructive backspace. It moves the cursor backward, but doesn't erase what's there, it replaces it. For a a destructive backspace,
use "\b \b" i.e. a backspace, a space, and another backspace.
This Program prints all the prime number up to given number with comma separated