Pages

Sunday, July 8, 2018

Convert centimeter to inch scale

Problem: Write a C program to read a length in centimeter scale and convert it in the inch scale.

Solution:                           
                                                   Formula:

                                       inch = centimeter / 2.54

Code:


1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#include <stdio.h>

int main()
{
    float centi, inch;
    printf("Enter the length in centimeter: ");
    scanf("%f", &centi);

    inch = centi / 2.54;

    printf("The length in inch scale is : %0.2f\n", inch);

    return 0;
}

Task: Now, write a C program to to convert inch to centimeter scale.

Wednesday, July 4, 2018

Arithmetic Opertaions

Problem: Write a C program to find the addition, subtraction, multiplication and division of two integers.

Solution: We can use scanf() function to input the integers and printf() to output the results. %i or %d  can be used as format specifier. But division of two integers in a bit tricky. So, first we need to understand division of two integers in C.

Division Operator on different Data Type
Division Operator on different Data Type
Fig. 01




So, if we divide 1 by 2 the result will be 0 according to Fig. 01. Because int/int results int and the values after decimal point will be cut out from the result. To solve the problem we can type cast an integer to float. And then we shall get the expected result.

Code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
#include <stdio.h>

int main()
{
    int a, b;
    printf("Enter two whole numbers: ");
    scanf("%d%d", &a, &b);

    printf("%d + %d = %d\n", a, b, a + b);
    printf("%d - %d = %d\n", a, b, a - b);
    printf("%d * %d = %d\n", a, b, a * b);
    printf("%d / %d = %0.2f\n", a, b, (float) a / b);

    return 0;
}

Task: Now, write a C program that can perform basic arithmetic operations on any two real numbers.