Lets start with the first program in 'C' as to
print "Hello World". Its the best example to initiate to write programs
in 'C' language.
1. C Program to print Hello World
#include<stdio.h>
void main()
{
printf("Hello World\n");
}
Output:- Hello World
Note:- If you are using Devcpp to compile C program then use int main() instead of void main().
Now, lets study the complete program step by step.
#include<stdio.h>
Here,
we include a file named as stdio.h (Standard Input/Output Header file).
With the help of this file, we can use some certain commands for input
or output in the program. Input commands like reading from keyboard and
output command like print things to the screen.
void main()
Here, void is the return type and every
program in 'C' must have a main(). Program actually starts from here
only.
{ }
These are the
beginning and closing curly brackets respectively to group all commands
together. Here, they are used to mark the beginning and end of the
main() function.
printf("Hello World\n");
printf is used
to print the things on the screen. Here, it will print Hello World on
the screen. \n is used to break the line. It represents a new line
character. Everything written after \n will be printed in a new line.
The last ;(semicolon) indicates the termination of the printf line.
2. WAP to take a number as input and print it.
#include<stdio.h>
void main()
{
int a;
printf("Enter a number");
scanf("%d",&a);
printf("Number you entered is %d",a);
}
Output:- Enter a number
5
Number you entered is 5
Explanation for the program
For the starting lines of the program as
#include<stdio.h>, main() etc, you can refer the above first
example's explanation. Now, we start it after main().
int a;
Here, int refers to integer and 'a' is variable written after int. It means, 'a' is an integer variable.
printf("Enter a number")
Whatever you will write in printf, it will be printed he same.
So, on the screen, it will be printed as "Enter a number".
scanf("%d",&a);
scanf is used to take inputs from the user. You can say that
these values entered by user is stored in computer's memory. Here, %d is
used for integer variable.
For character, we use:- %c
For float, we use:- %f
After this there is &a. It is the integer variable defined after main().
printf("Number you entered is %d".a);
Now, the value of integer variable 'a' is stored in
computer's memory. But you have to see it also. For that its necessary
to print the value of 'a' on the screen. And, it requires a printf
command. So, we have used here printf.
But, herein this printf, we
have also a %d. Actually this is also for the variable a whose value is
entered by the user. Note that, after this, there is no '&'. But in
scanf, it is necessary to include it.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment