Saturday, October 13, 2007

Writing a program to print values in variables

Storing data in variables

The easiest way to store a value in a variable named ‘num is by writing the statement num=value.

Here, ‘= is called an assignment operator because it assigns a value to the variable. Writing

num=10;

indicates to the complier that the value ‘10’ should be stored in the ‘num’ variable.

Note: You can use the assignment operator to store a value in a variable you are declaring. For example:

int number=10;

Writing a program to print values in variables

Now that you know how to store values in variables, let us write a program to print stored values on the screen. Consider this program:

/* Author: Globarena

Date: 15/10/2003

Purpose: To print values stored in variables

*/

#include

main()

{

int a=10;

float b=3.1412;

char ch=’A’;

printf(“%d\n%f\n%c”,a,b,ch);

}


When you run this program, the following output will be displayed on screen:

10

3.1412

A

Observe how the printf() function is used in the program. Doesn’t it look different from the printf() used to print messages ? (See article 2.) You might also be wondering what those strange characters (%d, %f, \n, etc.) are.

The characters %d, %f, and %c are called format specifiers or simply format strings. The ‘%’ symbol alerts the compiler that a variable is to be printed at that location and the letter that follows tells it to print the value as an int, float, char, and so on.

The character ‘\n’ is called a newline character. It is used to insert a new line so that the values in variables mentioned after it are printed on a new line (as shown above). If this character is not used, the output will look as shown below:

103.1412A

This would be difficult to comprehend.

Note: Characters like the ‘\n’ character that start with ‘\’ are called escape sequences.

The following tables gives you a partial list of format strings and escape sequences that you will frequently come across in C programs.

Table 2 Table 3

Sl. No

Data type

Format Specifier

1.

int

d

2.

float

f

3.

char

c

4.

unsigned int

u

5.

string

s

6.

long int

ld

7.

double

lf

Sl. No

Escape sequence

Purpose

1.

\n

Newline

2.

\t

Tab

3.

\a

Beep

4.

\b

Backspace

5.

\r

Return


Try it out:

  1. Write a program to store 10, 12.5, and a character ‘Z’ in integer, float, and character variables respectively and display the values on the screen.

Write a program to store 15, 3,14, and ’X’ in integer, float, and character variables respectively and display the values on separate lines on the screen

No comments: