Unit 2
Unit 2
1.Explain with example declaring, initializing and assigning values to the variable.
A variable is a data name that may be used to store a data value.
Declaration Of Variables
Variables must be declared before they are used. Declaration serves two purposes
I. It tells the compiler what the variable name is.
2. It specifies what type of data the variable will hold.
Primary Type Declaration
A variable can be used to store a value of any data type. The syntax for declaring a variable
is as follows:
data-type vl,v2, .... vn;
vl, v2, ....vn are the names of variables. Variables are separated by commas. A declaration
statement must end with a semicolon. Some valid declarations are:
int count ;
int number, total;
double ratio;
int and double are the keywords to represent integer type and real type data values
respectively. Table shows various data types and their keywords.
Note that the qualifiers short, long, or unsigned are by default int. If we want to declare
a character variable as unsigned, then we must use both the terms like unsigned char.
Assigning values to the variables:
Assigning values can be done in three ways- They are : Using assignment statement,
Initialization and inputting using scanf
Assignment statement : Values can be assigned to variables using the assignment
operator = as follows :
variable_name=constant;
Examples : initial_value=0;
Balance=78.23;
C permits multiple assignments in one line. For example, the following is valid.
initial_value=0; Balance=78.23;
An assignment statement calculates the value of the expression on the right hand side
and assigns it to the variable on the left hand side. Hence following are valid :
ch=ch+32; fact=fact*i;
Initialization : It is the process of assigning values to variables at the time of declaration.
The general form is :
data-type variable_name=constant;
Examples : int final_value=100; float bal=23.67;
C permits initialization of more than one variable in one statement Example :
int p=q=r=10;
External variables are initialized to zero by default. Local variables that are not initialized
contain garbage value.
Reading data from keyboard :
Scanf is used to read data from keyboard. It has the following general form :
scanf(“control string”,&variable1, &variable2,….);
Example
/*program for assigning value of variable*/
#include<stdio.h>
#include<conio.h>
void main()
{
int num1, num2;
float a, b;
chat ch;
clrscr() ;
num1=10;
num2=2000;
a=87.56;
b=34567.21367;
ch='M';
printf("num1=%d\n", num1);
printf("num2=%d\n", num2);
printf("a=%f\n",a);
printf("b=%5.2f\n", b);
printf("ch=%c\n", ch);
getch();
}
4. Explain token in C.
C Tokens
In a passage of text, individual words
and punctuation marks are called
tokens. Similarly, in a c program the
smallest individual units are knownas
C tokens. C has six types of tokens as
shown in Fig. C programs are written using these tokens and the syntax of the language.
Getchar Putchar