Monday, February 9, 2009

C's Input and Output Commands

In C, we have to declare our variables. To do this, we have to specify their data types. The following are the basic data types. These are basic data types as well in C++.

int - for integer or whole number values
float - for values with floating points or with decimals
double - similar with float but with bigger range
char - for characters or string of characters

These too can be further modified through the following:

signed unsigned
long short

We use putchar( ) function to display a character at a time and printf () to display more.

Check samples below:
putchar('H'); /*H is displayed on the screen*/
printf("Hello"); /*Hello is displayed*/
int x=5; /*Declaring a variable x with integer data type with initial value of 5*/
printf(%d",x); /*Displaying 5 as the value of x, %d denotes the format specifier for integer*/

We use gets() to read a string of characters,getchar() or getche() for a single character and scanf() to read variants of inputs.

Check samples below:
int x;
scanf("%d",&x); /*to read an integer and assign it to variable x*/

/*the program below reads two integers and computes them*/

[+/-] show/hide

#include stdio.h /*the stdio.h must be enclosed in <> */
{ int x,y,sum;
clrscr(); /*a function to clear your screen*/
printf("\nInput your first number: "); /*\n is used to denote carriage return*/
printf("\nInput your second number: ");
sum=x+y; /*adding x and y and assigning it to variable sum*/
printf("\n The sum of %d and %d is %d",x,y,sum);

The input and output commands in C++ are cin and cout functions. Do check C++ for their uses.

No comments: