Hello I want to output every positive element that is even. I use VA_LIST. The compiler counts numbers only from 1 to 4, 4 to 8 is not counted, what is the problem?
#include <stdio.h>
#include <stdarg.h>
int MyPerfectF(int num, ...) {
int sum = 0;
va_list args;
va_start(args, num);
int x;
while (va_arg(args, int) != NULL) {
x = va_arg(args, int);
if (x > 0 && x % 2 == 0) {
printf("%d ", x);
sum++;
}
}
printf("\nAmount of true numbers is: %d", sum);
va_end(args);
return 0;
}
int main(void) {
int num = 5;
int a, b, c, d;
scanf_s("%d %d %d %d", &a, &b, &c, &d);
MyPerfectF(num, a, b, c, d, NULL);
}
From va_arg [emphasis mine]:
T va_arg( va_list ap, T );
The va_arg macro expands to an expression of type T that corresponds to the next parameter from the va_list ap.
In MyPerfectF() function,
while (va_arg(args, int) != NULL) {
x = va_arg(args, int);
va_arg is called twice, so if the input contains even number at even place then all those even number will be counted otherwise they are not.
Apart from this there is one more problem in your code -
In context of your program, type T is int. Compiler must be throwing a warning on comparison statement (va_arg(args, int) != NULL) of while loop condition.
You don't need to pass NULL to indicate the termination of arguments. Instead, pass the value of num as number of variable arguments passed to MyPerfectF() function, like this:
int main(void) {
int num = 4;
.....
.....
MyPerfectF(num, a, b, c, d);
}
and in MyPerfectF() replace the while loop with this
for (int i = 0; i < num; ++i) {
Also, you can assign the return value of scanf() to num and pass it to MyPerfectF() function, this will ensure that the MyPerfectF() function will read only those arguments which are successfully read and assigned by scanf(). Putting these altogether:
#include <stdio.h>
#include <stdarg.h>
int MyPerfectF(int num, ...) {
int sum = 0;
va_list args;
va_start(args, num);
for (int i = 0; i < num; ++i) {
int x = va_arg(args, int);
if (x > 0 && x % 2 == 0) {
printf("%d ", x);
sum++;
}
}
va_end(args);
printf("\nAmount of true numbers is: %d\n", sum);
return 0;
}
int main(void) {
int a, b, c, d;
printf ("Enter 4 values:\n");
int num = scanf("%d %d %d %d", &a, &b, &c, &d);
MyPerfectF(num, a, b, c, d);
return 0;
}
Related
I have tried this program to take 3 integers and print the 2nd largest number:
#include<stdio.h>
int main()
{
int a,b,c,max2;
printf("Enter 3 integers: ");
scanf("%d%d%d",&a,&b,&c);
max2=a;
if(a>b){
max2=b;
printf("")
}
return 0;
}
Now i am stuck here. I am unable to find the logic behind this code. What can I do?
This is not the Logic which you can understand, it'll not give you the right, expected result.
Code:
#include <stdio.h>
int main()
{
int a, b, c;
printf("Values: ");
scanf("%d%d%d", &a, &b, &c);
if(a>b && a>c)
{
if(b>c)
printf("2nd largest: %d", b);
else
printf("2nd largest: %d", c);
}
else if(b>c && b>a)
{
if(c>a)
printf("2nd largest: %d", c);
else
printf("2nd largest: %d", a);
}
else if(a>b)
printf("2nd largest: %d", a);
else
printf("2nd largest: %d", b);
return 0;
}
You should compare all the three variables to get the 2nd largest among those numbers.
Output:
Values: 32 31 12
2nd largest: 31
Explanation:
First pick any variable and compare it with the other two variables like if(a>b && a>c), if its true, it means a is the largest and any of the two variables b and c is the 2nd largest, so inside the if(a>b && a>c) block there's a comparison if(b>c), if true then b is the 2nd largest otherwise c is the second largest. Similarly, compare the other two variables for if they are the largest. e.g. else if(b>c && b>a) and else if(c>a && c>b).
One method is to sort these three numbers and then print the middle one:
#include <stdio.h>
static inline void swap_if_out_of_order (int *p, int *q)
{
if (*p > *q) {
int t = *p;
*p = *q;
*q = t;
}
}
int main (void)
{
int a, b, c;
printf("Enter three integers\n");
if (scanf("%d%d%d", &a, &b, &c) == 3) {
swap_if_out_of_order(&a, &b);
swap_if_out_of_order(&b, &c);
swap_if_out_of_order(&a, &b);
printf("Second greatest: %d\n", b);
}
}
Or, without sorting, with at most three comparisons:
#include <stdio.h>
int main (void)
{
int a, b, c, m;
printf("Enter three integers\n");
if (scanf("%d%d%d", &a, &b, &c) == 3) {
if (a > b) {
if (b > c) m = b;
else if (a > c) m = c;
else m = a;
} else if (a > c) m = a;
else if (b > c) m = c;
else m = b;
printf("Second greatest: %d\n", m);
}
}
or, likely the most efficient way with max and min functions:
#include <stdio.h>
static inline int min (int x, int y) { return x < y ? x : y; }
static inline int max (int x, int y) { return x > y ? x : y; }
int main (void)
{
int a, b, c;
printf("Enter three integers\n");
if (scanf("%d%d%d", &a, &b, &c) == 3)
printf("Second greatest: %d\n", max(min(a, b), min(max(a, b), c)));
}
JS recursion:
function f(a,b,c) {
if(a>=b && c<b) return b;
if(a>b) return f(a,c,b);
return f(b,a,c);
}
f(2,12,0) // 2
#include <stdio.h>
main()
{
int a,b,c;
scanf("%d %d %d",&a,&b,&c);
// largest //
if(a>b&&a>c)
printf("largest=%d",a);
if(b>a&&b>c)
printf("largest=%d",b);
if(c>b&&c>a)
printf("largest=%d",c);
// second largest//
if(a>b&&a<c)
printf("\nscenond largest=%d",a);
if(b>a&&b<c)
printf("\nscenond largest=%d",b);
if(c>a&&c<b)
printf("\nscenond largest=%d",c);
}
this will output the largest and the second largest number.
I have a task to make a program in which you have to input a given number on a given position in another given number. Example: input:12345, 2, 3 output 123245. I tried to make a loop but it is apparently an infinite loop. The code is here:
int c, x, p, broj, i = 0, brcifara = 0, k, broj2, k2, broj3, ind;
printf("Unesite redom x, p i c: ");
scanf("%d%d%d", &x, &p, &c);
broj2 = x;
while(broj2 >= 1)
{
broj2/= 10;
brcifara += 1;
}
while(i < brcifara)
{
k2 = pow(10, i + 1);
k = broj3%k2;
broj3 -= k*pow(10, i+ 1);
if(i<p)
{
broj += k*pow(10, i+1);
}
if(i=p)
{
broj += c*pow(10, p);
}
if(i>p)
{
broj += k*pow(10, i+2);
}
i = i + 1;
}
printf("Broj je sada %d", broj);
}
C represents the number for putting in, X is the number in which we are putting C, P represents the postion(starting from 0). Brcifara is the number of digits. The problem is only in the second loop.
Why not trying something like that :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#define MAX_STR_SIZE (100U)
int main()
{
char x[MAX_STR_SIZE] = {'\0'};
unsigned int p;
char c;
int x_int;
printf("input x, p, c\n");
scanf("%s %d %c", x, &p, &c);
if(strlen(x) > p) // check string upper boundary
{
x[p] = c;
}
x_int = atoi(x);
printf("%d\n", x_int);
}
X is a string in which you replace your C character at the given P position.
Thus :
X is a string.
C a character.
P an index (unsigned char).
Then convert the X string to an integer using the atoi() function.
I want to print function argument in the printf command. Please help to suggest.
void printline(char ch, int len);
value(float, float, int);
main()
{
double amount;
printline('=', 30);
amount = value(500, 0.12, 5); // I want to print argument of function value. please help
printf("The total amount is: %f \n", amount);
//printf("%f\t%f\t%d\t%f \n", 500, 0.12, 5, amount);
printline('=', 30);
_getch();
}
void printline(char ch, int len)
{
int i;
for (i = 0; i < len; i++)
printf("%c", ch);
printf("\n");
}
value(float p, float r, int n)
{
int year;
float sum;
sum = p;
year = 1;
while (year <= 5)
{
sum = sum * (1 + r);
year = year + 1;
}
return(sum);
}
In your printline function you only have one character as an argument. So there is no purpose in iterating through it. If you want to print a string or array of characters you want to use char * or char[] and iterate through it. So your function printline could look like this:
void printline(char *ch, int len)
{
int i;
for (i = 0; i<len; i++)
printf("%c", ch[i]);
printf("\n");
}
just make sure that len isn't bigger then the length of *ch.
Even better solution, where you don't have to worry about the value of len is to print the characters one by one until you come across the \0 character indicating the end of an array.
void printline(char *ch)
{
int i;
for (i = 0; ch[i] != '\0'; ++i)
printf("%c", ch[i]);
printf("\n");
}
Or even better
If the string is null terminated, use printf("%s", ch). If the string is not null terminated but the length is supplied, use printf("%.*s", len, ch). In both cases, there's no loop in the user code; the loop is buried inside the printf() function. Further, since there's a newline printed after the loops, use printf("%s\n", ch) or printf("%.*s\n", len, ch) and skip the extra printf() after the loop.
value(500, 0.12, 5); // I want to print argument of function value. please help
You can add a printf to the beginning of the function:
value(float p, float r, int n)
{
printf("%s(%f, %f, %d)\n", __func__, f, r, n);
#include <stdio.h>
int main()
{
int a, b, c, temp;
scanf("%d %d %d", &a, &b, &c);
if (a > b)
{
temp = a;
a = b;
b = temp;
}
else if (b > c)
{
temp = b;
b = c;
c = temp;
}
else if (c > a)
{
temp = c;
c = a;
a = temp;
}
printf("%d %d %d", a, b, c);
return 0;
}
If I put 8,6,3, the output comes 6,8,3. It doesn't change the last number. I am trying to arrange three 3 numbers in ascending manner using if statement, but this doesn't work for the third number. What can be done about it?
It easiest if you first find the smallest, then make sure the remaining two are correct :
int main()
{
int a, b, c, temp;
int ret = scanf("%d %d %d", &a, &b, &c);
if (ret != 3) {
printf("scanf() error\n");
exit(1);
}
// get smallest into a
if ((b < a) && (b < c)) {
temp = a;
a = b;
b = temp;
} else if ((c < a) && (c < b)) {
temp = a;
a = c;
c = temp;
}
// a is smallest, check b and c
if (c < b) {
temp = b;
b = c;
c = temp;
}
printf("%d %d %d", a, b, c);
return 0;
}
You need to use if instead of else if as you want to compare a with b, b with c and a with c (the three and not only one of them). Moreover, as you are moving the numbers you have to take into account where they are moved for the last comparison. And your third condition was wrong. So this should be what you are trying to do:
#include <stdio.h>
int main(){
int a, b, c, temp;
scanf("%d %d %d", &a, &b, &c);
if (a > b){
temp = a;
a = b;
b = temp;
}
if (b > c){
temp = b;
b = c;
c = temp;
if (a > b){
temp = a;
a = b;
b = temp;
}
}
else if (a > c){
temp = c;
c = a;
a = temp;
}
printf("%d %d %d", a, b, c);
return 0;
}
I think you have misunderstood the concept of if else if structure, In your case it is not working for third number because the execution will reach to else if part only when the if condition is false.
#include <stdio.h>
int main()
{
int a,b,c,temp;
scanf("%d %d %d",&a,&b,&c);
if(a>b) //evaluates to true.
{
temp=a;
a=b;
b=temp;
}
else if(b>c) // not able to execute.
{
temp=b;
b=c;
c=temp;
}
else if(c>a) // not able to execute
{
temp=c;
c=a;
a=temp;
}
printf("%d %d %d",a,b,c);
return 0;
}
a = 8
b = 6
c = 3
checking a>b evaluates to true hence swapped
now:
a = 6 // your output
b = 8
c = 3
you may need to go over the concept of if else structure once again
#include<stdio.h>
int main()
{
int a ,b,c;
printf("Enter the number : \n");
scanf("%d %d %d",&a,&b,&c);
if((a>b)&&(a>c))
{
if(b>c)
printf("%d %d %d",a,b,c);
else
printf("%d %d %d",a ,c,b);
}
else if((b>c)&&(b>a))
{
if(c>a)
printf("%d %d %d",b,c,a);
else
printf("%d %d %d",b,a,c);
}
else if((c>a)&&(c>b))
{
if(a>b)
printf("%d %d %d",c,a,b);
else
printf("%d %d %d",c,b,a);
}
return 0;
}
The easiest way is to use an array instead of three individual variables. Then use qsort for getting the input sorted.
Like:
#include <stdio.h>
#include <stdlib.h>
// Compare function for qsort
int cmp(const void *p1, const void *p2)
{
if (*(int*)p1 < *(int*)p2) return -1;
if (*(int*)p2 < *(int*)p1) return 1;
return 0;
}
int main()
{
int arr[3];
if (scanf("%d %d %d", &arr[0], &arr[1], &arr[2]) != 3) exit(1);
// Sort the input
qsort(arr, sizeof(arr)/sizeof(int), sizeof(int), cmp);
printf("%d %d %d\n", arr[0], arr[1], arr[2]);
return 0;
}
#include <stdio.h>
int main()
{
int a,b,c,temp,min;
scanf("%d %d %d",&a,&b,&c);
if(a>b)
{
temp=a;
a=b;
b=temp;
}
if(c<a)
{
min=c;
c=b;
b=a;
a=min;
}
else if(c>a && b<c) {
min=c;
c=b;
b=min;
}
printf("%d %d %d",a,b,c);
return 0;
}
you are comparing using else if, if any one condition satisfies it won't execute the other else condition.
I have the following code:
//get distances
int a = -1;
int b = -1;
while ((a != 0) && (b != 0)) {
scanf("%d %d", &a, &b);
printf("The shortest path from %d to %d is %.1lf meters.\n", a, b, D[a][b]);
}
The loop seems to terminate after one input, despite the fact that a and b are not inputed as 0.
ie:
0 2
The shortest path from 0 to 2 is 237.7 meters.
Not really sure why it's doing that so any help would be appreciated.
Then it terminates
Full code in case needed
#include <stdio.h>
#include <stdlib.h>
#define INF 41e6
double** new2Ddouble(int n, int m);
void free2D(double **a);
int main() {
//get # of nodes
int size = 0;
scanf("%d", &size);
//create matrix
double **D = new2Ddouble(size, size);
//fill with inf for D[i][j]
int i;
int j;
for(i=0; i<size; i++) {
for(j=0; j<size;j++){
D[i][j] = INF;
}
}
//fill D[i][i] with INF
for(i=0;i<size;i++) D[i][i] = INF;
int exit = 0;
int I;
int J;
double d;
while(exit != 1) {
//populate values in matrix
scanf("%d %d %lf", &I, &J, &d);
if(I == 0 && J == 0 && d == 0){
//we can exit
exit = 1;
} else {
D[I][J] = d;
}
}
//calculate distances
/* Floyd-Warshall Algorithm */
int k;
for (k=0; k<size; ++k)
for (i=0; i<size; ++i)
for (j=0; j<size; ++j)
if (D[i][k]+D[k][j] < D[i][j])
D[i][j] = D[i][k]+D[k][j];
exit = 0;
//get distances
int a = -1;
int b = -1;
while ((a != 0) && (b != 0)) {
scanf("%d %d", &a, &b);
printf("The shortest path from %d to %d is %.1lf meters.\n", a, b, D[a][b]);
}
return 0;
}
double** new2Ddouble(int n, int m) {
int i;
double **ret = (double**) malloc(n*sizeof(double*));
double *a = (double*) malloc(n*m*sizeof(double));
for (i=0; i<n; ++i) ret[i] = &a[i*m];
return ret;
}
void free2D(double **a) { free(a[0]); free(a); }
scanf("%d %d", &a, &b);
In this line you are scanning values for a and b 0 and 2 respectively.
So once a new value is scanned to these variables then your while condition fails because as you have showed a is 0 and the second condition is never checked because 0 && (0|1) = 0
Once a=0 the condition fails and exits the loop.
while ((a != 0) && (b != 0))
This loop will terminate when a or b is zero and will continue when a and b are not zero. You enter a as 0 and as the condition a!=0 fails,your loop terminates.
there are a couple of problems with this line:
scanf("%d %d", &a, &b);
Note: scanf does not automatically consume white space,
so on the second iteration
the next input char is a newline.
so scanf fails
Note: all I/O statements
should have the returned value checked
to assure success of the operation
to fix those items, write it like so:
if( 2 != scanf(" %d %d", &a, &b) )
{
perror( "scanf failed" );
exit( EXIT_FAILURE );
}
the leading ' ' in the format string causes leading
white space, like the newline, to be consumed
the 'if' checks the returned value from
scanf to assure that all the input conversions were successful