Using for statement to find the greatest of four given integers? - c

#include <stdio.h>
int max_of_four(int, int, int, int);
int main() {
int a, b, c, d;
printf("Enter 4 numbers -");
scanf("%d %d %d %d", &a, &b, &c, &d);
int ans = max_of_four(a, b, c, d);
printf("%d", ans);
return 0;
}
int max_of_four(int a, int b, int c, int d) {
int greatest, i = 0;
int num[4] = { a, b, c, d };
greatest = num[0];
while (i >= 3) {
if (greatest <= num[i]) {
greatest = num[i];
}
i++;
}
return greatest;
}
So I tried using a for loop to compare every number to a variable greatest.
But the answer for the greatest integer is always the first integer.

In max_of_four:
while (i >= 3) is never true because you start with i being 0, and 0 is not greater than or equal to 3. Perhaps you meant while (i <= 3), but you would normally write this loop using for rather than while:
for (int i = 0; i < 4; i++)
if (greatest <= num[i]) greatest = num[i];

The problem is with the while loop condition. The condition should have been while(i<=3).
int max_of_four(int a,int b ,int c, int d) {
int greatest,i = 0;
int num[4] = {a, b, c, d};
greatest = num[0];
while(i <= 3) {
if(greatest <= num[i]) {
greatest = num[i];
}
i++;
}
return greatest;
}

The test while (i >= 3) is incorrect, you probably meant to write this instead:
while (i <= 3)
Note that for loops are much more readable as you can group the initialization, test and increment of i in a single line:
for (i = 0; i <= 3; i++) {
if (greatest <= num[i]) {
greatest = num[i];
}
}
Note also that it is more consistent to use i < 4 instead of i <= 3 to make the array length more obvious.
Also, you do not need an array with 4 entries: 3 entries suffice as you initialize greatest to the first value already.
Here is a modified version:
int max_of_four(int a, int b, int c, int d) {
int greatest = a;
int num[3] = { b, c, d };
for (int i = 0; i < 3; i++) {
if (greatest < num[i]) {
greatest = num[i];
}
}
return greatest;
}
Finally, constructing an array to determine the maximum value among 4 integers is a bit of an overkill. Here is a much simpler version:
int max_of_four(int a, int b, int c, int d) {
if (a < b) a = b; // a = max(a, b)
if (c < d) c = d; // c = max(c, d)
if (a < c) a = c; // a = max(a, c)
return a;
}
If you must use a for loop, you can just wrap 3 simple tests into a dummy for statement:
int max_of_four(int a, int b, int c, int d) {
for (;;) {
if (a < b) a = b;
if (c < d) c = d;
if (a < c) a = c;
return a;
}
}

Related

Min function gives output 6422164 irrespective of the input

I want to implement a function that returns the minimum of four elements. I have written the following code:
#include <stdio.h>
int max_of_four(int a, int b, int c, int d) {
int max;
if (a > b) {
if (a > c) {
if (a > d) {
max = a;
}
}
} else if (b > a) {
if (b > c) {
if (b > d) {
max = b;
}
}
} else if (c > a) {
if (c > b) {
if (c > d) {
max = c;
}
}
} else {
max = d;
}
return max;
}
int main() {
// initializing int a, b, c, d, max;
scanf("%d %d %d %d", &a, &b, &c, &d);
int ans = max_of_four(a, b, c, d);
printf("%d", ans);
return 0;
}
This code is giving me output 6422164 irrespective of the input. What is wrong with my code?
You haven't covered the cases properly, E.g. what if a=1 and b=2 and c=3. The condition in the second if (b>a) will be true and the block entered. Then the condition b>c will be false and no other block will be entered. Finally the uninitialised variable max is returned, returning an undefined value which you see as 6422164.
A better way to write it is to initialise max to the first value and then compare each value in turn to max, updating it if the current number is greater than max.
int max_of_four(int a,int b,int c,int d) {
int max = a;
if (b > max) max = b;
if (c > max) max = c;
if (d > max) max = d;
return max;
}

levenshtein ALWAYS infinite loop recursive C

Liechtenstein in c programming always return infinite loop this is my code i try many solution and i try to stock variables and use pointers but always i have the infinite loop i think it's because the 3 recursive calls but in the doc of Liechtenstein algorithm i found this implementation
#include "distance.h"
#include "sequence.h"
#include "string.h"
#include <stdarg.h>
int max(int a, int b){
if (a>b) return a;
return b;
}
float min(float a,float b, float c){
if((a<b) && (a<c)) return a;
if((c<b) && (c<a)) return c;
return b;
}
float dif(int a,int b){
int d;
d = a-b;
if((a==32)||(b==32)) return 1.5; //verification d'espaceC
if(d==0.0) return d;
if((abs(d)==17.0) || (abs(d)==6.0)) return 1.0;
return 2;
}
float distance_D1(SEQUENCE S1, SEQUENCE S2){
float d = 0.0; int a,b; int m; int i;
m = max(S1.l,S2.l);
for(i=0;i < m; i++){
a = S1.tc[i];
b = S2.tc[i];
d = d + dif(a,b) ;
printf("%.1f\n",d);
}
return d;
}
float DistanceMinRec(char* a,char* b,int n,int m){
printf("%s \n",a);
printf("%s \n",b);
printf("%d \n",n);
printf("%d \n",m);
float l,k,j,d;
if (m <= 0) return n;
// If second string is empty, the only option is to
// remove all characters of first string
if (n <= 0) return m;
// If last characters of two strings are same, nothing
// much to do. Ignore last characters and get count for
// remaining strings.
if (a[m] == b[n]) {
return DistanceMinRec(a, b, m-1, n-1);
}
// If last characters are not same, consider all three
// operations on last character of first string, recursively
// compute minimum cost for all three operations and take
// minimum of three values.
l=DistanceMinRec(a, b, m, n-1)+dif(a[m],b[n-1]);
k=DistanceMinRec(a, b, m-1, n)+dif(a[m-1],b[n]);
j=DistanceMinRec(a, b, m-1, n-1)+dif(a[m-1],b[n-1]);
d= min (l , // Insert
k, // Remove
j // Replace
);
return d;
}
the main file
int n=strlen(S1.tc);
int m=strlen(S2.tc);
char* X = S1.tc;
char* Y = S2.tc;
// char* X = "sunday";
// char* Y = "saturday";
//affiche_sequence(S1);
//affiche_sequence(S2);
d = DistanceMinRec(X,Y,n,m);
printf("Distance entre %s et %s = %.1f\n", argv[1],argv[2],d);
exit(0);
i think that the flush of variable is the problem i comment the block of printf in recursive function and it work but im not sure that is the correct output

Algorithm to find and print figures that are common to two given long integers

Please help me with the appropriate C algorithm without using arrays.
Example:
Input
123456789
2037
Output
Common figures are 2, 3, 7.
My failed attempt:
long a, b, original_a, original_b;
int i, j, figure_a, figure_b;
printf("a=");
scanf_s("%li", &a);
printf("b=");
scanf_s("%li", &b);
original_a = a;
original_b = b;
for (i = 0; i <= 9; i++)
for (j = 0; j <= 9; j++){
a = original_a;
b = original_b;
while (a||b){
figure_a = a % 10;
figure_b = b % 10;
a /= 10;
b /= 10;
if (i == figure_a && j == figure_b && i == j)
printf("%d, ", i);
}
}
You can convert both the integers to strings and then compare each character of the first string with the second one to check whether any of them matches or not. I've used nested for loops for comparing.
I've used strings because comparing each character of two strings is a lot easier than comparing each digit of two integers.
#include <stdio.h>
int main()
{
long int a,b;
int i,j;
scanf("%ld %ld",&a,&b); //taking both inputs
char temp_a[50],temp_b[50];
sprintf(temp_a, "%ld", a); //converting the first integer to a string
sprintf(temp_b, "%ld", b); //converting the second integer to a string
int length_a=strlen(temp_a); //length of first string
int length_b=strlen(temp_b); //length of second string
// matching whether any character is in common using nested for-loops
// printing the character as soon as it matches
// if a character matches, the loop breaks.
for(i=0 ; i<length_a ; i++)
{
for(j=0 ; j<length_b ; j++)
{
if(temp_a[i]==temp_b[j])
{
printf("%c",temp_a[i]);
break;
}
}
}
}
This is a fun little problem.
I threw together a quick, simple solution:
#include <stdio.h>
int main(void)
{
int a, b;
int d[10]={0};
scanf("%d %d", &a, &b);
while(a)
{
d[a%10] = 1;
a /= 10;
}
while(b)
{
if (d[b%10]) d[b%10]=2;
b /= 10;
}
for(a=0;a<10;++a) if (d[a]==2) printf("%d ", a);
return 0;
}
Link to IDE One code
Here's a short version that does not use arrays:
#include <stdio.h>
int main(void)
{
int a, b, c;
scanf("%d %d", &a, &b);
while(a)
{
c = b;
while(c)
{
if (c%10 == a%10)
{
printf("%d ", c%10);
break;
}
c /= 10;
}
a /= 10;
}
return 0;
}
This version runs slower than my first one, and does not print out the numbers in ascending order.
May it helps:
#include <stdio.h>
int original_a, original_b, i;
short digit_a, digit_b, digit_common;
short find_digit(int num);
int main()
{
printf("Insert 2 numbers a and b\n");
scanf("%d %d", &original_a, &original_b);
digit_a = find_digit(original_a);
digit_b = find_digit(original_b);
digit_common = digit_a & digit_b;
printf("digit_common: %x\n", digit_common);
printf("Common digits of a and b\n");
for(i = 0; i < 10; i++){
if(digit_common & (1<<i)){
printf("%d",i);
}
}
return 0;
}
short find_digit(int num){
short result = 0;
while(num>0){
result |= (1 << (num%10));
num /= 10;
}
return result;
}

GCD function for C

Q 1. Problem 5 (evenly divisible) I tried the brute force method but it took time, so I referred few sites and found this code:
#include<stdio.h>
int gcd(int a, int b)
{
while (b != 0)
{
a %= b;
a ^= b;
b ^= a;
a ^= b;
}
return a;
}
int lcm(int a, int b)
{
return a / gcd(a, b) * b;
}
int main()
{
int res = 1;
int i;
for (i = 2; i <= 20; i++)
{
res = lcm(res, i);
}
printf("%d\n", res);
return 0;
}
This is very simple but I don't understand how function "gcd" works; can somebody please help me understand the logic. (I know it returns the GCD of 2 numbers but why so many operations?)
To your second question: The GCD function uses Euclid's Algorithm. It computes A mod B, then swaps A and B with an XOR swap. A more readable version might look like this:
int gcd(int a, int b)
{
int temp;
while (b != 0)
{
temp = a % b;
a = b;
b = temp;
}
return a;
}
This problem can also be solved in a very clean way with recursion:
int gcd(int a, int b) {
int remainder = a % b;
if (remainder == 0) {
return b;
}
return gcd(b, remainder);
}
The GCD computation in C :
int gcd(int a, int b){
if (a && b) for(;(a %= b) && (b %= a););
return a | b;
}
The absolute value computation :
#include <limits.h>
unsigned int abso(int v){
const int mask = v >> (sizeof(int) * CHAR_BIT - 1);
return (v + mask) ^ mask;
}
I executed this statements for GCD :
#include<stdio.h>
#include<conio.h>
int main(){
int l, s,r;
printf("\n\tEnter value : ");
scanf("%d %d",&l,&s);
while(l%s!=0){
r=l%s;
l=s;
s=r;
}
printf("\n\tGCD = %d",s);
getch();
}
Using a bit of recursion and Objective-C
-(int)euclid:(int)numA numB:(int)numB
{
if (numB == 0)
return numA;
else
return ([self euclid:numB numB:numA % numB]);
}

Simpler way of sorting three numbers

Is there a simpler and better way to solve this problem because
I used too many variables.
I used so many if else statements
I did this using the brute force method
Write a program that receives three integers as input and outputs the numbers in increasing order.
Do not use loop / array.
#include <stdio.h>
main(){
int no1;
int no2;
int no3;
int sto;
int hi;
int lo;
printf("Enter No. 1: ");
scanf("%d", &no1);
printf("Enter No. 2: ");
scanf("%d", &no2);
printf("Enter No. 3: ");
scanf("%d", &no3);
if (no1>no2) {
sto=no1;
lo=no2;
} else {
sto=no2;
lo=no1;
}
if (sto>no3) {
hi=sto;
if(lo>no3){
sto=lo;
lo=no3;
}else {
sto=no3;
}
}else hi=no3;
printf("LOWEST %d\n", lo);
printf("MIDDLE %d\n", sto);
printf("HIGHEST %d\n", hi);
getch();
}
if (a > c)
swap(a, c);
if (a > b)
swap(a, b);
//Now the smallest element is the 1st one. Just check the 2nd and 3rd
if (b > c)
swap(b, c);
Note: Swap changes the values of two
variables.
Call the three variables x, y, and z, then:
if (x > y) swap(x, y);
if (y > z) swap(y, z)
if (x > y) swap(x, y);
Writing the swap function is left as an exercise for the reader. Hint: you may have to use pointers.
#include <stdio.h>
#define min(a,b) ((a)<(b)?(a):(b))
#define max(a,b) ((a)>(b)?(a):(b))
int main(){
int a, b, c;
int hi;
int lo;
printf("Enter No. 1: ");
scanf("%d", &a);
printf("Enter No. 2: ");
scanf("%d", &b);
printf("Enter No. 3: ");
scanf("%d", &c);
lo = min(min(a, b), c);
hi = max(max(a, b), c);
printf("LOWEST %d\n", lo);
printf("MIDDLE %d\n", a+b+c-lo-hi);
printf("HIGHEST %d\n", hi);
getchar();
}
If you want to sort the values into new external variables, you can actually do the swaps without temporaries:
void sort(int a, int b, int c, int *min, int *mid, int *max) {
min = a;
mid = b;
max = c;
if (min > mid) { mid = a; min = b; }
if (mid > max)
{
max = mid;
mid = c;
if (min > mid)
{
mid = min;
min = c;
}
}
}
This works because the last swap test is really only needed if the second test succeeds (otherwise it will simply be a repetition of the first test, which will fail by definition since we already sorted those variables).
Because of this, we can track the assignments of each of the original variables and avoid swap locals.
The following code performs only 2 (best case) to 3 (worst case) conditional tests, with no assignment operations nor any extra variables:
void echo(int _1st, int _2nd, int _3rd) { printf("%d %d %d", _1st, _2nd, _3rd); }
void echoFrom(int pivot, int x, int y) {
(pivot < y) ? ((x < y) ? echo(pivot, x, y) : echo(pivot, y, x)) : echo(y, pivot, x);
}
void printSorted(int a, int b, int c) { (a < b) ? echoFrom(a, b, c) : echoFrom(b, a, c); }
Basic call (scanf() stuff avoided for simplicity):
int main() {
printSorted(2,3,1); //Output: 1 2 3
}
To find the min, mid and max of 3 values, you can use the ternary operator. You can either do all your work within the main body of your code, or you can separate the minof3, midof3 and maxof3 calculations into reusable functions.
In the case of min and max you simply make 2 out of 3 possible comparisons, and then return a comparison of the results. In the case of mid, you do the same, but compute the min and max of the 3 values, and then check all 3 against min and max in order to find the value that is neither the min or max. (you can do this part in the main body of your code without an additional function by declaring the min and max values as variables and doing the elimination there).
Putting the pieces together, you could do something similar to the following, which takes the first 3 arguments as the values to sort (or uses defaults of 99, 231, 8 if a needed value isn't specified)
#include <stdio.h>
#include <stdlib.h>
/** direct ternary comparison of 3 values */
long minof3 (long a, long b, long c) {
long x = a < b ? a : b,
y = a < c ? a : c;
return x < y ? x : y;
}
long maxof3 (long a, long b, long c) {
long x = a > b ? a : b,
y = a > c ? a : c;
return x > y ? x : y;
}
long midof3 (long a, long b, long c) {
long x = a < b ? a : b,
y = a > b ? a : b,
z = y < c ? y : c;
return x > z ? x : z;
}
int main (int argc, char **argv) {
long x = argc > 1 ? strtol (argv[1], NULL, 10) : 99,
y = argc > 2 ? strtol (argv[2], NULL, 10) : 231,
z = argc > 3 ? strtol (argv[3], NULL, 10) : 8;
/* strtol validations omitted for brevity */
printf ("\n sorted values : %ld, %ld, %ld\n",
minof3 (x, y, z), midof3 (x, y, z), maxof3 (x, y, z));
}
Example Use/Output
$ ./bin/sort3
sorted values : 8, 99, 231
$ ./bin/sort3 -23 -281 1031
sorted values : -281, -23, 1031
(yes, I know this is an old post, but given the recent comment about code hidden behind the swap function, a full example was in order).
A compact solution sans magic swap() function, that dances around int overflow, and abuses arrays:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
int a = atoi(argv[1]);
int b = atoi(argv[2]);
int c = atoi(argv[3]);
int ab[] = {a, b}, bc[] = {b, c};
int smaller[] = {ab[a > b], bc[b > c]}, larger[] = {ab[a < b], bc[b < c]};
int smallest = smaller[a > c], largest = larger[a < c];
int middle = (a - smallest) + (b - largest) + c;
printf("%d, %d, %d\n", smallest, middle, largest);
return 0;
}
USAGE
> ./a.out 2147483647 2147483645 2147483646
2147483645, 2147483646, 2147483647
>
#include <stdio.h>
int main()
{
int a;
int b;
int c;
//Temporary storage variable
int t = 0;
printf("Enter No. a: ");
scanf("%d", &a);
printf("Enter No. b: ");
scanf("%d", &b);
printf("Enter No. c: ");
scanf("%d", &c);
if (a > b)
{
t = a;
a = b;
b = t;
}
if (a > c)
{
t = a;
a = c;
c = t;
}
if (c < b)
{
t = c;
c = b;
b = t;
}
printf("a = %d < b = %d < c = %d", a, b, c);
return 0;
}
#include <stdio.h>
int main() {
int a,b,c;
printf("enter a b c values:\n");
scanf("%d%d%d",&a,&b,&c);
if(a<b && a<c)
{ printf("%d,",a);
if(b<c)
printf("%d,%d",b,c);
else
printf("%d,%d",c,b);
}
else if(b<a && b<c)
{
printf("%d,",b);
if(a<c)
printf("%d,%d",a,c);
else
printf("%d,%d",c,a);
}
else
{
printf("%d,",c);
if(a<b)
printf("%d,%d",a,b);
else
printf("%d,%d",b,a);
}
return 0;
}
int number1 = int.Parse(Console.ReadLine());
int number2 = int.Parse(Console.ReadLine());
int number3 = int.Parse(Console.ReadLine());
int swap = 0;
if (number2 > number1 && number2 > number3)
{
swap = number2;
number2 = number1;
number1 = swap;
}
else if (number3 > number2 && number3 > number1)
{
swap = number3;
number3 = number1;
number1 = swap;
}
if (number3 > number2)
{
swap = number2;
number2 = number3;
number3 = swap;
}
Console.WriteLine(number1 + "/" + number2 + "/" + number3);
Console.ReadKey();
I was attempting to solve the same problem today. Could make this compact version of code without using any temporary variables; loops; library functions like swap, sort, max, min, etc. The code uses only if statements and makes continuous mutations in the hierarchy until all possibilities are checked.
int main()
{
int a, b, c; //User inputs stored in these three variables
int first, second, third; //These three variables will store the sorted numbers in sequence
std::cout<<"Please enter three integers : "; //User input prompt
std::cin>>a>>b>>c;
first = a; //Initially assuming number 'a' is smallest
if (b <= a && b <= c) first = b; //Checking whether b is smallest
if (c <= a && c <= b) first = c; //Checking whether c is smallest
if (((a >= b && a <= c) || (a >= c && a <= b))) second = a; //Checking if a is middle number
if (((b >= a && b <= c) || (b >= c && b <= a))) second = b; //Checking if b is middle number
if (((c >= a && c <= b) || (c >= b && b <= a))) second = c; //Checking if c is middle number
if (a >= b && a >= c) third = a; //Checking if a is the greatest
if (b >= c && b >= a) third = b; //Checking if b is the greatest
if (c >= a && c >= b) third = c; //Checking if c is the greatest
std::cout<<"The numbers in ascending order are : "<<first<<", "<<second<<", "<<third<<std::endl;
}

Resources