as

Tuesday 11 November 2014

First Program in C

Best way to learn any language is by examples. So let us start with the coding. In this section, we will write a simple C program. File name – abc.c
//include header files
#include<stdio.h>             
     

//main function
void main()            
{
  
   //declare the variables
   int no;
   char a[30];


//clear the screen
system("cls");

//printf function is used to print the string.

   printf("enter number : ");

//scanf function is used to accept the input from the user.
   scanf("%d",&no);
  
   printf("enter string : ");
   scanf("%s",a);
  
   printf("Display \n");
   printf("number is : %d \n",no);
   printf("String is : %s ",a);
   getchar();                                   
}


Output of the above program is given below.
 

Explanation

Let us try to understand above program.
Program starts with below lines.
//include header files

Any line that starts with // is a comment in C. This is used for single line comment. But if you want to comment multiple lines, you can use below syntax.
/*
Comment Line 1
Comment line 2
….so on
*/
Next line starts with #include.
 #include is called as a pre-processor directive that can be used to include the contents of header file in the program. We have included 1 header file.
#include <stdio.h>                  

<stdio.h> header file contains declarations for functions like prinf, scanf.
Next line starts with void main() function. Every c program has a main function which is the entry point for the program.
In next line, we have declared 2 variables no and a. Variables are used to store the information. Each variable has a data type.
For example data type of no is int. That means this variable can store only integer variables. We will look into more details about variables later in the book.
   int no;
   char a[30];

Next line clears the output screen.
system("cls");

Next lines use printf and scanf functions that can be used to print the output to the console and read data from the user respectively.
Program ends with getchar() function which waits until user enters any character.

In next section, we will see how to compile and execute this program.





No comments:

Post a Comment

Leave your valuable feedback. Your thoughts do matter to us.

Sponsored Links

Popular Posts

Comments

ShareThis