In this source code example, you will learn to use scanf() function to take input from the user, and the printf() function to display output to the user.
C Programming C Programs
1. printf() function
The printf() is a standard output library function used to display the value of a variable or a message on the screen.Syntax:
printf("<message>"); printf("<control string>", argument list separated with commas);
Example: To print a message "Hello World" on the screen
/*Program to print a message "Hello World" */ #include<stdio.h> main() { printf("Hello World"); }
Output:
Hello World
Example 2: To Display Multiple Statements
/*Program to print Name and Address*/ #include<stdio.h> main() { printf("Name: Sachin Tendulkar"); printf("\nQualification: Degree"); printf("\nAddress: Mumbai"); printf("\nWork: Cricket Player"); }
Output:
Name: Sachin Tendulkar Qualification: Degree Address: Mumbai Work: Cricket Player
scanf() function
The scanf() is a standard library function for input operation. This allows a program to get user input from the keyboard. This means that the program gets input values for variables from users.Syntax:
scanf("<format code>",list of address of variables separated by commas)
Example: To accept the values of int, float, and char data types and display them
/*Program to accept values of int, char, float data types Display them in the order of reading*/ #include<stdio.h> main() { char x; int num; float j; /*Accept the values for data types from user*/ printf("Enter Character: "); scanf("%c",&x); printf("Enter Integer Value: "); scanf("%d",&num); printf("Enter Float Value: "); scanf("%f",&j); /*Display the accepted values*/ printf("Integer=%d\tFloat Value=%f\tCharacter=%c",num,j,x); }
Output:
Enter Character: R Enter Integer Value: 10 Enter Float Value: 12.25 Integer=10 Float Value=12.250000 Character=R
Find the Sum and Average of Three Numbers - Read input from user using scanf() and print the result using printf() function
#include<stdio.h> int main( ) { int a,b,c; int sum,average; printf("Enter any three integers: "); scanf("%d%d %d",&a,&b,&c); sum = a+b+c; average=sum/3; printf("Sum and average of three integers: %d %d",sum,average); return 0; }
SAMPLE INPUT:
Enter any three integers:2 4 5
EXPECTED OUTPUT:
Sum and average of three integers: 11 3
Comments
Post a Comment