Operators

1. What is the value of variable z in following code snippets?

a.

int x = 5;

int y = 7;

int z = x%y;

Ans: 5

b.

int x = 5;

int y = 7;

int z = x/y;

Ans: 0. Integer division yields only quotient.

c.

double x = 4.4;

double y = 2.0;

double z = x/y;

Ans: 2.2

 

2. What will be the output of following program snippets?

a.

int x = 5;

double y = 2.5;

printf (“x/y = %f\n”, x/y);

Ans: x/y = 2.000000

x is an int, y is a double. Result of their division is a double which is printed using %f format string.

b.

double x = 5.0;

int y = 2;

printf (“x/y = %f\n”, x/y);

Ans: x/y = 2.500000

x is a double, y is an int. Result of their division is a double which is printed using %f format string.

c.

int x = 5;

double y = 2.5;

printf (“x + y = %f\n”, x+y);

Ans: 7.5. Result of addition of an int and a double is a double.

 

3. Write a program that swaps value of two int

#include <stdio.h>

int main (int argc, char * argv[]) {
    int var1 = 10, var2 = 20;
    int temp = 0;
    printf("var1 = %d and var2 = %d\n", var1, var2);
    temp = var1;
    var1 = var2;
    var2 = temp;
    printf("var1 = %d and var2 = %d\n", var1, var2);
    return 0;
}

 

4. Write a program the computes sum of two int

#include <stdio.h>

int main (int argc, char * argv[]) {
    int var1 = 10, var2 = 20;
    int sum = var1 + var2;
    printf("%d + %d = %d\n", var1, var2, sum);
    return 0;
}

 

5. Write a program to convert 15723 meters to kilometres.

#include <stdio.h>

int main (int argc, char * argv[]) {
    int meters = 15723;
    /* Division of two int will result in an int */
    /* Hence we typecast meters to double before dividing */
    /* Now result of division is going to be a double */
    double kms = ((double)15723)/1000;
    printf("%d meters is %f kms\n", meters, kms);
    return 0;
}

 

6. Write a program to convert 42.2 degree Celsius to Fahrenheit.

#include <stdio.h>

int main (int argc, char * argv[]) {
    double celsius = 42.2;
    /* Note construction of expression below.
    * We first multiply double with int, that gives us a double
    * Then we divide this resulting double with an int, that also gives us double
    * Finally we add it to an int giving us a double as final answer.
    * If we had instead written (celsius * (9/5)) + 32, then 9/5 both being int
    * would have evaluated to quotient 1 and we would have computed wrong answer */
    double fahrenheit = ((celsius * 9)/5) + 32;
    printf("%f celsius = %f fahrenheit\n", celsius, fahrenheit);
    return 0;
}

 

7. Write a program to calculate area and circumference of a circle of radius 2 cm.

#include <stdio.h>

int main (int argc, char * argv[]) {
    int radius = 2;
    double pi = 22.0/7;
    double circumference = 0, area = 0;
    circumference = 2 * pi * radius;
    area = pi * radius * radius;
    printf("Circle of radius %d has circumference %f and area %f\n", radius, circumference, area);
    return 0;
}