How to display and add all even numbers? - c

How can I display and add all even numbers? The current code displays numbers between 2 numbers in an ascending manner.
#include <stdio.h>
main() {
int a;
int b;
printf("Enter integer a:");
scanf("%d", &a);
printf("Enter integer b:");
scanf("%d", &b);
if(b > a)
{
do {
printf("Result: %d\n", b);
b--;
} while (a <= b);
}
else
{
do {
printf("Result: %d\n", a);
a--;
} while (a >= b);
}
}

To check if an integer is even you can check if the least significant bit is zero.
To check if an integer is odd you can check if the least significant bit is one.
You can do that using bitwise AND (&).
Something like:
if(b > a)
{
if (b & 1) b--; // Make b even
if (a & 1) a++; // Make a even
int sum = 0;
do
{
sum += b;
printf("b is %d, sum is %d\n", b, sum);
b = b - 2;
} while (b >= a);
}

All even numbers are divisible by 2. You need to check if the remainder of division by 2 is equal to zero. In order to do it, you can use the modulo operator (%).
To display only even numbers:
if ((b%2) == 0) {
printf("Result: %d\n", b);
}

I'd write a function which I could test for different possible combinations of the extremes:
#include <stdio.h>
void evens(int a, int b)
{
// Make sure to always start from the greatest value.
if ( a > b ) {
int tmp = a;
a = b;
b = tmp;
}
// Make sure to always start from an EVEN value.
if ( b % 2 != 0 ) {
--b;
}
int sum = 0;
while ( a <= b ) {
printf("%d ", b);
sum += b;
b -= 2; // Jump directly to the previous even number.
}
printf("\nSum: %d\n", sum);
}
int main(void)
{
// Those should all print "10 8 6 4 2 \nSum: 30\n"
evens(1, 10);
evens(10, 1);
evens(2, 11);
evens(11, 1);
evens(2, 10);
}

Related

How to run a c program using loops to find the remainder of two numbers without using multiplication, division and modulo operators?

#include <stdio.h>
int main()
{
int num1, num2;
printf ("Input value for num1: ");
scanf ("%d", &num1);
printf ("Input value for num2: ");
scanf ("%d", &num2);
int prod =0, i;
for(i = 1; i <= num1; i++){
prod += num2;
}
int quo = 0 , rem = 0;
for(rem = num1 - num2; rem >= 0; rem = rem-num2) {
if(rem < 0)
break;
else
quo++;
}
//The last part is that i need to find the remainder without using multiplication, division and the modulo itself.
printf ("The product of %d and %d is: %d\n", num1, num2, prod);
printf ("The integer quotient of %d and %d is: %d\n", num1, num2, quo);
return 0;
}
The simplest solution for calculating a mod b for positive integers a and b with only subtraction and addition is to subtract b from a until the result is smaller than a. However, this takes many iterations if b is much smaller than a.
A method with better worst-case performance is the following:
#include <stdio.h>
unsigned rem(unsigned a, unsigned b)
{
if(b == 0) return 0; // Error
while(a >= b)
{
unsigned s = b;
do
{
a = a - s;
s = s + s;
} while(a >= s);
}
return a;
}
int main(void)
{
unsigned example = rem(32453, 3);
printf("%u\n", example);
}
This method is based on the fact that to get closer to the result, we can subtract any multiple of b as long as it is smaller than a, so in each inner iteration we try to subtract twice the multiples of the last iteration until the subtractor becomes too large and we start over again with a single multiple of b.
Be aware that this will give wrong results if s = s + s; overflows the unsigned range. Hence, a should not be larger than half the upper limit of unsigned.
If you want a slow calculation of num1 % num2 (i.e. without multiplication/division) you can do:
// Calculate num1 % num2
unsigned rem(unsigned num1, unsigned num2)
{
if (num2 == 0) {.... error handling ....}
while (num1 >= num2) num1 -= num2;
return num1;
}
int main(void)
{
unsigned num1 = 42;
unsigned num1 = 3;
unsigned rem = rem(num1, num2);
printf("%u", rem);
return 0;
}

Why is this program giving the result 0 or garbage value although all the conditions have been met?

Why is this program giving the result 0 or garbage value although all the conditions have been met ?
As i read it is okay to write the if...else without the else clause.
// Program to find the largest of three given numbers
#include <stdio.h>
int main()
{
int a, b, c, big;
printf("Enter three given numbers : ");
scanf("%d%d%d", &a, &b, &c);
// if (1>2) (1>3) (2>3)
if (a > b) // 1>2
{
if (a > c)
big = a;
else
big = c;
}
printf("The largest numnber is = %d",big);
return 0;
}
To make it more clear this if statement
if (a > b) // 1>2
{
if (a > c)
big = a;
else
big = c;
}
may be rewritten like
if (a > b) // 1>2
{
//.. unimportant
}
provided that a is not greater than b. That is in this case the sub-statement of the if statement that represents the compound statement will not get the control. And as a result the variable big will not be initialized.
Your program could look the following way
#include <stdio.h>
int main( void )
{
int a = 0, b = 0, c = 0, big;
printf( "Enter three numbers: " );
scanf( "%d %d %d", &a, &b, &c );
if ( !( a < b ) && !( a < c ) )
{
big = a;
}
else if ( !( b < c ) )
{
big = b;
}
else
{
big = c;
}
printf( "The largest number is = %d\n", big );
return 0;
}
Pay attention to that the user can enter for example three numbers equal each other.
You are missing the branch where this is false:
if (a > b)
big will then be left uninitialized and have an indeterminable value.
To catch all combinations using only two comparisons, you could do like this:
if (a > b) big = a;
else big = b;
if(c > big) big = c;
A more general form:
int arr[...] = {filled with values};
big = arr[0];
for(size_t i = 1; i < sizeof arr / sizeof *arr; ++i) {
if(arr[i] > big) big = arr[i];
}
My two cents for the simplest solution:
#include <stdio.h>
int main()
{
int big, b, c; // only need 3 variables
printf("Enter three given numbers : ");
// should check this return value
scanf_s("%d%d%d", &big, &b, &c); // assume first value entered is largest
if (b > big) big = b; // b larger? reassign
if (c > big) big = c; // c larger? reassign
// big is now the largest number entered
printf("biggest number is %d\n", big);
return 0;
}
Logically your programm is not correct. After if you should use else.
In your programm, when you input numbers {1,2,3}, big is never initialized. However if you input {3,2,1} it will output correct result.
#include <stdio.h>
int main()
{
int a, b, c, big;
printf("Enter three given numbers : ");
scanf_s("%d%d%d", &a, &b, &c);
if (a > b)
{
if (a > c)
big = a;
else
big = c;
printf("The largest numnber is = %d", big);
}
else
printf("The largest numnber is not detected");
return 0;
}

Write a recursive function in C that prints all odd numbers(backwards) and when it reaches 1 it stops

I am first time poster here. Like the tittle says I need to print all odd numbers via a recursive function. The problem is that I have created a simple program that does that, but when it reaches 1(which should be the point where the program stops) the program crashes and I honestly do not see where is the problem. My professor said that I forgot to put a return somewhere, but I honestly do not know where. So if someones can point out the problem that would be great(ps. I am using Code::Blocks as my IDE).
int main() {
int a, b;
printf("Unesi neki broj: \n");
scanf("%d", &a);
b = koko(a);
printf(b);
}
int koko(int a) {
if (a == 1) {
return a;
}
if (a % 2 != 0) {
printf("Ovaj broj je neparan: %d \n", a);
}
koko(a - 1);
}
First, you have to declare the function koko; for using it in main function.
int koko(int a);
Secondly, printf(b) need to define the type to print out:
printf("%d\n", b);
Finally, Using return koko(a - 1); instead of koko(a-1) because this function has to return an int value.
Then, the complete code:
#include <stdio.h>
#include <stdlib.h>
int koko(int a);
int main() {
int a, b;
printf("Unesi neki broj: \n");
scanf("%d", &a);
b = koko(a);
printf("%d\n", b);
return 0;
}
int koko(int a) {
if (a == 1) {
return a;
}
if (a % 2 != 0) {
printf("Ovaj broj je neparan: %d \n", a);
}
return koko(a - 1);
}
enter image description here
int koko(int a)
{
if (a % 2 != 0)
{
printf("Ovaj broj je neparan: %d \n", a);
}
if (a == 1) {
return a;
}
koko(a - 1);
}
int main()
{
int a, b;
printf("Unesi neki broj: \n");
scanf("%d", &a);
b = koko(a);
printf(" koko(a) return %d", b);
return 0;
}

divide a 4-digit integer into 2-digit integers and calculate by c

//Enter a 4-digit integer n from the keyboard, and write a program to divide it into two 2-digit integers a and B. Calculate and output the results of the addition, subtraction, multiplication, division and redundancy operations of the split two numbers. For example, n=-4321, if the two integers after splitting are a and b, then a=-43 and b=-21. The result of division operation requires that it be precise to 2 decimal places, and the data type is float. Redundancy and division operations need to take into account the division of 0, that is, if the split B = 0, then output the prompt information "The second operator is zero!"
//Failure to pass the test,how should i fix
#include<stdio.h>
#include<math.h>
int main()
{
int x, a, b;
printf("Please input n:\n");
scanf("%d", &x);
a = x / 100;
b = x % 100;
printf("%d,%d\n", a, b);
printf("sum=%d,sub=%d,multi=%d\n", a + b, a - b, a*b);
if (b == 0)
printf("The second operater is zero!");
else
printf("dev=%.2f,mod=%d\n", (float)a / b, a%b);
}
You forgot to check that x is a 4-digits number. So if the input is 12345 or 123 you don't satisfy the requirement.
#include <stdio.h>
int main()
{
int x, a, b;
int passed = 0;
// Enter a 4 digits number: ABCD
do {
printf("Enter X = ");
scanf("%d", &x);
passed = (x >= 1000 && x <= 9999) || (x >= -9999 && x <= -1000);
} while (!passed);
a = x / 100;
b = x % 100;
printf("Numbers: %d %d \n", a, b);
printf("Sum = %d \n", a + b);
printf("Sub = %d \n", a - b);
printf("Mul = %d \n", a * b);
if (0 == b) {
printf("Div by Zero \n");
} else {
printf("Div = %f \n", (double)a / b);
printf("Mod = %d \n", a % b);
}
return 0;
}

Find a two digit number with recursion

I'm trying to code something in C by using recursion.
The user writes two positive numbers of same length and the program gives him a new number, which is composed like this :
new number unity digit = the smallest digit in the second positive number that the user wrote.
new number ten digit = the biggest digit in the first positive number that the user wrote.
Very simple in fact, here is an example :
5642 and 2371
will give us : 61.
I tried something like this :
#include <stdio.h>
int calcPair(int a, int b){
int number = calcPair(a/10, b/10);
int digit1 = (number/10);
int digit2 = number%10;
if(digit1 < a%10){
digit1 = a%10;
}
if(digit2 > b%10){
digit2 = b%10;
}
return(number);
}
int main()
{
int a, b, number=0;
printf("Please enter two positive number of same length:\n");
scanf("%d", &a);
scanf("%d", &b);
calcPair(a, b);
printf("The two-digit number composed from %d, %d is: %d", a, b, number);
return 0;
}
BUT the program doesn't run at all.. and closes.
Maybe someone can correct me ? Or helping me finding the mistake.
Thanks by advance.
Your recursion can never end. Consider the following line in calcPair:
int number = calcPair(a/10, b/10);
This statement will always be executed unless you make it conditional, such as:
int number;
if((a != 0) || (b != 0))
number = calcPair(a/10, b/10);
Eventually, because you're dividing both numbers by 10, this condition will prove FALSE.
Something like this:
int calcPair(int a, int b){
int number;
if (a < 10 && b < 10) {
number = a*10 + b;
} else {
int digita = a%10;
int digitb = b%10;
number = calcPair(a/10, b/10);
if(digita > number/10){
number = digita*10 + number%10;
}
if(digitb < number%10){
number = (number/10)*10 + digitb;
}
}
return number;
}
Also, a small fix to the main:
int main()
{
int a, b, number=0;
printf("Please enter two positive number of same length:\n");
scanf("%d", &a);
scanf("%d", &b);
number = calcPair(a, b);
printf("The two-digit number composed from %d, %d is: %d", a, b, number);
return 0;
}
I think you can refactor your code to be more expressive of your requirement, with a few helper functions.
int greater(int a, int b)
{
return (a>b);
}
int less(int a, int b)
{
return (a<b);
}
int pickDigit(int n, int (*func)(int, int))
{
int ret = n%10;
n /= 10;
while ( n > 0 )
{
if ( fun(n%10, ret) )
{
ret = n%10;
}
n /= 10;
}
return ret;
}
int getBiggestDigit(int n)
{
return pickDigit(n, greater);
}
int gteSmallestDigit(int n)
{
return pickDigit(n, less);
}
int numDigits(int n)
{
int ret = 0;
while (n > 0 )
{
++ret;
n /= 10;
}
return ret;
}
int calcPair(int a, int b)
{
if ( numDigits(a) != numDigits(b) )
{
// Deal with error.
}
return betBiggestDigit(a)*10+getSmallestDigit(b);
}
Whether or not you are allowed to (you did not specify in OP),
here is a recursive search method using strings :
Strings are just an array of char. because you are interested in distinguishing the individual digits within a larger integer, the char data type will be a sufficient size container to facilitate the comparison.
Using arrays of char (strings) within a recursive function with exit criteria of strlen() > 0 will allow you to walk through each integer, and select the appropriate value (min or max).
This approach uses two recursive functions: getMinDigit() and getMaxDigit(), both returning a char representing the maximum value digit, or minimum value digit of their respective original multi-digit integer. These results are then concatenated, and converted back into a two digit integer.
Here is the example code that given:
5642 and 2371
will give us : 61.
char getMinDigit(char *digit)
{
static char val='9';//largest single digit base 10
int len=0;
if(strlen(digit) > 0)
{
len = strlen(digit);
if(digit[len-1] < val) //test for smallest char in string
{
val = digit[len-1];
digit[len-1] = 0;
getMinDigit(digit);
}
else
{
digit[len-1] = 0;
getMinDigit(digit);
}
}
return val;
}
char getMaxDigit(char *digit)
{
static char val='0'; //smallest single digit base 10
int len=0;
if(strlen(digit) > 0)
{
len = strlen(digit);
if(digit[len-1] > val) //search for largest char in string
{
val = digit[len-1];
digit[len-1] = 0;
getMaxDigit(digit);
}
else
{
digit[len-1] = 0;
getMaxDigit(digit);
}
}
return val;
}
int calcPair(int a, int b)
{
char big[10]={""}, small[10]={""};
char Big, Small;
char result[3]={""};
sprintf(big, "%d", a);
sprintf(small, "%d", b);
Big = getMaxDigit(big); //recursive function
Small = getMinDigit(small); //recursive function
sprintf(result, "%c%c", Big, Small);
return atoi(result);
}
int main(void)
{
int result = calcPair(5642, 2371);
printf("%d", result);
return 0;
//for illustration, hard coded to OP values
//int a, b, number=0;
//printf("Please enter two positive number of same length:\n");
//scanf("%d", &a);
//scanf("%d", &b);
//calcPair(a, b);
//printf("The two-digit number composed from %d, %d is: %d", a, b, number);
//return 0;
}

Resources