C Programming • C Basics, Operators, Loops
C Programming / Type Conversion — Exercises

Type Conversion — Exercises

Practical 2 C Basics, Operators, Loops

Write a C program that demonstrates implicit and explicit type conversion between an integer and a float.

Practical / Solution

Type Conversion — Exercise 1

Problem

Write a C program that demonstrates implicit and explicit type conversion between an integer and a float.

Program

#include <stdio.h> int main() { int num = 5; float value = 9.75f; float implicitResult = num; // int to float automatically int explicitResult = (int)value; // float to int using casting printf("Implicit conversion = %.2f\n", implicitResult); printf("Explicit conversion = %d\n", explicitResult); return 0; }

Explanation

Assigning the integer to a float performs implicit conversion. The expression (int)value performs explicit conversion and removes the fractional part.

Expected Output

Implicit conversion = 5.00

Explicit conversion = 9