Sunday, 5 May 2013

Escape Sequences in c language


Escape Sequences
Escape sequences are special symbols prefixed with a back slash ( \ ). These symbols are used in printf to provide a formatted output.

Here is the list of escape sequences:
Escape Sequence
Name
Meaning
\a
Alert
Produces an audible or visible alert.
\b
Backspace
Moves the cursor back one position (non-destructive).
\f
Form Feed
Moves the cursor to the first position of the next page.
\n
New Line
Moves the cursor to the first position of the next line.
\r
Carriage Return
Moves the cursor to the first position of the current line.
\t
Horizontal Tab
Moves the cursor to the next horizontal tabular position.
\v
Vertical Tab
Moves the cursor to the next vertical tabular position.
\'

Produces a single quote.
\"

Produces a double quote.
\\

Produces a single backslash.
\0

Produces a null character.
\ddd

Defines one character by the octal digits (base-8 number). Multiple characters may be defined in the same escape sequence, but the value is implementation-specific.
\xdd

Defines one character by the hexadecimal digit (base-16 number).

Consider the following program

main()
{
   int a=3,b=56;
   clrscr();
   printf(“%d\n%d”,a,b);
   getch();
}



Output
3
56

Here output comes in two lines. Notice \n in the printf , first value (3) gets printed then \n moves cursor to the next line and then 56 gets printed.

Use list of different escape sequences in your program and observe the effect.

Input Instruction

Default input device is keyboard. Input instruction makes possible to input data from keyboard.

scanf()

scanf() is a predefined function. It is used to input data from keyboard and stores in variables of the program.

Syntax:
scanf(“format specifier”, address of variable);

Example:
main()
{
   int a;
   scanf(“%d”,&a);
}

In this program, we have declared a variable a of type int. scanf makes possible one integer value through keyboard. scanf receives this value and stores it in variable a.

Here it is important to notice address of operator (&) before variable a. don’t forget to put this operator before variable name. We will understand this operator in great detail in later chapter.

Multiple input

main()
{
   int a;
   float y;
   scanf(“%d%f”,&a,&y);
}

For float variable format specifier should be %f. Here we can input two values, first an integer and second one is float.

Write a program to add two numbers.

main()
{
   int a,b,c;
   clrscr();
   printf(“Enter two numbers”);
   scanf(“%d%d”,&a,&b);
   c=a+b;
   printf(“Sum is %d”,c);
   getch();
}

Output
Enter two numbers5
6
Sum is 11

Now you can use scanf for user input.  

No comments:

Post a Comment