Thursday, February 14, 2013

Array in C program

 Array Declaration 

To declare an array we need three things as:
  1. What kind types(i.e. data type) of array?
  2. What is the name of array?
  3. What is the size of array?
In our C program, we have declare array as:

syntax: data_type array_name[SIZE];
example: int result[10];

Here, int is a data type and the word result is the name of array. The [10] is however is new. The number 10 tells how many elements of the type int will be in our array. This number is often called the 'dimension' of the array. The bracket ( [] ) tells the compiler that we are dealing with an array.

 Accessing element of an Array 

Once an array is declared, we can access it and use it in our program.
Now you know that, all the array elements are numbered, starting with 0. Thus, result[10] is not the 10th elements of the array, but the 9th.
We are using the variable i as a subscript to refer to various elements of the array. This variable can take different values and hence can refer to the different elements in the array in turn. This ability to use variables to represent subscripts is what makes arrays so useful.

 Entering Data into an Array 

int result[10];
for(i=0; i<10; i++)
{
 printf("\nEnter elements: ");
 scanf("%d", &result[i]);
}


The for loop causes the process of asking for and receiving a result from the user to be repeated 10 times. The first time through the loop, i has a value 0, so the scanf() functions will cause the value typed to be stored in the array element marks[0], the first element of the array. This process will be repeated until i become 9. This is last time through the loop, which is a good thing, because there is no array element like result[10].

 Reading data from an array 

for(i=0; i<10; i++)
  printf("\n%d",result[i]);

 Array Initialisation 

We has been discuss about how to declare arrays, access them and read them. Let us now see how to initialize an array while declaring it as:

syntax:
data_type arrayName[SIZE]={n1,n2,n3,.....}
Here, n1,n2,... etc are equal to SIZE.

example:
int result[5]={10,20,4,8,99}
float price[]={1.5,53.3,-66.6}
int race[]={11,4,579,31,278,3}

 Till the array elements are not given any specific values, they are supposed to contain garbage values.
 If the array is initialised where it is declared, mentioning the dimension of the array is optional as in the 2nd and 3rd example above.

 Array elements in memory 

Consider the following array declaration:

int arr[5];

What happens in memory when we make this declaration?
10 bytes get immediately reserved in memory, 2 bytes each for the 5 integers. And since the array is not being initialized, all five values present in it would be garbage values. This so happens because the storage class of this array is assumed to be auto. If the storage class is declared to be static then all the array elements would have a default initial value as zero. Whatever be the initial values, all the array elements would always be present in contiguous memory locations. This arrangement of array elements in memory is shown in the following figure as:

Memory representation of array
Figure: Array in memory map demonstration

Related article:

Tuesday, February 12, 2013

Array in C

Before you kick start to reading array, you should understand why array concept is comes? How it is requires in C?

Let's read following program:

#include<stdio.h>
int main()
{
 int r;
 r=1;
 r=2;
 printf("The value of r = %d",r);
 getch();
 return 0;
}

The output of above program would be:
The value of r = 2

So, you can understand that when the value 2 is assigned into r, the earlier value of r (i.e. 1) is lost. Thus the ordinary variables are capable of holding only one value at a time.
What we do if we would want to store more than one value at a time in a single variable?
Here, the comes the concept of array.

What is array?
  1. Array is a collection of similar elements.
  2. The first element in the array is numbered 0, so the last element is 1 less than the size of the array.
  3. An array is also known as a subscripted variable.
  4. Before using an array, its type and dimension must be declared.
  5. The array elements are always stored in contiguous memory locations. This is a very important features of array.
Thus, an array is collection of similar elements. These similar elements could be all ints, or all floats, or all chars.

Array of characters is called a string whereas an array of ints or floats is called simply an array.

Keep in mind that all elements of any array must be the same type. i.e. cannot have an array of 10 numbers, of which 5 are ints and 5 are floats.

Preprocessor directives

The #if directive can be used to test whether an expression evaluates to a nonzero value or not. If the result of the expression is nonzero, then subsequent lines upto a #else, #elif or #endif are compiled, otherwise they are skipped.

Syntax of #if directive as:

#if LABEL == 10
     statement 1;
     statement 2;
#else
     statement 3;
     statement 4;
     statement 5;
#endif


If we so desire, we can have nested conditional compilation directives.


#undef directive

Sometimes, it may be desirable to cause a defined name to become 'undefined'. This can be accmplished by means of the #undef directive.
Syntax: #undef macro_temp_name
example: #undef TEST


#pragma Directive

This is a special directive that we use to turn on or off certain features. Pragma vary from one compiler to another.
Turbo c/c++ compiler has got a pragma that allows you to suppress warnings generated by the compiler.
Some pragmas directives as following:
  • #pragma startup and #pragma exit
  • #pragma warn

Conditional Compilation

What is conditional compilation?
You can understand it by its name i.e. a program is compiling according condition.
In other word, we can, if we want, have the compiler skip over part of a source code by inserting the preprocessing commands #ifdef and #endif, which have the general form:

#ifdef macroname
    statement 1;
    statement 2;
    statement 3;
    statement 4;
#endif

if macroname has been #defined, the block of code will be processed as usual, otherwise not.

File Inclusion

The first preprocessor directive is macro and the second preprocessor directive is file inclusion.
File inclusion causes one file to be included in another.

#include "filename"

What is the meaning of above syntax?
It is simply causes the entire contents of filename to be inserted into source code at that point in the program.

Why file inclusion is used?

If we have a very large program, the code is best divided into several different files, each containing a set of related functions. It is a good programming practice to keep different sections of a large program separate. These files are #included at the beginning of main program file.
There are some functions and some macro definitions that we need almost in all program that we write. These commonly needed functions and macro definitions can be stored in a file, and that file can be included in every program we write, which would add all the statements in this file to our program as if we have typed them in.

There are two way to write #include statement as:

1. #include "myfile.h"
   This command would look for the file myfile.h in the current directory as well as  the specified list of directories as mentioned in the include search path that might have been setup.

2. #include<myfile.h>
   This command would look for the file myfile.h in the specified list of directories only.

Monday, February 11, 2013

Macro Rules and Example

Macro without argument example

A #define directive is many a time used to define operators as shown below:

#include<stdio.h>
#define OR ||
#define AND &&
int main()
{
 int p=10,q=20,r=30;
 if((p==10) AND (q<25 OR r>=50))
    printf("You are winner!!");
 else
    printf("You are loser!!");
 getch();
 return 0;
}

The output of above program would be:
Output of using macro in C program
Figure: Screen shot of shows macro uses in C program


A #define directive could be used even to replace a condition as:


#include<stdio.h>
#define OR ||
#define AND &&
#define RESULT ((p==10) AND (q<25 OR r>=50))
int main()
{
 int p=10,q=20,r=30;
 if(RESULT)
    printf("You are winner!!");

 else
    printf("You are loser!!");
 getch();
 return 0;
}

The output of above program would be:
Output of macro C program
Figure: Screen shot of shows macro uses in C program

A #define directive could be used to replace even an entire C statement.

#include<stdio.h>
#define DISPLAY printf("Yes, I got iT");
int main()
{
 DISPLAY;
 getch();
 return 0;
}

The output of above program would be:
Output of using macro in C program
Figure: Screen shot for macro example C program


Macro with argument example

#include<stdio.h>
#define SQUARE(p) (p*p)
int main()
{
 int n,result;
 printf("Enter any number: ");
 scanf("%d", &n);
 result = SQUARE(n);
 printf("Square of %d is %d",n,result);
 getch();
 return 0;
}

The output of above program would be:
Output of macro square C program
Figure: Screen shot of macro square C program


Keep in mind some following point, when you create macro

1. If there are two or more macro expansions then, entire macro expansions should be enclosed within parentheses.
Example:
#define SQUARE(p) p*p  //wrong 
#define SQUARE(p) (p*p)  //right

2. There should be not a blank between the macro template and its argument while defining the macro.
Example:
#define SQUARE (p) p*p  //wrong 
#define SQUARE(p) (p*p)  //right

3. Macro can be split into multiple lines, with a '\'(back slash) present at the end of each line.
Example:
#include<stdio.h>
#define MYPROG for(c=1; c<=10; c++)        \
               {                           \
                if(c==5)                   \
                   printf("Good C blog."); \
               }
int main()
{
 int c;
 MYPROG
 getch();
 return 0;
}

The output of above program would be:
Output of macro split C program
Figure: Screen shot for macro split C program


Related article:

Sunday, February 10, 2013

Macro Expansion

What is macro?

Let's understand macro using following program:

/*c program for macro expansion*/
#include<stdio.h>
#define LENGTH 3
#define WIDTH 2
int main()
{
 int r,c;
 for(r=1; r<=LENGTH; r++)
 {
  for(c=1; c<=WIDTH; c++)
     printf("%d%d",c,r);
  printf("\n");
 }
 getch();
 return 0;
}

The output of above program would be:

Output of macro C program
Figure: Screen shot of macro C program

In above program, instead of writing 5 in the for loop we are writing it in the form of text as LENGTH and WIDTH, which have already been defined before main() through the statement.
#define LENGTH 3
#define WIDTH 2
This statement is called 'macro definition' or macro.
LENGTH and WIDTH in the above program are often called 'macro templates' , whereas 5 and 3 are called their corresponding 'macro expansions'.

What is reason of using macro in the program?

Macro makes the program easier to read.
For example: if the phrase "%ls[$2]!@" cause the screen to clear, but which would you find easier to understand in the middle of your program "%ls[$2]!@" or "CLRSCREEN"? 
#define CLRSCREEN "%ls[$2]!@"

Macro makes the easyness if we want to change the vale of constant in program. We can change value values of a constant at all the places in the program by just making a change in the #define directive.
This conversion may not matter for small programs shown above, but with large programs, macro definitions are almost indispensable.

Now you will be thinking, there are any similarity in macro and variable? Can i use variable as macro?
(i recommended, before you read next line, you should think about macro and variable properties.)

After thinking you will be find that we also use variable as macro. Then why not use it?

Why the variable is not using as macro because:
  1. Variable may inadvertently get altered somewhere in the program. so it's no longer a constant that you think it is.
  2. Variable is inefficient, since the compiler can generate faster and more compact code for constant than it can for variables.
  3. Using a variable for what is really a constant encourages sloppy thinking and makes the program more difficult to understand: if something never changes, it is hard to imagine it as a variable.

Related Article:
  1. General rules and example of macro