[source code] C Programming Tutorial - 23 - Shorthand if else

+2 Bucky Roberts · August 4, 2014


Syntax: 

(test) ? trueCode : falseCode;


#include <stdio.h>
#include <stdlib.h>

int main()
{
    //choosing teams
    char lastName[20];
    printf("Enter your last name:\n");
    scanf("%s", lastName);

    //test the first letter
    (lastName[0] < 'M') ? printf("Blue team") : printf("Red team");

    return 0;
}



#include <stdio.h>
#include <stdlib.h>

int main()
{
    int friends = 87;
    printf("I have %d friend%s", friends, (friends!=1) ? "s" : "" );

    return 0;
}


Post a Reply

Replies

Oldest  Newest  Rating
0 Ass Cold · October 25, 2014
Hi bucky

I try to ask my self how many friends do I have and enter a number and  saying "you have %d friends".
also try to make it if I enter 1 will say 1 friend, enter 2 will way 2 friends.
I can't get it work

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int friends = 1;


    printf("How many friends do you have? \n");
    scanf("I have %d friend%s");

    if((friends!=1) ? "s" : "" ){
        printf("I have %d friends", &friends);
    }

    return 0;
}
+1 Ben   · October 25, 2014
RE: Ass Cold 

I have something that may be a solution to your problem. 
Try this: 


#include <stdio.h>
int main(){
        int friends;

        printf("How many friends do you have?\n");
        scanf("%d", &friends);

        if(friends > 1){
                printf("I have %d friends\n", friends);
        }
        else if(friends == 1){
                printf("I have 1 friend\n");
        }else{
                printf("I have no friends\n");
        }
}
  • 1

C

107,229 followers
About

One of the most popular languages of all time.

Links
Moderators
Bucky Roberts Administrator