Type Casting in C
Type casting means explicitly converting a value from one data type to another. It is useful when you need a particular type for a calculation.
Syntax / Basic Pattern
| (target_type) expression |
Easy points to remember
- (float)a / b can produce decimal division.
- Casting does not change the original variable unless you assign the converted value.
- Be careful: converting from a larger/decimal type to a smaller/integer type can lose information.
| ⭐ PRACTICE TIP: Type these programs yourself. Change the values and run them again. That is how control statements become easy. |
Program 1: Integer to float
| #include <stdio.h> int main(){int a=5,b=2;printf(“%.2f”,(float)a/b);return 0;} |
| OUTPUT 2.50 |
Program 2: Float to int
| #include <stdio.h> int main(){float x=9.87;int n=(int)x;printf(“%d”,n);return 0;} |
| OUTPUT 9 |
Program 3: Char to int
| #include <stdio.h> int main(){char c=’A’;printf(“%d”,(int)c);return 0;} |
| OUTPUT 65 |
Program 4: Int to char
| #include <stdio.h> int main(){int n=66;printf(“%c”,(char)n);return 0;} |
| OUTPUT B |
Program 5: Average
| #include <stdio.h> int main(){int a=70,b=80,c=90;printf(“%.2f”,(float)(a+b+c)/3);return 0;} |
| OUTPUT 80.00 |
Program 6: Percentage
| #include <stdio.h> int main(){int obtained=425,total=500;printf(“%.2f%%”,(float)obtained/total*100);return 0;} |
| OUTPUT 85.00% |
Program 7: Division
| #include <stdio.h> int main(){int a=7,b=2;printf(“Int=%d\n”,a/b);printf(“Float=%.2f”,(float)a/b);return 0;} |
| OUTPUT Int=3 Float=3.50 |
Program 8: Double to int
| #include <stdio.h> int main(){double x=12.99;printf(“%d”,(int)x);return 0;} |
| OUTPUT 12 |
Program 9: Char code calculation
| #include <stdio.h> int main(){char c=’C’;printf(“%d”,(int)c+1);return 0;} |
| OUTPUT 68 |
Program 10: Celsius to Fahrenheit
| #include <stdio.h> int main(){float c=25;printf(“%.1f”,(c*9.0f/5.0f)+32);return 0;} |
| OUTPUT 77.0 |
Program 11: Area with double
| #include <stdio.h> int main(){int r=5;double area=3.14159*(double)r*r;printf(“%.2f”,area);return 0;} |
| OUTPUT 78.54 |
Program 12: Average with casting
| #include <stdio.h> int main(){int s=251,n=4;printf(“%.2f”,(double)s/n);return 0;} |
| OUTPUT 62.75 |
Program 13: Explicit long double
| #include <stdio.h> int main(){int a=100,b=6;printf(“%.3Lf”,(long double)a/b);return 0;} |
| OUTPUT 16.667 |
Program 14: Character digit to number
| #include <stdio.h> int main(){char c=’7′;printf(“%d”,(int)c-(int)’0′);return 0;} |
| OUTPUT 7 |
Program 15: Mixed calculation
| #include <stdio.h> int main(){int a=3,b=2;double r=(double)(a+b)/b;printf(“%.2f”,r);return 0;} |
| OUTPUT 2.50 |
