Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Explain variable declaration and rules of variables in C language
Let us first understand, what is a variable.
Variable
It is the name for memory location that may be used to store a data value.
A variable may take different values at different times during execution.
A variable name may be chosen by the programmer in a meaningful way, so as to reflect its function (or) nature in the program.
For example, sum, avg, total etc.
Rules for naming variable
The rules for naming a variable are explained below −
They must begin with a letter.
Maximum length of variable is 31 characters in ANSI standard. But, first eight characters are significant by many compilers.
Upper and lowercase characters are different. For example: total, TOTAL, Total are 3 different variables.
The variable is not to be a keyword.
White space is not allowed.
Variable declaration
The syntax and example with regards to variable declaration are explained below −
Syntax
Given below is the syntax for variable declaration −
Datatype v1,v2,… vn;
Where, v1, v2,...vn are names of variables.
For example,
int sum; float a,b;
Variable can be declared in two ways −
Local declaration − ‘Local declaration’ is declaring a variable inside the main block and its value is available within that block.
Global declaration − ‘Global declaration’ is declaring a variable outside the main block and its value is available throughout the program.
Example
Following is the C program for local and global declaration of variables in C language −
int a, b; /* global declaration*/
main ( ){
int c; /* local declaration*/
- - -
}
Example
Given below is a C program to find the selling price (SP) and cost price (CP) of an article −
#include<stdio.h>
int main(){
float CostPrice, SellingPrice, Amount; //variable declaration
//costprice & sellingprice are variables and
//float is a datatype
printf("
product cost price: ");
scanf("%f", &CostPrice);
printf("
product selling price : ");
scanf("%f", &SellingPrice);
if (SellingPrice > CostPrice){
Amount = SellingPrice - CostPrice;
printf("
Profit Amount = %.4f", Amount);
}
else if(CostPrice > SellingPrice){
Amount = CostPrice - SellingPrice;
printf("
Loss Amount = %.4f", Amount);
}
else
printf("
No Profit No Loss!");
return 0;
}
Output
The output is as follows −
product cost price : 240 product selling price : 280 Profit Amount = 40.0000