Monday, December 8, 2014

Variable and Data Type in C

  No comments    
categories: 


Variable and Data Type in C
Put simply a variable is what the program used to store a value in computer's memory

Data Type

Data Types of variables tell the computer to store different types of values such as number, text, true/false....They also inform
the computer to reserve the different memory's spaces for those variables.

Here is a table of the data types of variables in C that can be used.


Declaring Variables

Before a variable can be used to store temporary data in computer memory. it must be declared.
To declare a variable in C programming language you must write down its name immediately after its data type.

Example:

int a; //declare a variable a to store integer value

you can declare more than one variable of the same type on a single line by separating them with commas (int i,j;)

Assigning values to variables

Example:

int a=2;
char b=A;

you can also write as shown below

int a;
a=2;
char b;
b=A;

In C a variable can also be a signed variable or an unsigned variable. Signed means that it can have negative numbers and unsigned means it can't but unsigned gives a variable a greater positive range.

Example:

unsigned int i;
To give the variable a smaller or bigger rane respectively. you need to put short or long keywords.

Example:

short int i;

Levels of declaring variables

You can declare variables at two levels--local and global levels. A variable declared at the local level is in a function and it can only be used by the code in that function.
By declaring the variable at global level the variable can be used by code in any function in the program.
You need to declare a global variable outside any function above the main function.

Example:

#include <stdio.h>
#include <stdlib.h>

int x;//Global variable
void printd();
int main(int argc, char *argv[]){
int y=20;//Local variable
x=10;//assign value to x variable
printf("Value of y is:%d\n",y);//using y variable
printd();
system("pause");
return 0;
}
void printd(){
printf("Value of x is:%d\n",x);//using x variable
}

String data type

A string is a type of variable that can store multiple words. You can declare a string in two ways.
The first is to declare it as a string pointer by using Char the means that it points to the first character of the string.

Example:

char *s= "C programming";
The second way is to declare it as an array of character which yo must set a size when you declare it.
you have to use the strcpy function to assign values to it.
You must also include the string header file to be able to use the strcpy function.

Example:

char s[20]

Strcpy(s,"THEARA");






0 comments:

Post a Comment