I'm trying to check if five numbers are odd or even. I want to use a for-loop that iterates 5 times and uses a for loop that checks if the number is odd or even.
Code:
#include <stdio.h>
int main()
{
int a ,b ,c ,d ,e;
scanf("%d %d %d %d %d", &a, &b ,&c ,&d ,&e);
int count = 5;
for (int i = 0; i < count; i++)
{
if(num % 2 == 0) //num should be a then b then c etc.
printf("even");
else
printf("odd");
}
}
I cant find any information about swapping/switching variables inside a loop/statment. If anyone has an answer or where to find the information i will be forever grateful!
Thanks in advance!
//Noob programmer
Instead of scanf-ing into distinct variables (a, b, etc.), perhaps you can scanf into an array of integers.
Then you can use indexing of the array.
int num = numbers[i];
Within the for loop.
As I mentioned in a comment, this can be solved with only a single variable and without arrays:
#include <stdio.h>
int main()
{
unsigned const count = 5;
for (unsigned i = 0; i < count; i++)
{
printf("Please enter a number: ");
fflush(stdout); // To make sure the output is printed
int number;
scanf("%d", &number); // Note: Doesn't handle errors
if (number % 2 == 0)
{
printf("The number %d is even\n", number);
}
else
{
printf("The number %d is odd\n", number);
}
}
}
If you do not want to learn the arrays there is a hardcore way of doing it:
for (int i = 0; i < count; i++)
{
switch(i)
{
case 0:
num = a;
break;
case 1:
num = b;
break;
/* etc etc etc */
}
}
Our teacher gave us an exercise in C. We have to create a program that accepts three integers and outputs them if they are odd or even without using arrays, only loops and conditional statements can be used.
What I am only allowed to use are scanf(), printf(), loops and conditional statements. I must not have multiple variables like odd1, odd2, odd3, even1, even2, even3.And I must not do scanf("%d %d %d",), so I must run scanf("%d") three times in a loop.I couldn't think of any idea that would precisely print the same format of the expected output. I hope someone could help me on this
#include <stdio.h>
int main() {
int i, num;
printf("Enter three integers: ");
for(i=1;i<=3;i++)
{
scanf("%d", &num);
if(!(num%2))
{
printf("\nEven: %d", num);
}
if(num%2)
{
printf("\nOdd: %d\n", num);
}
}
}
I expect the following like this...
Input:
1 2 3
Output:
Odd: 1 3
Even: 2
Input:
2 4 6
Output:
Odd:
Even: 2 4 6
...but the only thing i can do is this
Input:
1 2 3
Output:
Odd: 1
Even: 2
Odd: 3
Input:
1 3 5
Output:
Odd: 1
Odd: 3
Odd: 5
Recursion (loop in disguise) for the win (if you don't mind having the even numbers reversed).
#include <stdio.h>
#include <stdlib.h>
void separate(int m, int n) {
if (m == n) printf("Odd:");
if (n == 0) { printf("\nEven:"); return; }
int i;
if (scanf("%d", &i) != 1) exit(EXIT_FAILURE);
// print odd numbers before recursing; even numbers after recursing
if (i % 2 == 1) printf(" %d", i);
separate(m, n - 1);
if (i % 2 == 0) printf(" %d", i);
if (m == n) printf("\n\n");
}
See https://ideone.com/GpE7rC which includes the calling and input
separate(3, 3); // for 3 numbers
One way would be say:
int odd1, odd2, odd3, numOdd = 0;
/* Code as above */
scanf("%d", &num);
if (num%2)
{
if (numOdd == 0)
{
odd1 = num;
numOdd++;
}
else if (numOdd == 1)
{
odd2 = num;
numOdd++;
}
/* And continue */
}
else
{
/* Repeat with even1, even2, even3 and numEven */
}
/* Print out numOdd oddn's */
/* Print out numEven evenn's */
It seems a silly exercise, but at least you'll get a lot of practise writing if statements...
I also thought:
scanf("%d", &num1);
scanf("%d", &num2);
scanf("%d", &num3);
Might be shorter, but then you don't need a for loop, unless you do something like:
printf("Odd: ");
for (i = 0; i < 3; i++)
{
int thisNum;
if (i == 0) thisNum = num1;
else if (i == 1) thisNum = num2;
/* etc */
if (thisNum % 2) printf("%d ", thisNum);
}
The problems is that you cannot use arrays. Hence you must not use strings, which are arrays. Allowing the use of scanf and printf is a deliberate trap set by your teacher - there is no way of using them in an useful way without resorting to use of arrays, explicit or implied.
Therefore you must do this:
#include <stdio.h>
#include <ctype.h>
void print_number(int n)
{
if (n < 0) {
putchar('-');
n = -n;
}
if (n == 0)
putchar('0');
if (n / 10)
print_number(n / 10);
putchar(n % 10 + '0');
}
int main(void) {
putchar('E');
putchar('n');
putchar('t');
putchar('e');
putchar('r');
putchar(' ');
putchar('t');
putchar('h');
putchar('r');
putchar('e');
putchar('e');
putchar(' ');
putchar('i');
putchar('n');
putchar('t');
putchar('e');
putchar('g');
putchar('e');
putchar('r');
putchar('s');
putchar(':');
putchar(' ');
fflush(stdout);
int odd1, odd2, odd3, odd_count = 0;
int even1, even2, even3, even_count = 0;
for(int i = 0; i < 3; i++)
{
int number = 0;
int c;
while (1) {
c = getchar();
if (isspace(c)) {
if (c == '\n')
break;
while ((c = getchar()) == ' ');
ungetc(c, stdin);
break;
}
else if (isdigit(c)) {
number = number * 10 + c - '0';
}
}
if (number % 2) {
switch (odd_count) {
case 0: odd1 = number; break;
case 1: odd2 = number; break;
case 2: odd3 = number; break;
}
odd_count ++;
}
else {
switch (even_count) {
case 0: even1 = number; break;
case 1: even2 = number; break;
case 2: even3 = number; break;
}
even_count ++;
}
}
putchar('O');
putchar('d');
putchar('d');
putchar(':');
putchar(' ');
if (odd_count >= 1) {
print_number(odd1);
}
if (odd_count >= 2) {
putchar(' ');
print_number(odd2);
}
if (odd_count >= 3) {
putchar(' ');
print_number(odd3);
}
putchar('\n');
putchar('E');
putchar('v');
putchar('e');
putchar('n');
putchar(':');
putchar(' ');
if (even_count >= 1) {
print_number(even1);
}
if (even_count >= 2) {
putchar(' ');
print_number(even2);
}
if (even_count >= 3) {
putchar(' ');
print_number(even3);
}
putchar('\n');
}
This code does not use any arrays.
If you cannot define any functions (other than main obviously), you must inline the print_number in the 6 places changing the recursion into iteration. Good luck!
If the teacher however accepts the use of strings in a task that does not allow the use of arrays, you can take it as a license to disregard all silly restrictions set by them.
Given the fact that you are learning C, perhaps your teacher wants to teach you some pointer arithmetics instead of using arrays like in this code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i = 0;
int *odd = (int*)malloc(3 * sizeof(int));
int odd_count = 0;
int *even = (int*)malloc(3 * sizeof(int));
int even_count = 0;
printf("Enter three integers: ");
for(i=0; i<3; i++)
{
int num = 0;
scanf("%d", &num);
if(!(num%2))
{
*even++ = num;
even_count++;
}
if(num%2)
{
*odd++ = num;
odd_count++;
}
}
even -= even_count;
odd -= odd_count;
printf("\nEven: ");
for(i=0; i<even_count; i++)
{
printf("%d ", *even++);
}
printf("\nOdd: ");
for(i=0; i<odd_count; i++)
{
printf("%d ", *odd++);
}
free(odd);
free(even);
return 0;
}
This question already has answers here:
Variable leading zeroes in C99 printf
(1 answer)
printf string, variable length item
(2 answers)
Closed 5 years ago.
I've written a programm for college where I print out all prime number twins between two numbers. (f.e. between 1 and 12000)
In my printing statement i've written %04d for 4 digits. But what i want to do is to make this variable. (I tried %0%dd, but this didnt work.) I dont want to do write just the max digit count of int. I count hte digits of the int with int count = floor(log10(abs(b))) + 1;
Heres my complete code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int isPrime(int a);
void listOfPrimeNumberTwins(int a, int b);
typedef int twins[10000][2];
int main(){
int a;
int b;
printf("Check if prime:\nEnter number: ");
scanf(" %d", &a);
b = isPrime(a);
if (b == 0){
printf("No Prime!");
} else if (b == -1){
printf("Negative number!");
} else {
printf("Prime!");
}
printf("\nPrime Number Twins:\nEnter number 1: ");
scanf(" %d", &a);
printf("Enter number 2: ");
scanf(" %d", &b);
listOfPrimeNumberTwins(a,b);
}
int isPrime(int a){
int i;
int b = 0;
if (a == 1){
return 0;
}
if (a <= 0){
return -1;
}
for (i = 2; i < a; i++){
if (a % i == 0){
return 0;
}
}
return 1;
}
void listOfPrimeNumberTwins(int a, int b){
int count = floor(log10(abs(b))) + 1;
int i;
int j = 0;
twins c;
b -= 1;
for (i = a; i < b; i++){
if (i > 1 && isPrime(i) == 1 && isPrime(i + 2) == 1){
c[j][0] = i;
c[j][1] = i + 2;
j += 1;
}
}
if (j == 0){
printf("No Prime number twins between %d and %d!", a,b);
} else {
printf("Prime number twins between %d and %d:\n", a,b);
for (i = 0;i < j; i++){
printf("%04d\t<-->\t%04d\n", c[i][0],c[i][1]);
}
}
}
How can I achieve what I want? Or is it just impossible like I want it?
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
For my programming assignment I have to create 3 programs that print out an asterisk based triangle in c based on the user's input. The difference between the 3 programs would be one will use for loops, the other would use while loops and the last one would use goto. I have the for loop program as well as the goto program, but as for the while loop program I'm not sure how incorporate it into my program. This is my program with a for loop and the second program is my attempt at the while loop version.
#include <stdio.h>
int main() {
int lines, a, b;
//prompt user to input integer
do{
printf("Input a value from 1 to 15: ");
scanf("%d", &lines);
//Check if inputed value is valid
if(lines < 1 || lines > 15) {
printf("Error: Please Enter a Valid number!!!\n");
continue;
}
/*create triangle based on inputed value */
for(a = 1; a <= lines; a++) {
for(b=1; b<= a; b++) {
printf("*");
}
printf("\n");
}
} while(1);
system("pause");
}
Progam #2:
#include <stdio.h>
int main() {
int lines, a = 1, b = 1;
//prompt user to input integer
do{
printf("Input a value from 1 to 15: ");
scanf("%d", &lines);
//Check if inputed value is valid
if(lines < 1 || lines > 15) {
printf("Error: Please Enter a Valid number!!!\n");
continue;
}
while(a <= lines) {
a++;
while (b <= a) {
b++;
printf("*");
}
printf("\n");
}
} while(1);
system("pause");
}
Here is how you convert a for loop like the following
for (stat1; stat2; stat3) {
stat4;
}
to a while loop
stat1;
while (stat2) {
stat4;
stat3;
}
So here is the while loop you want:
a = 1;
while(a <= lines) {
b = 1;
while (b <= a) {
printf("*");
b++;
}
printf("\n");
a++;
}
Set b=1 before 2nd while loop
while(a <= lines) {
a++;
b=1; //you want to start b from 1 for each inner loop
while (b <= a) {
b++;
printf("*");
}
printf("\n");
}
The program2 can be changed as below. The below code result is equivalent to program1.`
#include <stdio.h>
int main() {
int lines, a = 1, b = 1;
//prompt user to input integer
do{
printf("Input a value from 1 to 15: ");
scanf("%d", &lines);
//Check if inputed value is valid
if(lines < 1 || lines > 15) {
printf("Error: Please Enter a Valid number!!!\n");
continue;
}
while(a <= lines) {
//a++;
while (b <= a) {
b++;
printf("*");
}
b =1;
a++1;
printf("\n");
}
} while(1);
system("pause");
}`