Program to find biggest of four numbers using nested-if - c

Sir/Ma'am,
I do not know what may be that I'm doing wrong. Logic- wise everything appears correct to me. The braces seem placed in the correct positions as well. Then why is it that I'm receiving the following error messages?
32 8 [Error] expected constructor, destructor, or type conversion before '(' token
33 2 [Error] expected unqualified-id before 'return'
34 1 [Error] expected declaration before '}' token
What am I doing wrong with this particular program? And, I was hoping for a correction using the same statements, and not any other.
Please help!
The program:
#include <stdio.h>
main()
{
int a, b, c, d, big;
printf("\n Enter value to a, b, c, d: ");
scanf("%d %d %d %d", &a, &b, &c, &d);
if (a >b)
{
if(a>c)
{
if(a>d)
big = a;
else
big=d;
}
else
{
if(c>d)
big = c;
else
big = d;
}
else
if(b>c)
{
if(b>d)
big = b;
else
big = d;
}
}
printf("\n The biggest number is %d", big);
return 0;
}

You can use the ternary operator to solve your problem. Thus, the code simplifies to
int main() {
int a, b, c, d;
printf("\n Enter value to a, b, c, d: ");
scanf("%d %d %d %d", &a, &b, &c, &d);
const int big1 = (a > b) ? a : b;
const int big2 = (c > d) ? c : d;
int big = (big1 > big2) ? big1 : big2;
printf("\n The biggest number is %d", big);
}

I do not know what may be that I'm doing wrong. Logic-wise everything appears correct to me.
There are some syntactic errors, though. A construct like
// ...
if ( a > c ) {
// ...
}
else { // <----
// ...
}
else if ( b > c ) {
// ...
}
Is not valid in C.
It's unclear to me how the OP was planning to structure the nested ifs in order to solve the task, but before going on, I'd suggest to write some simple tests to verify the correctness of the algorithm:
#include <stdio.h>
// Prototype of the function which returns the biggest out of the four arguments
int max_of_four(int a, int b, int c, int d);
// Helper function used to verify the correctness of the results
int test_(int a, int b, int c, int d, int expected)
{
int result = max_of_four(a, b, c, d);
if ( result != expected )
{
printf("FAILED - Expected: %d (given %d, %d, %d and %d), instead of %d.\n",
expected, a, b, c, d, result);
return 1;
}
return 0;
}
// Test runner
int main(void)
{
int failed = 0;
// The function should be able to find the biggest regardless of its "position"
failed += test_(1, 2, 3, 4, 4);
failed += test_(4, 3, 2, 1, 4);
failed += test_(2, 1, 4, 3, 4);
failed += test_(3, 4, 1, 2, 4);
// The function should manage negative values
failed += test_(1, -2, -3, -4, 1);
failed += test_(-4, -3, -2, -1, -1);
failed += test_(0, -3, -1, -2, 0);
// The function should manage duplicate values
failed += test_(1, -2, 1, 2, 2);
failed += test_(-4, -3, -3, -5, -3);
failed += test_(1, 1, 1, 1, 1);
if ( failed == 0 )
puts("So far so good.");
return 0;
}
// A simple implentation.
int max_of_four(int a, int b, int c, int d)
{
int big = a;
if ( b > a )
big = b;
if ( c > big )
big = c;
if ( d > big )
big = d;
return big;
}
You can test it here and try to rewrite the function using nested if statements, if you want. Maybe something like
int max_of_four(int a, int b, int c, int d)
{
if ( b > a )
{
if ( d > c )
{
if ( b > d )
return b;
else
return d;
}
else // d <= c
{
if ( b > c )
return b;
else
return c;
}
}
else // b <= a
{
// You got the idea...
}
}

I used the ternary operator instead of if-else statements it works the same as if-else you can check how ternary operator works.
int max_of_four(int a,int b,int c,int d){
return (a < b ? ((b > c)? ((b > d)? b:d) :((c > d)? c: d)) : ((a < c)? ((c > d)? c: d) : ((a > d) ? a : d)));
}
int main() {
int a, b, c, d;
scanf("%d %d %d %d", &a, &b, &c, &d);
int ans = max_of_four(a, b, c, d);
printf("%d", ans);
return 0;
}

You did not consider case when a <= b or it places in wrong position (inside a < b block).
You can imagine problem in a decision tree similar to this (3 numbers) for clearer.
#include <stdio.h>
main() {
int a, b, c, d, big;
printf("\n Enter value to a, b, c, d: ");
scanf("%d %d %d %d", &a, &b, &c, &d);
if (a > b) {
if (a > c) {
if (a > d)
big = a;
else
big = d;
} else {
if (c > d)
big = c;
else
big = d;
}
} else {
if (b > c) {
if (b > d)
big = b;
else
big = d;
}
else {
if (c > d)
big = c;
else
big = d;
}
}
printf("\n The biggest number is %d", big);
return 0;
}

Related

The program needs to show the variable with greater first digit

The program needs to show an number which has a greater first digit, which works, only if the numbers of digits are the same on both variables. Try with these numbers 4506 29985, it should show 4506, but the program shows 29985, the program was written in C language.
#include <stdlib.h>
#include <stdio.h>
int disassembly1 (int a)
{
while (a>=10)
{
a /= 10;
}
return a;
}
int disassembly2 (int b)
{
while (b>=10)
{
b /= 10;
}
return b;
}
int main ()
{
int A1, B1, a, b;
printf("Int 2 numbers:\n");
scanf_s("%d %d", &A1, &B1);
a = A1;
b = B1;
disassembly1(A1);
disassembly2(B1);
if (a > b || ((a == b) && (A1 > B1)))
printf("%d\n", A1);
else
printf("%d\n", B1);
system("pause");
}
First of all, disassembly1 and disassembly2 are the same function and should not written twice.
Second and more important, the function disassembly returns the first digit, but you need to store it in a variable.
A working code (with a few changes):
#include <stdlib.h>
#include <stdio.h>
int disassembly(int a)
{
while (a>=10)
{
a /= 10;
}
return a;
}
int main()
{
int a, b, a_digit, b_digit;
printf("Int 2 numbers:\n");
scanf_s("%d %d", &a, &b);
a_digit = disassembly(a);
b_digit = disassembly(b);
if (a_digit > b_digit || ((a_digit == b_digit) && (a > b)))
printf("%d\n", a);
else
printf("%d\n", b);
system("pause");
return 0;
}
Also, the name disassembly does not match the function meaning. I would suggest to change it to something like get_first_digit.
Your code does not read the values returned from the functions, leaving variables a & b unchanged.
Change:
disassembly1(A1);
disassembly2(B1);
To:
a = disassembly1(A1);
b = disassembly2(B1);
Other suggestions:
define and use a single instance of function: int disassembly(int x); and call it twice.
a = disassembly(A1);
b = disassembly(B1);
Here is a much simpler version (this is matlab/octave, but can easily be ported to c)
a = 4506;
b = 29985;
isAbigger = floor(a/10^(floor(log10(a)))) > floor(b/10^(floor(log10(b))));

How to multiply 2 numbers using recursion

I'm trying to multiply (3, 6) and (9, 9) using recursion. However, the result printed is 18 and 45. I need to find out which part is wrong.
Here's my code:
#include <stdio.h>
int multiply (int, int);
int main()
{
int a, b, c;
a = 6; b = 3; c = multiply(a, b);
printf("%d\n", c);
a = 9; b = 9; c = multiply(a, b);
printf("%d\n", c);
return 0;
}
int multiply(int a, int b)
{
static int c = 0, i = 0;
if (i < a) {
c = c + b;
i++;
multiply(a, b);
}
return c;
}
The issue is that multiply's static variables persist from call to call, which throws the second calculation off. It is possible to bandage this wound, but it's better to address the underlying design problem that is compelling use of static variables in the first place. There is no need to artificially maintain state in the function using i (the number of additions to perform) and c (a product accumulator).
Given that multiplication is repeated addition of a b times, you can establish a base case of b == 0 and recursively add a, incrementing or decrementing b (depending on b's sign) until it reaches 0. The product accumulator c is replaced by the function return value and the number of multiplications i is represented by b.
Using this approach, each stack frame's state is naturally self-reliant.
#include <stdio.h>
int multiply(int a, int b) {
if (b > 0) {
return a + multiply(a, b - 1);
}
else if (b < 0) {
return -a + multiply(a, b + 1);
}
return 0;
}
int main() {
printf("%d\n", multiply(3, 6));
printf("%d\n", multiply(9, 9));
printf("%d\n", multiply(-6, 2));
printf("%d\n", multiply(6, -2));
printf("%d\n", multiply(-7, -3));
printf("%d\n", multiply(0, 7));
printf("%d\n", multiply(7, 0));
printf("%d\n", multiply(0, 0));
return 0;
}
Output:
18
81
-12
-12
21
0
0
0
As a final note, I recommend following proper code style. Minifying your code and using single-character variable names only makes debugging more difficult (someone has since de-minified the original code in an edit).
Both c and i need to be reset to zero on each [outer] call to multiply [as others have mentioned] because a function scope static variable is only initialized once.
There is no way to do this because the static variables are at multiply function scope (i.e. how does main access/reset them?). They would need to be moved to global/file scope.
Adding a helper function and moving the variables to global scope will do it:
#include <stdio.h>
int multiply(int, int);
int
main()
{
int a,
b,
c;
a = 6;
b = 3;
c = multiply(a, b);
printf("%d\n", c);
a = 9;
b = 9;
c = multiply(a, b);
printf("%d\n", c);
return 0;
}
static int c, i;
int
mul(int a, int b)
{
if (i < a) {
c = c + b;
i++;
mul(a, b);
}
return c;
}
int
multiply(int a, int b)
{
i = 0;
c = 0;
return mul(a,b);
}
Try resetting your static variables before second call to multiply or do without them
int multiply(int a, int b) {
If (a==0)
return 1;
else if (a>0)
return b+multiply(a-1, b);
else
return - 1*multiply(-1*a, b); }

Undefined behaviour in C program. Please explain

Below is a program to add two numbers using bitwise operators. Though the final value returned in function add is as expected the value printed in main function is showing some junk value.Can anyone explain this undefined behaviour and let me know what is going wrong here.Sample output below.
#include <stdio.h>
#include <string.h>
#include <windows.h>
int add (int, int);
int main ()
{
int n1 = 0, n2 = 0;
scanf("%d %d", &n1, &n2);
printf("\nSum: %d\n",add(n1, n2));
system("pause");
return 0;
}
int add (int a, int b)
{
printf("%d %d\n", a, b);
if (!a) {
return b;
} else {
add ((a & b) << 1, a ^ b);
}
}
Sample output:-
3 1
3 1
2 2
4 0
0 4
Sum: 2686756
you need to return the result of add in your recursive call
int add (int a, int b)
{
printf("%d %d\n", a, b);
if (!a) {
return b;
} else {
return add ((a & b) << 1, a ^ b);
}
}
which could be
int add (int a, int b)
{
if (!a) return b;
return add ((a & b) << 1, a ^ b);
}
The line add ((a & b)... is missing return, so it's just returning a random number off the stack.
I can be wrong (C is loooong time away) but
if (!a) {
Is not bit "not" operator.
It will be "true" for every value, except 0
Edit :
See other answers. But in c++ ot's working :)

stuck in GCD of 2 numbers in C using recursion

I am getting segmentation fault with the following program. I am trying to find out the GCD using recursive function. The code is:
#include<stdio.h>
int gcd(int a, int b)
{
int temp, g, c;
if(a>b)
{
c=a;
a=b;
b=c;
}
//printf("The values of a and b are: %d %d",a,b);
temp = a % b;
if(temp != 0)
{
g = gcd(b, temp);
return(g);
}
if(temp == 0)
g= b;
return g;
}
int main()
{
int a,b;
printf("Enter two numbers: \n");
scanf("%d %d", &a, &b);
printf("The GCD of two numbers you entered are: %d\n", gcd(a,b));
}
The problem that I found out is in swapping variables. If I am removing it then the code is working fine. Can anybody tell me where I am going wrong? I am trying to implement it using Euclidean algorithm. So no other method can be implemented.
if(a>b)
{
c=a;
a=b;
b=c;
}
temp = a % b;
The problem is here. First, you're making sure that b > a. Now, if b is greater than a, it's not difficult to prove that a % b == a. For instance, 2 % 5 = 2.
Just replace the last line with
temp = b % a;
or, even better, reverse the condition for swapping :
if(a < b)
Instead of swapping the variables at the GCD function,Find the max number and send it as a and min number as b in the main function itself.
int GCD(int a, int b)
{
if (b == 0)
return a;
else
return GCD(b, a % b);
}
The condition should be
if (a < b)
Because doing
// Pre-condition: a >= b
temp = a % b;
// Post-condition: temp < b or temp == 0.
then the call gcd(b, temp)
has: temp < b, b <= min(original a, original b)
And so gcd terminates (variant a + b getting smaller on every call).
i think there is no need for the if (a > b) test, just remove it. If a >= b, the code works just as you want; if not, the first recursive call just do the swap.
You really don't need to check for each step which is greater (a or b).
Use following function to calculate gcd of two numbers.
int gcd(int a ,int b){
if(a % b == 0)
return b;
return gcd(b,a%b);
}
That's it.
Why to complicate things that much? Use this:
int findgcd(int x,int y){
while(x!=y){
if(x>y)
return findgcd(x-y,y);
else
return findgcd(x,y-x);
}
return x;
}

Given two int numbers A and B. How to find next multiple of B that is not less than A?

Suppose you input A = 15, B = 6, The answer is 18. What algorithm do I need?
This is what I try, but it doesn't work:
#include <stdio.h>
int main() {
int a, b;
scanf("%d %d", &a, &b);
for ( ; a % b != 0; a++ ) {
if ( a % b == 0 ) {
printf("%d\n", a);
return a;
}
}
return 0;
}
I get infinite loop.
The question (now) asks for:
The next multiple of b that is not less than a?
Using your notation of a and b, you can write it directly like this:
int NextMultipleUp(int a, int b)
{
int r = a % b;
if (r == 0)
return a;
else
return a + b - r;
}
The question originally asked for
The next multiple of a that is not greater than b
And for that the answer is
int NextMultipleDown(int a, int b)
{
return b - b % a;
}
This was the answer for which the original comments applied to.
return (((a-1) / b )+1) * b;
Always returns a multiple of b. Increment the integer dividend to get a multiple that is larger than the original a - subtract one from the original, because we want 'not less than' rather than 'greater than' a
I think that you want a do - while iterative loop, so I will give an alternative answer.
How to find next multiple of B that is not less than A?
Obviously this code is slower than David's.
int main ( void ){
int a, b, c;
long int result;
scanf("%d %d", &a, &b);
c = 0;
do {
result = b * c;
c++;
} while ( result < a );
printf( " The number is: %d \n", result );
}
int nextMultiple(int a,int b)
{
if(a%b == 0) return a;
return a+(b-(a%b));
}
so if a=15 b=6
the ans is
=15+(6-(15%6))
=15+(6-(3))
=15+3
=18

Resources