Example 1 : Take a character input and print it.
Program :
#include<stdio.h>
void main()
{
char var; /* Variable declaration*/
printf("Please enter a character"); /* This is not necessary we can skip it */
scanf("%c",&var); /* Input stored in variable var*/
printf(" You entered %c",var); /*display of input value*/
}
Output :
Program :
Program :
#include<stdio.h>
void main()
{
char var; /* Variable declaration*/
printf("Please enter a character"); /* This is not necessary we can skip it */
scanf("%c",&var); /* Input stored in variable var*/
printf(" You entered %c",var); /*display of input value*/
}
Output :
Note : - Press Enter key after typing each input to enter it in program. Like in above after typing @ press enter to give it as input to program.
Explanation :
- To use a variable in program, we have to first declare its name along with its type in starting of code. It is an error if you declare them later in code or after their use. Program starts with all variable declarations (if any) then further coding is done.
- Second line is optional, if you won't write it the also you code works properly, but I have used it to convey my message properly to the user of program.
- Third line takes input of a character from keyboard and store it in variable var. &var is necessary to write so for meanwhile learn it as it is, I'll explain this later. Every time you take input in a variable, don't forget to add & sign just before its name.
- Last line displays the content of the variable. This is new use of printf() function. The printf() displays the content of var at same place where its type specifier is written.
Example 2 : Take age, 1st letter of name and height as input and display it back.
Program :
#include<stdio.h>
void main()
{
char name;
int age;
float height;
printf("Enter your age :");
scanf("%d",&age);
printf("Enter 1st letter of your name");
scanf("%c",&name);
printf("Enter your height");
scanf("%f",&height);
printf("Your name : %c Your age %d Your height %f",name,age,height);
}
Output :
void main()
{
char name;
int age;
float height;
printf("Enter your age :");
scanf("%d",&age);
printf("Enter 1st letter of your name");
scanf("%c",&name);
printf("Enter your height");
scanf("%f",&height);
printf("Your name : %c Your age %d Your height %f",name,age,height);
}
Output :
Explanation :
- 1st three lines declare required variables.
- Next 6 lines takes input.
- In last line printf prints whole string as it is but replacing all type specifiers in it with the values in variables. These variables are placed in list in the order which is similar to occurrence of their relevent type specifier.
We will see more such usage with time. Let us get introduced to some basic mathematical operators.
No comments:
Post a Comment