Wednesday, April 4, 2012

Functions

A function is used to perform a specific operation in your program.

The functions are your best and safest bet when moving on to large programs. You cannot just start your program and combine all your program's functionalities within the main function itself. Whenever you indulge in writing programs of large size, always try to use different functions for different operations your program does.

Dividing the program into functions has the following advantages :
  1. Get a better grasp of your program.
  2. You can reuse your function whenever necessary without writing it over and over again.
  3. Do not let your own program confuse you to the bitter end.
A sample program would help you better understand it. Suppose you want to find the factorial of 5 numbers, without using functions, you need to write the loops over and over for 5 times. But with function you dont have to do that. :
Factorial Program without using a seperate function : 
#include<stdio.h>
void main()
{
 int no[2]={4,5},factorial[2];
 int fact=1,i;
 for(i=1;i<=no[0];i++)
 {
  fact = fact*i;
 }
 factorial[0]=fact;
 printf("\n The factorial of %d is %d",no[0],factorial[0]);
 fact=1;
 for(i=1;i<=no[1];i++)
 {
  fact = fact*i;
 }
 factorial[1]=fact;
 printf("\n The factorial of %d is %d\n",no[1],factorial[1]);
} 
Factorial Program with a seperate function :
#include<stdio.h>
int factorial(int num) /* Function that returns integer data type */
{
 int factorial_result=1,i;
 for(i=1;i<=num;i++)
 {
  factorial_result = factorial_result*i;
 }
 return factorial_result; /* Return the factorial result to the calling function */
}
void main()
{
 int no[2]={4,5},fact[2],fact_sec_num;
 printf("\n The factorial of %d is %d ",no[0],factorial(no[0]));
 /* Call the function within printf statement */
 fact_sec_num = factorial(no[1]);
 /* Assign the value returned to fact_sec_num */
 printf("\n The factorial of %d is %d ",no[1],fact_sec_num);
}
When you look at the above example, the first one seems to be redundant and occupying more space which reduces the readability and understanding of the program.

But the second one is pretty much self-explanatory. Whenever you need to calculate the factorial for a number, just call the function instead of writing code for it again and again.

Function Declaration and Definition :
A function can be defined as follows :
return-type function-name(data-type argument-1,data-type argument-2,......)
{
     /* Function Statements - Your function body goes here */
}

Sunday, December 25, 2011

Arrays

An array is a collection of variables of the same  type under a single name. Arrays are used to store data that have common purpose.

Arrays can be of one dimensional, two dimensional or multidimesional. Anyway, multidimensional array those are more than 3 dimensions are hard to imagine. Now, we are going to concentrate on one and  two dimensional arrays.

Very well then. How do I access the array values if all of them have the same name ? Its just like a book. Just as the pages are numbered in a book, each value in an array are identified with what is called as 'index'.

1. One Dimensional Array
Following picture portrays the one dimensional array of size 'n'. As you know, for an array of size 'n', the indices of the array are from '0' to 'n-1' (shown in the picture) :
An one dimensional array of size 'n'
An one dimensional array is declared as follows :
datatype identifier[size(optional)];
(or)
datatype identifier[size(optional)] = {Constants}; 
For example if we declare an array of type 'int' of size 5 and identifier as 'marks' , then the declaration would be as follows :
int marks[5];
//Or else it could be declared and initialized with the values as follows :
int marks[5]={60,67,73,66,70};
Here, marks[0] = 60 marks[1] = 67 marks[2] = 73 marks[3] = 66 marks[4] = 70
Now, lets see this with an example:
/* Fetch marks, Find Total Marks and Display */
#include<stdio.h>
void main()
{
    int marks[5],sum=0,i;
    char name[20];    /* String of size 20 */ 
    /* A String is an array of Characters */  
    printf("\n Demonstration of One Dimensional Array ");
    printf("\n Enter the name of the student : \t");
    gets(name);
    printf("\n Enter the marks obtained in 5 subjects : \n");
    for(i=0;i<5;i++)
    {
        scanf("%d",&marks[i]);        
    }
    printf("\n Student Name : \t %s",name);
    printf("\n Marks ");
    for(i=0;i<5;i++)
    {
        printf("\n %d ",marks[i]);
        sum += marks[i];
    }
    printf("\n Total Marks : \t %d",sum);
}
Sample Output : Demonstration of One Dimensional Array Enter the name of the student : Hari Hara Sudhan Enter the marks obtained in 5 subjects : 12 23 34 45 56 Student Name : Hari Hara Sudhan Marks 12 23 34 45 56 Total Marks : 170
2. Two Dimensional Array
The two dimensional array consists of rows and columns. An array of m rows and n columns is of size m * n. The numbering goes from 0 to m-1 for rows and 0 to n-1 for columns.


datatype identifier[rows][columns];
(or)
datatype identifier[rows][columns] = {Constants};


The two dimensional array is pictorially represented as follows :
Two Dimensional Array of 'm' rows and 'n' columns
Here is an example how a two dimensional array is declared and initialized :


int array[4][3]={{1,2,3},{4,5,6},{7,8,9},{10,11,12}};
In this, each row is seperated from the other by using curly braces. Thus the first row is : array[0][0] = 1 array[0][1] = 2 array[0][2] = 3 The second row is : array[1][0] = 4 array[1][1] = 5 array[1][2] = 6 The third will be : array[2][0] = 7 array[2][1] = 8 array[2][2] = 9 The fourth row will be : array[3][0] = 10 array[3][1] = 11 array[3][2] = 12
Now, lets see this with an example :
#include<stdio.h>
void main()
{
    int item_details[20][3],i,count=0; /* Three Columns - Unit Price, Quantity, Total Price 
    item_details[some_row][0] - item price
    item_details[some_row][1] - item quantity 
    item_details[some_row][2] - item total price
    A maximum of twenty rows */
    char item_name[20][25],choice;    /* Here item_name - Maximum of 25 characters(columns) and 20 names(rows)*/
    printf("\n Demonstration of two dimensional array ");
    do
    {
         printf("\n Enter the Item name : \t ");
         gets(item_name[count]);
         /* gets - used to get a line of characters from the user */
         printf("\n Enter the per item price : \t ");
         scanf("%d",&item_details[count][0]);
         /* Get the item price */
         printf("\n Enter the quantity : \t ");
         scanf("%d",&item_details[count][1]);
         /* Get the item quantity */
         item_details[count][2] = item_details[count][0] * item_details[count][1];
         /* Calculate the total price
              total price = item price * quantity    */ 
         printf("\n Do you want to add another item (y/n) ? ");
         count++;
         choice = getchar();
         fflush(stdin);         /* Clear the Input Buffer */
    }while(choice=='y'||choice=='Y');
    printf("\n\n Items List : ");
    printf("\n Item Name \t Item Price \t Quantity \t Total Price");
    for(i=0;i<count;i++)
    {
 printf("\n %s \t\t %d \t\t %d \t\t %d",item_name[i],item_details[i][0],item_details[i][1],item_details[i][2]);
    }
}

Branching Statements

The branching statements are used to take the control of the program to elsewhere in the program. There are three branching statements. They are :
  1. break
  2. continue
  3. goto and labeled statements
1. break :
The break statement is used to terminate the current iteration and passes the control to the subsequent statements. It is most frequently used within the switch statement to terminate the current case and so the following case does not start executing its statement.

The following example demonstrates the break statement :
#include<stdio.h>
void main()
{
    int i=5;
    printf("\n Demonstration of break statement ");
    while(1)
    {
        printf("\n %d ",++i);  /* Increments the value of i and then prints the value */
      
  if(i==10)
            break;    /* Loop terminates when the value of i reaches 10 */
    }
    printf("\n Loop terminated at i = %d",i);
}        
Here in this program when the value of the variable i reaches the value 10, the 'break' statement will terminate the iteration. So the output of this will be :
Output :

Demonstration of break statement
6 
7
8
9
10
Loop terminated at i = 10
2. continue
The 'continue' statement is used to skip the current iteration and continue with the next iteration based on the condition specified.
An illustration will be helpful to understand this :
/* Printing the odd numbers from 1 to 10 */
#include<stdio.h>
void main()
{
    int i;
    printf("\n Demonstration of continue statement ");
    for(i=1;i<=10;i++)
    {
        if(i%2==0)    /* If i is even, then move on to next iteration */
            continue;
        printf("\n %d ",i);
    }    
}
In the above example, only for odd values of i, 'i' will be printed on the screen. On the occurrence of even values of i, the loop will be skipped and so 'i' will not be printed on the screen.
The output of the above program will be :
Demonstration of continue statement
1
3
5
7
9
3. goto and labeled statements
The goto statement is used to transfer the execution of the program to a label. The following limitations apply when using goto and labeled statements:
  1. The label used is unique i.e. only one label name should be used within a function.
  2. The branching can be done only within a function. i.e. goto statement and its label should be present within the same function.
Now, look at the following example :
/* Print numbers from 1 to 5 */
#include<stdio.h>
void main()
{
    int i=0;
    printf("\n Demonstration of goto and labels ");
    while(1)
    {
        printf("\n %d ",++i)
        if(i==5)
            goto abc; /* Transfer control to label 'abc'
    }
    abc: printf("\n Iteration stopped at i = %d ",i); /* Control is transferred here */
}
Here, in this example, when the value of i reaches 5, the goto statement transfers the control to the label 'abc'. Hence the output will be :
Demonstration of goto and labels
1
2
3
4
5
Iteration stopped at i = 5