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 */
}
}
Related
I'm pretty new in programming and I making a decimal to binary converter. I need help to make the print output starts from right to left (reversed).(Sorry if my code is messy)
int main()
{
int num, form;
printf("Decimal to Binary\n\n");
printf(" Value : ");
scanf("%d", &num);
printf(" Expected Format (Type 2 for binary): ");
scanf("%d", &form);
if (form == 2)
printf(" %d base 10 is ", num);
if (form == 2)
do {
if (num % 2 == 0) {
printf("0");
num = num / 2;
}
else {
printf("1");
num = num / 2;
}
} while (num > 0);
else
printf("Invalid input!");
return 0;
}
If I input the value to 25,I expected the output will be "11001", but the actual output is "10011"
Some recursion.. It's looks much more better, for my opinion
#include <stdio.h>
void rec(int num)
{
if (num==0) return;
rec(num>>1);
printf("%d", num%2);
}
int main()
{
int n;
printf("Enter an integer in decimal number system\n");
scanf("%d", &n);
printf("%d in binary number system is: ", n);
rec(n);
printf("\n");
return 0;
}
One possibility would be recursion as Jean-Francois Fabre said. Since you mentioned you are a beginner, recursions are sometimes hard to understand at the beginning, so another possibility that I didn't find in his link would be something like this
#include <stdio.h>
int main()
{
int n, c, k;
printf("Enter an integer in decimal number system\n");
scanf("%d", &n);
printf("%d in binary number system is:\n", n);
for (c = 8; c >= 0; c--)
{
k = n >> c;
if (k & 1)
printf("1");
else
printf("0");
}
printf("\n");
return 0;
}
You can use c to specify the length of your output, or calculate in advance to have a perfect output.
Using a scanf in a for-loop, where do I store the input, if there is more then 1 loop? Trying to use arrays, but it always fails.
Let's say:
Please enter number of octets: 3
Please enter octet: 1
Please enter octet: 2
Please enter octet: 3
Then the input should be stored in the array, but it doesn't work. For the controll, I printf v[2] and it should be 3, but it is a another number.
#include<stdio.h>
#include<limits.h>
int main()
{
int c;
int v[c];
printf("Please enter number of octets:\n");
scanf("%d", &c);
if ( (c > 1) && (c < CHAR_MAX))
{
for ( i = 1; i <= c; i++)
{
printf("Please enter octet:\n");
scanf("%d", x);
v[c]=x;
}
printf("v[2]: %d\n", v[2]);
}
return 0;
}
You probably want this:
#include <stdio.h>
#include <limits.h>
int main()
{
int c;
printf("Please enter number of octets:\n");
scanf("%d", &c);
if ((c > 1) && (c < CHAR_MAX))
{
int v[c];
// scan values into array
for (int i = 0; i < c; i++) // indexes from 0 to c-1 !!
{
printf("Please enter octet:\n");
scanf("%d", &v[i]);
}
// print all values from array
for (int i = 0; i < c; i++)
{
printf("v[%d]: %d\n", i, v[i]);
}
}
else
{
printf("Input error\n"); // show an error message
}
return 0;
}
Not clear what are you trying to do here but if you modify you code like below it will work:-
for ( i = 0; i <= c; i++)
{
printf("Please enter octet:\n");
scanf("%d", &x);
v[i]=x;
}
printf("v[2]: %d\n", v[2]);
and to print all the value just add below codes
for ( i = 0; i <= c; i++)
printf("v[i]: %d\n", v[i]);
From the code you have posted, the following lines may be the reason for the problem.
int c;
int v[c];
This is invalid. In C, array must be declared like this.
data_type array_name[size];
To make your declaration valid, you must either read the value of n or specify it like this.
int c = 10;
int v[c];
Also,
scanf("%d", x);
Change it to
scanf("%d", &x);
I'll try not to answer the question but let me point out the mistakes
#include<stdio.h>
#include<limits.h>
int main()
{
int c; // uninitialized
int v[c]; // this will behave quite unexpectedly because c is uninitialized
printf("Please enter number of octets:\n");
scanf("%d", &c);
if ( (c > 1) && (c < CHAR_MAX)) // c is a int so why restrict to CHAR_MAX
{
for ( i = 1; i <= c; i++) // trying to scan c elements and i is undefined
{
printf("Please enter octet:\n");
scanf("%d", x);
v[c]=x; // assigning to v[c] everytime so if c is 2 v[2] is the only element getting modified. not something you want to
}
printf("v[2]: %d\n", v[2]);
}
return 0;
}
I made a C program to check if a number is palindrome or not. I used the following code, but it shows numbers like 12321 as non palindrome. Can you please explain me the mistake in the program below?
#include <stdio.h>
int main()
{
int i, x, n, c, j;
int d=0;
printf ("enter total digits in number: ");
scanf ("%d", &i);
printf ("\nenter number: ");
scanf ("%d", &n);
j=n;
for (x=1; x<=i; x++)
{
c= j%10;
d=c*(10^(i-x))+d;
j=(j-c)/10;
}
if (d==n)
{
printf ("\npalindrome");
}
else
{
printf ("\nnon palindrome");
}
return 0;
}
^ is the xor operator.
In order to raise power, you need to include math.h and call pow
d = (c * pow(10, i - x)) + d;
this algorithm is as simple as human thinking, and it works
#include <stdio.h>
int main() {
int i=0,n,ok=1;
char buff[20];
printf("Enter an integer: ");
scanf("%d", &n); // i am ommiting error checking
n=sprintf(buff,"%d",n); //convert it to string, and getting the len in result
if(n<2) return 0;
i=n/2;
n--;
while(i && ok) {
i--;
//printf("%c == %c %s\n", buff[i],buff[n-i],(buff[i]==buff[n-i])?"true":"false");
ok &= (buff[i]==buff[n-i]);
}
printf("%s is %spalindrome\n",buff, ok?"":"not ");
return 0;
}
// Yet another way to check for palindrome.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
int n, rn, tn;
printf("Enter an integer: ");
scanf("%d", &n);
// reverse the number by repeatedly extracting last digit, add to the
// previously computed partial reverse times 10, and keep dropping
// last digit by dividing by 10
for (rn = 0, tn = n; tn; tn /= 10) rn = rn * 10 + tn % 10;
if (rn == n) printf("%d is palindrome\n", n);
else printf("%d is not palindrome\n", n);
}
A loop like this might do:
int src; // user input
int n; // no of digits
int res = 0;
int tmp; // copy of src
// .... read the input: n and src ....
tmp = src;
for(int i = 0; i < n; i ++)
{
int digit = tmp % 10; // extract the rightmost digit
tmp /= 10; // and remove it from source
res = 10*res + digit; // apend it to the result
}
// ...and test if(res == src)...
I need to create a simple program which asks for 10 numbers from user and then shows the sum of those numbers or, if the user gives 0 as input, stops and immediately displays the sum of those numbers, and I need to create it only by using a "for" condition. Here is the code:
#include <stdio.h>
int main(){
int num = 0;
for(num = 0; num < 10; num++){
printf("Input a number: \n");
scanf("%d", &num);
if(num == 0){
printf("Sum: %d\n", num);
}
}
printf("Sum: %d\n", num);
getchar();
getchar();
}
It stops only when the number is greater than "10".Whats wrong?
I think you want to do this kind of work with your code.
#include <stdio.h>
int main(){
int num = 0;
int sum=0;
for(num = 0; num < 10; num++){
int i;
printf("Input a number: \n");
scanf("%d", &i);
sum = sum+i;
if(i == 0){
printf("Sum: %d\n", sum);
getchar();
return 0;
}
}
printf("Sum: %d\n", sum);
getchar();
return 0;
}
You are changing the value of the counter inside the for loop. That's why, when you read a value greater than or equal to 10, it will abandon the for loop, since you have the condition num < 10.
Let me tweak the code for you:
#include <stdio.h>
int main(){
int sum = 0;
int i;
int num;
for(i = 0; i < 10; i++){
printf("Input a number: \n");
scanf("%d", &num);
sum += num;
if(num == 0){
break; //means leave the loop
}
}
printf("Sum: %d\n", sum);
getchar();
return 0;
}
I'm using 3 variables:
sum, which is used to store the overall sum.
i, which is used as the for loop counter.
num, which is used to store the current number given by the user.
First of all, I'm waiting for an input:
printf("Input a number: \n");
scanf("%d", &num);
Now, the input is stored in num, so I'm upgrading the sum, to add the new value:
sum += num;
The I check if the current number is zero; in that case I'll just leave the loop:
if(num == 0){
break;
}
The problem in your code is, you're using the same variable num both as counter and for taking user input which is breaking the logic in for loop.
Use another variable for taking user input.
Also, you've to have a break statement to discontinue the for loop once you've got the breaking criteria.
Note: as I mentioned in my comments, there is no logic for Sum.
Check the below code.
#include <stdio.h>
int main(){
int num = 0;
int sum = 0; //to hold the sum
int input = 0;
for(num = 0; num < 10; num++){
printf("Input a number: \n");
scanf("%d", &input);
sum += input; // yoo-hoo, time to add-up
if(input == 0){
printf("Sum: %d\n", sum);
break; // time to say bye-bye to for loop
}
}
if (num == 10) //only print if not printed previously
printf("Sum: %d\n", sum);
return 0;
}
In the main method below I'm trying to call a sort function and after function selects that latter from the user input it has to print the sort accordingly with the for loop at the end. But I have a warning that reads "loop will run at most once (loop increment never executed)" pointing at the array[arraySize]. Does it have to do with the return type or the other for loop above? What's happening here? Can anyone point out and explain please. Thanks much! Here's the code below:
int main()
{
long array[100], arraySize;
char sort;
long maxi = 100;
for(arraySize = 0; arraySize < maxi; arraySize++)
{
printf("Enter any positive integer, enter 0 to stop: ");
scanf("%li", &num);
if(num < 0) {
arraySize--;
printf("I said positive!");
count++;
}
else if(num == 0) {
maxi = arraySize;
}
else {
array[arraySize]=num;
arraySize--;
}
}
printf("Please enter A for ascending or D for descending order\n");
scanf("%s", &sort);
bubble_sort(array, arraySize, sort); //calling the sort function
printf(" Sorted list in the selected order:\n");
for (arraySize = 0; arraySize < num; arraySize++) {
printf("%ld \n", array[arraySize]);
puts("");
return 0;
}
}
EDIT: Thanks everyone for all your suggestions. I did make a few changes and here's what I have so far. Now it's skipping the A/D user input along with the bubble_sort function logic. Here's what it does as a final output: Note: long num is declared as a global variable!
int main()
{
long array[100], arraySize;
char sort;
long maxim = 100;
for(arraySize = 0; arraySize < maxim; arraySize++)
{
printf("Enter any positive integer, enter 0 to stop: ");
scanf("%li", &num);
if(num < 0)
{
arraySize--;
printf("I said positive! \n");
count++;
}
else if(num == 0)
{
maxim = arraySize;
}
else
{
array[arraySize]=num; //arraySize--;
}
}
printf("Please enter A for ascending or D for descending order: \n");
scanf("%c", &sort);
bubble_sort(array, maxim, sort); //calling the sort function
printf("Sorted list in the selected order:\n");
for (arraySize = 0; arraySize < maxim; arraySize++)
{
printf("%ld \n", array[arraySize]);
}
puts("");
return 0;
}
Any more suggestions will be appreciated!
There are a few other problems, but let's talk about your warning. You have this code:
for (arraySize = 0; arraySize < num; arraySize++) {
printf("%ld \n", array[arraySize]);
puts("");
return 0;
}
The corrected indentation should make it obvious why that loop will run at most once.
It seems your print loop has a typo, and should be corrected to:
for (arraySize = 0; arraySize < maxi; arraySize++) {
Also the call to bubble_sort() should use maxi rather than arraySize.
The last character entered gets stored in sort and that character is most probably \n.
Changing scanf("%c", &sort); to scanf(" %c", &sort); should solve the problem.
Note the space before %c.