Monday, January 6, 2014

Basic Input Output

Basic Input and Output in C is easy to learn. You just have to memorize the function for displaying messages [ printf() ]  and getting the input [ scanf() ].  

printf("Some message");
scanf("%+data type",&+variable name);

But first, you need to declare the variable to be used. A variable is where you store the value for the input data. For numbers that range from 1-4 digits, we use the integer or int data type [ d or i ].
For more than 4 digit numbers, we use the long int
 
For int data type:                                                             For long data type:

int num;                              //declare the variable              long int num;
printf("Enter Number: ");    //prompt the  user                   printf("Enter Serial Number: "); 
scanf("%d",&num);           //input data                              scanf("%ld",&num);     // we use %ld for long int   

When getting letters or characters, we use the char data type [ c ].

char letter;
printf("Enter Your Letter: ");
scanf("%c",&letter);

 However the char data type only holds a single character. For getting characters more than 1, we use an array to declare how many characters the user can enter. 

char name[6];                //declare the variable and how many characters can be entered
printf("Enter Name: ");
scanf("%c",&name);



Now that we know the basic data types and how to input data, we can now proceed with the printing of the entered data. In printing data, the same format is used as entering data, the only difference is we use the printf() function in printing data. By the way, unlike other programming languages, C doesn't print or display another message on the following line. So to make the program more neat, we use [ \n ] to make another message appear on the next or new line.

Try the following code:

#include<stdio.h>
main()
{
int name[6];
clrscr();   

printf("Enter Name: ");           //prompt the user
scanf("%c",&name);             //input data

printf("/nHello %c!",name);   //display the data using the printf() function and \n for it to appear on the next line

getch();
}

Output:

Enter Name: Syntax
Hello Syntax!





No comments:

Post a Comment