Starting from:
$25

$19

Homework #3 (C Programming for Beginners - OnLine)

3.1 Here is a listing of a program, which asks a user to enter his/her age. It will print:

    a) “You are a golden” if the entered age is 50 and

    b) “You are not so golden” otherwise.

#include <stdio.h>

int main()

{

int yourAge;

printf("How old are you?: ");

scanf("%d", &yourAge);

if (yourAge == 50)

printf("You are golden\n");
else

printf("You are not so golden\n");

return 0;
}

Modify the above program, so that it will print:

    a) “You are a kid” if the age is less than 13

    b) “You are a teenager” if the age is between 13 and 19

    c) “You are an adult” if greater than 19

3.2 Here is a calculator program. The program gives a prompt and waits for user to enter a number, operator and another number and gives the output like this:






Another run looks like this:






#include <stdio.h>

int main()

{

int firstN;

int secondN;
char op;

printf("Type a number, operator, number -- separated by a space: ");

scanf("%d %c %d", &firstN, &op, &secondN);
if (op == '+')

printf("%d + %d = %d",

firstN, secondN, firstN + secondN);
else if (op == '-')
printf("%d - %d = %d",

firstN, secondN, firstN - secondN);

else if (op == '*')

printf("%d * %d = %d",
firstN, secondN, firstN    * secondN);
else if (op == '/')

printf("%d / %d = %d",

firstN, secondN, firstN / secondN);
else if (op == '%')
printf("%d %% %d = %d",

firstN, secondN, firstN % secondN);

else

printf("Unknown operator");
printf("\n\n");

return 0;

}

Modify the above program, so that it will:

    a) Accept decimal numbers from the user instead of integers.

    b) Once the output is displayed, ask the user if they want to continue, if they say yes, then repeat the process

3.3 Ternary/conditional operator ?: works like if .. else.

Here is an example, which finds the maximum of two numbers. It shows how can it be written using if else, and ?: both.

#include <stdio.h>

int main()

{
int max, a = 10, b = 20; // get value for a and b from user

//using if else

if (a > b) {

max = a;
}
else {
max = b;
}

//using ternary operator

max = (a > b) ? a : b; // what is the value of max?
printf("The Max is: %d\n\n", max);

return 0;

}


Re-write the above ternary operator code to find the max of three numbers, for example, a, b, and c.
Bonus, declare a, b, and c as integer variable and ask the users to enter these three values instead of hard coding them. Also, ask the user to continue if they like to find max of another set of integers.

Hint: You need to daisy chain the conditions!

A sample interaction with the user would look like this:

More products