A program that cannot talk to the user is just a silent calculator. C gives you printf for output and scanf for input. These are your program's voice and ears.
printf โ Sending Output
printf stands for "print formatted." You give it a string, and it prints it to the console. You can embed format specifiers in the string to print variables.
%dโ int%fโ float%lfโ double%cโ char%sโ string
scanf โ Reading Input
scanf reads input from the user. You pass the format specifier and the address of the variable where the input should be stored. That is why you see the & symbol โ it means "address of."
Do not forget the &. Forgetting it is one of the most common C mistakes, and the program will likely crash.
#include
int main() {
int age;
float height;
printf("Enter your age: ");
scanf("%d", &age);
printf("Enter your height in meters: ");
scanf("%f", &height);
printf("You are %d years old and %.2f meters tall.\n", age, height);
return 0;
}
Try it Yourself โ