Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

Thursday, July 14, 2011

SWITCH-CASE STATEMENT

SWITCH-CASE STATEMENT

Switch Statements

The switch and case statements help control complex conditional and branching operations. The switch statement transfers control to a statement within its body.
Syntax:
The general form of a switch statement is:
switch (variable)
{
    case expression1:
        do something 1;
        break;
    case expression2:
        do something 2;
        break;
      ....
    default:
        do default processing;
}

Example :
#include<stdio.h>
 
main()
{
    int x;
 
    printf("Enter the any number");
    scanf("%d", &x);
 
    switch(x)
{
 case 1:
    printf("I am in Case one");
    break;
 case 2:
    printf("I am in case two");
    break;
 case 3:
    printf("I am in case three");
    break;
 default:
    printf(" I am in Default");
}
}
 
In above program if we enter 1 value in x then the output will be:
I am in Case one
When an expression is found that is equal to the tested variable, execution continues until a break statement is encountered. It is possible to have a case without a break. This causes execution to fall through into the next case. This is sometimes very useful.

STORAGE CLASSES : Programming

STORAGE CLASSES

Introduction

The storage class determines the part of memory where storage is allocated for an object (particularly variables and functions) and how long the storage allocation continues to exist.
A scope specifies the part of the program which a variable name is visible, that is the accessibility of the variable by its name.  In C program, there are four storage classes: automatic, register, external, and static.
Moreover, a variable's storage class tells us:
  • Where the variable would be stored
  • What will be the initial value of the variable, if initial value is not specifically assigned(i.e. the default initial value)
  • What is the scope of the variable; i.e. in which functions the value of the variable would be available.
  • What is the life of the variable; i.e. how long would the variable exist.

Automatic Storage Class

The features of a variable defined to have an automatic storage class are as under
Storage
Memory
Default initial value
Garbage value
Scope
Local to the block in which the variable is defined
Life
Till the control remains within the block in which the variable is defined
  • The scope of automatic variables is local to the block in which they are declared, including any blocks nested within that block. For these reasons, they are also called local variables.
  • No block outside the defining block may have direct access to automatic variables (by variable name) but, they may be accessed indirectly by other blocks and/or functions using pointers.
  • Automatic variables may be specified upon declaration to be of storage class auto. However, it is not required to use the keyword auto because by default, storage class within a block is auto.
  • Automatic variables declared with initializers are initialized every time the block in which they are declared is entered or accessed.
  • auto is the default storage class for local variables.

Example
void main()    
{
    int Count;
    auto int Month;
}
The example above defines two variables with the same storage class. auto can only be used within functions, i.e. local variables.

Register Storage Class

The features of a variable defined to have an automatic storage class are as under
Storage
CPU Register
Default initial value
Garbage value
Scope
Local to the block in which the variable is defined
Life
Till the control remains within the block in which the variable is defined
  • Registers are memory located within the CPU itself where data can be stored and accessed quickly. Normally, the compiler determines what data is to be stored in the registers of the CPU at what times.
  • register is used to define local variables that should be stored in a register instead of RAM. This means that the variable has a maximum size equal to the register size (usually one word) and can't have the unary '&' operator applied to it (as it does not have a memory location).
Example:
      void main()
      {
        register int  Miles;
      }

Static Storage Class

The features of a variable defined to have an automatic storage class are as under
Storage
Memory
Default initial value
Zero
Scope
Local to the block in which the variable is defined
Life
Value of the variable persists between different function calls
  • Static automatic variables continue to exist even after the block in which they are defined terminates. Thus, the value of a static variable in a function is retained between repeated function calls to the same function.
Comparing two storage class we get to know how static storage class variable works and auto storage class works.
Auto Storage Class
Static Storage Class
void Increment()
{
    auto int i=1;
    printf("%d\n",i);
    i=i+1;
}
void main()
{
    Increment();
    Increment();
    Increment();
}
void Increment()
{
    static int i=1;
    printf("%d\n",i);
    i=i+1;
}
void main()
{
    Increment();
    Increment();
    Increment();
}
Output:
1
1
1
Output:
1
2
3
Each time the Increment() function is called i variable is taken as new and each time i is initialized with 1 so when i is printed each time it displays 1
When first time Increment() function is called i variable is initialized to 1 and next two time the value will be incremented by one. That is when Increment() function is called second time i variable in not initialized again but will directly goto printf() and displays the value of i i.e. 2 and so on it displays 3

External Storage Class

The features of a variable defined to have an automatic storage class are as under
Storage
Memory
Default initial value
Zero
Scope
Globle
Life
As long as the program's execution doesn't come to an end
  • All variables we have seen so far have had limited scope (the block in which they are declared) and limited lifetimes (as for automatic variables).
  • However, in some applications it may be useful to have data which is accessible from within any block and/or which remains in existence for the entire execution of the program. Such variables are called global variables, and the C language provides storage classes which can meet these requirements; namely, the external (extern) and static (static) classes.
  • Declaration for external variable is as follows:
  • extern int var;
  • External variables may be declared outside any function block in a source code file the same way any other variable is declared; by specifying its type and name (extern keyword may be omitted).
Example:
#include<stdio.h>
extern int i;    
void Increment()
{    
      i=i+1;
      printf("%d\n",i);
}
void Decrement()
{    
      i=i-1;
      printf("%d\n",i);
}
void main()
{    
      printf("initial value=%d\n",i);
      Increment();
      Increment();
      Decrement();
      Decrement();
}

          Output:

                    initial value = 0
                    1
                    2
                    1
                    0


Book : Let us C

INPUT/OUTPUT : Programming

INPUT/OUTPUT
Usually i/o, input and output, form an important part of any program. To do anything useful your program needs to be able to accept input data and report back your results. In C, the standard library provides routines for input and output. The standard library has functions for i/o that handle input, output, and character and string manipulation. In this lesson, all the input functions described read from standard input and all the output functions described write to standard output. Standard input is usually the keyboard. Standard output is usually the monitor.

Formatted Output

The standard library function printf is used for formatted output. It takes as arguments a format string and an optional list of variables or literals to output. The variables and literals are output according to the specifications in the format string. Here is the prototype for printf.
int printf(const char *format, arg1, arg2, arg3, ......);
Example: Adding two number
#include
#include
void main()
{
    int a,b,c;
    printf("enter the value for a and b");
    scanf("%d %d", &a, &b);

    c= a + b;

    printf("%d + %d = %d" ,a ,b ,c);
    getch();
}
Here are the more common conversion specifiers.
Specifier
Argument Type
%d
int
%f
float or double
%e
float or double, output in scientific notation.
%c
character
%s
character string (char *)

Formatted Input Output

The standard library function scanf is used for formatted input. It takes as its arguments a format string and a list of pointers to variables to store the input values. Similar to its use in printf, the format string can contain literals and conversion specifiers. In C, to return a value from a function to a calling routine, a pointer to a variable is passed into the function. A pointer stores the memory address of another variable. The methods of passing and returning values from functions are described in Passing Arguments to Functions. Don't worry if you don't understand pointers completely. For now, all this means is a slightly different notation in the call to scanf. In later lessons, pointers and functions will be fully explained. Here is the prototype of scanf and a program illustrating its use.
Scanf returns an integer, either the number of values read in, or EOF if an end of file is reached. EOF is a special termination character, specified in stdio.h, which designates the end of a file. If no values are successfully read, scanf returns 0. To use scanf in a program, the file stdio.h must be included.

WAP to find out simple interest (SI) and Amount (A), given that SI=PRT/100 and A=P+SI.
#include<stdio.h>
#include<conio.h>
void main()
{
   float p,t,r,A,SI;
   printf("Enter value p, t, r ");
   scanf("%f %f %f",&p,&t,&r);

   //calculating simple interest
   SI=(p*t*r)/100;

   //calculating Amount
   A=SI+p;

   printf("Simple interest=%f, Amount=%f", SI, A);
   getch();
}

Unformatted Input / Output

Unformatted functions do not allow the user to read or display data in desired format. These library functions basically deal with a single character or a string of characters. The functions getchar(), putchar(), gets(), puts(), getch(),gerche () , putch() are considered as unformatted functions.

getchar and putchar

getchar reads a single character from standard input.
putchar writes a single character to standard output.
Example:
#include<stdio.h>
void main()
{
    char c;

    c = getchar(); /* to take input form keyboard */
    putchar(c);    /* to display value of 'c' in screen */
}

gets and puts

gets reads a line of input into a character array (String).
puts writes a line of output to standard output .
Example:
#include<stdio.h>
void main()
{
     char str[120]; /* Holds input and output strings */
     gets(str); /* to take string as input form keyboard */
     puts(str); /* to display value of 'str' string in screen */
}

FILE HANDELING

FILE HANDELING

File Input and Output


Library Functions for File I/O.

fopen is used to open a file for formatted I/O and to associate a stream with that file. A stream is a source or destination of data. It may be a buffer in memory, a file or some hardware device such as a port.
FILE *fp;
fp=fopen(filename, mode);
fopen() returns a file pointer on success or NULL on failure. The file pointer is used to identify the stream and is passed as an argument to the routines that read, write or manipulate the file. The filename and mode arguments are standard null-terminated strings. The valid modes are shown below.
Mode Use
"r" Read Mode.If the file exists, loads it into memory and sets up a pointer which points to the first character in it. If the file doesn't  exist it returns NULL.
Operations Possible:- reading from the file
"w" Write Mode. If the file exists, its contents are overwritten. If the file doesn't exist, a new file is created. Returns NULL, if unable to open file.
Operations Possible:- writing to the file
"a" Append Mode. If the file exists, loads it into memory and sets up a pointer that points to the last character in it. If the file doesn't exist, a new file is created. Returns NULL, if unable to open file
Operations Possible:- adding new contents at the end of file
"r+" Read Plus Mode. If the file exists, loads it into memory and sets up a pointer which points to the first character in it. If the file doesn't  exist it returns NULL.
Operations Possible:- reading existing contents, writing new contents, modifying existing contents of the file
"w+" Write Plus Mode. If the file exists, its contents are destroyed. If the file doesn't exist, a new file is created. Returns NULL, if unable to open file.
Operations Possible:- writing new contents, reading them back and modifying existing contents of the file
"a+" Append Plus Mode. If the file exists, loads it into memory and sets up a pointer that points to the first character in it. If the file doesn't exist, a new file is created. Returns NULL, if unable to open file
Operations Possible:- reading existing contents, appending new contents to the end of file. Cannot modify existing contents.
Files are closed with the function fclose. Its prototype is:
fclose(*fp);

Functions for Reading and Writing to the file

fprintf():

Data is written to a file using fprintf. This function is very similar to printf. Printf was used to write to standard output, stdout. Fprintf has one additional argument to specify the stream to send data. Its prototype is:
fprintf(FILE *stream, const char* format, ....);

fscanf():

Data is read from a file using fscanf. This function is very similar to scanf, is used to read from standard input, stdin. Fscanf has one additional argument to specify the stream to read from. Remember that the argument to store data must be pointers.
fscanf(FILE *stream, const char* format, ....);

Other Useful Standard Library Functions for Input and Output

int fgetc(FILE *stream);
This function returns the next character in the input stream, or EOF if the end of the file is encountered. It returns int rather than char because the "end of file", EOF, character must be handled. EOF is an int and is too large to fit in a char variable.
int *fgets(char *s, int n, FILE *stream);
It returns a pointer to the character string if successful, or NULL if end of file is reached or if an error has occurred. The string is also read into the character array specified as an argument. The character string will be terminated be a "\0", which is standard for C.
At most n-1 characters will be read. This allows for storage of the string terminator, '\0'.
fputs(const char s*, FILE *stream);
This function writes a string to the stream. It returns EOF on failure.
int fputc(int c, FILE *stream);
fputc writes a single character to the output stream i.e. file. It returns EOF on failure.
int sprintf(char *buffer, const char *format, ...);
This function is the same as fprintf, except data is written into a character buffer rather than an output stream.
int sscanf(char *buffer, const char *format, ...);
This function is the same as fscanf, except data is read from a character buffer rather than an input stream.

Example 1: Here is the example program which creates a file "Record.txt" and adds students record in it.
#include<stdio.h>

main()
{
    char name[30];
    int idNum;
    FILE *fp;

    /* Open file for input */
    fp = fopen("Record.txt","w");
if(fp==NULL)
{
    printf("Error Opening File !!!");
    exit(1);
}
 
printf("Enter name and id")
scnaf("%d %s", name, &idNum);
 
/* Write out data */
fprintf(fp,"%d %s\n",idNum, name);
 
/* Close Files */
fclose(fp);
}
Example 2: Here is the example program which reads name and id form student record a file "Record.txt" and displays on screen.
#include<stdio.h>

main()
{
    char name[30];
    int idNum;
    FILE *fp;

    /* Open file for read */
    fp = fopen("Record.txt","r");
if(fp==NULL)
{
      printf("Error Opening File !!!");
      exit(1);
}
/*reading all records form file */
while(fscanf(fp,"%d %s", &idNum, name) != EOF)
          printf("%d %s\n", idNum, name);
 
/* Close Files */
fclose(fp);
}
Example: Create a file name "COLLEGE.DAT". Write a program to store record of n students in a file. These records contain student name, roll no, program. Also display records of those students whose program is BBAII and BCA II.
#include<stdio.h>
#include<conio.h>
#include<string.h>
#define N 2 //defining the N no. of student
void main()
{  
    struct student
    {
          int roll_no;
          char name[25],program[25];            
    };
    struct student s;
    int i;
    FILE *fp;
 
    fp = fopen ("COLLEGE.DAT ", "w+");
    if (fp == NULL);
    {
          puts("Cannot open file");          
          exit(0);
    }    
    //taking student records as input and writing it into file
    for(i=0;i<N;i++)
    {
          scanf("%d %s %s %d",&s.roll_no,s.name, s.program);
          fwrite(&s,sizeof(s),1,fp);//writing record into file
    }
   
    //reading from file until end of file
    while(fread(&s,sizeof(s),1,fp)!=EOF)
    {    
          //displaying only those records having program is BBAII or BCAII
          if(strcmp(s.program,"BBAII")==0||strcmp(s.program,"BCAII")==0)
                printf("%d\t %s\t %s\n",s.roll_no,s.name,s.program); 
    }    
    fclose(fp);
    getch();
}

STRUCTURE

STRUCTURE

Structures


Structures are used to group a number of different variables together which enables us treat a number of different variables stored in different place in memory.

Syntax:

struct structure_name
{
Data_type member;
........
};
struct structure_name  structure_variable;

Declaring Structures

A structure is declared by using the keyword struct followed by an optional structure tag followed by the body of the structure. The variables or members of the structure are declared within the body. Here is an example of a structure that would be useful in representing the book containing id, name of book and price.
struct book {
   int id;
   char name[25];
    float price;
};
The struct declaration is a user defined data type. Variables of type book may be declared similarly to the way variables of a built in type are declared.
struct book b1, b2;

Example: Simple example to declare structure and performing input/output process.
#include<stdio.h>
#include<conio.h>
main()
{
struct book
{
      int id;
      char name[25];
      float price;
};
struct book b1;
 
printf("Enter the record of book");
scanf("%d %s %f", &b1.id, b1.name, &b1.price);
 
//displaying the book record
printf("%d %s %f", b1.id, b1.name, b1.price);
 
getch();
}

Arrays of Structures

The data structures needed to solve some problems are best represented as an array of structures. Consider, for instance, the problem of storing 100 books record. Here we need to declare book variable like b1, b2, b3 and so on to b100, which is very hard way of doing so. So, this problem can be made easier by using array of structure. Array of structure is declared as follows:
struct book{
    int id;
    char name[25];
    float price;
    };
struct book b[100];
Example: Here is a simple program to illustrate the use of some of these array of structure. This program will input 100 book record and finds out the number of books price above 300.
#include<stdio.h>
#include<conio.h>
main()
{
struct book
{
      int id;
      char name[25];
      float price;
};
struct book b[100];
int i, ctr=0;
 
printf("Enter the 100 records of book");
for(i=0; i<100; i++)
      scanf("%d %s %f", &b[i].id, b[i].name, &b[i].price);
 
//finding out the book record whose price is above 300
for(i=0; i<100; i++)
{
if(b[i].price > 300)
      ctr = ctr +1;
}
 
printf("No. of books having price above 300 is %d", ctr);
 
getch();
}

Nested Structure

When a structure is created at first and then again is called by another structure as a member of it. We call this mechanism as nested structure. In another simply can say, structures can contain other structures as members then we call it as nested structure.

 Declaration:

struct Date
{
int dd, mm, yy;
};
struct book
{
int id;
char name[25];
float price;
struct Date issue;
};
struct book b;

Example:

    #include<stdio.h>
    void main()
    {
          struct Date
          {
                int dd, mm, yy;              
          };
          struct student
          {
                int roll;
                char name[25]
                struct Date dob;       
          };
          struct student s;
         
          //taking input in normal structure
          scanf("%d %s",&s.roll, name);
          //taking input in nested structure
          scanf("%d %d %d",&s.dob.dd, &s.dob.mm, &s.dob.yy);
         
          //Displaying the value of structure
          printf("%d %s",s.roll, name);
          //Displaying the value of nested structure
          printf("%d %d %d",s.dob.dd, s.dob.mm, s.dob.yy);
         
          getch();      
    }

UNION

UNION

Union

Union is used to group a number of different variables together which enables us to treat the same space in memory as a number of different variables. Union and structure are exactly alike, the only difference is that structure uses different memory space to store different variables but union uses the same memory space to store different variable.

Syntax:

union structure_name
{
Data_type member;
........
};
union structure_name  structure_variable;

Declaring Union

A union is declared by using the keyword union followed by an optional union tag followed by the body of the union. The variables or members of the union are declared within the body. Here is an example of a union that would be useful in representing the book containing id, name of book and price.
union book {
   int id;
   char name[25];
    float price;
};
The union declaration is a user defined data type. Variables of type book may be declared similarly to the way variables of a built in type are declared.
union book b1, b2, b[100];
Example:
#include<stdio.h>
#include<conio.h>
 
void main()
{
    union try
    {
          int i;
          char ch[2];
    };
   
    union try t;
   
    t.ch[0]=50;
    t.ch[1]=30;
    t.i=512;
 
    printf("t.i=%d\n",t.i);
    printf("t.ch[0]=%d\n",t.ch[0]);
    printf("t.ch[1]=%d",t.ch[1]);
}
Output:
t.i = 512
t.ch[0] = 0
t.ch[1] = 2
Reason:
Values of t.ch[0] and t.ch[1] i.e. 50 and 30 , is changed to 0 and 2 respectively after t.i is assigned with 512. This happens because t.ch[0] and t.ch[1] share the same memory.

Difference Between Structure And Union

 DIFFERENCE BETWEEN STRUCTURE AND UNION

Difference Between Structure And Union


Structure
Union
1
Structures are used to group a number of different variables together which enables us treat a number of different variables stored in different place in memory.
Union are used to group a number of different variables together which enables us to treat the same space in memory as a number of different variables.
2
Syntax:
struct structure_name
{
Data_type member;
........
};
struct structure_name  structure_variable;
Syntax:
union structure_name
{
Data_type member;
........
};
union structure_name  structure_variable;
3
Example:
#include<stdio.h>
#include<conio.h>

void main()
{
  struct try
  {
      int i;
      char ch[2];
  };

  struct try t;

  t.ch[0]=50;
  t.ch[1]=30;
  t.i=512;

  printf("t.i=%d\n",t.i);
  printf("t.ch[0]=%d\n",t.ch[0]);
  printf("t.ch[1]=%d",t.ch[1]);
}
Output:
t.i = 512
t.ch[0] = 50
t.ch[1] = 30
Reason:
t.ch[0] , t.ch[1] and t.i values are stored in different memory locations there for, no values are changed
Example:
#include<stdio.h>
#include<conio.h>

void main()
{
union try
{
      int i;
      char ch[2];
};

union try t;

  t.ch[0]=50;
  t.ch[1]=30;
  t.i=512;

printf("t.i=%d\n",t.i);
printf("t.ch[0]=%d\n",t.ch[0]);
printf("t.ch[1]=%d",t.ch[1]);
}
Output:
t.i = 512
t.ch[0] = 0
t.ch[1] = 2
Reason:
Values of t.ch[0] and t.ch[1] i.e. 50 and 30 , is changed to 0 and 2 respectively after t.i is assigned with 512. This happens because t.ch[0] and t.ch[1] share the same memory.

FUNCTION

FUNCTION
A self-contained software routine that performs a task. Functions can do a large amount of processing or as little as adding two numbers and deriving a result. Values are passed to the function, and values may be returned. Or, the function may just perform the operation and not return a resulting value. The concept of a function within a program is that, once written, it can be used over and over again without the programmer having to duplicate the same lines of code in the program each time that same processing is desired.
Syntax:
return_type function_name(list of parameters);
Example:
int max(int n1, int n2);    /* A programmer-defined function */
int printf(const char *format,...);    /* From the standard library */
int fputs(const char *buff, File *fp);    /* From the standard library */

Local Variables

The scope of a variable is simply the part of the program where it may be accessed or written. If a variable is declared within a function, it is local to that function. Variables of the same name may be declared and used within other functions without any conflicts.
int fun1()
{
    int a;
    int b;
    ....
}

int fun2()
{
    int a;
    int c;
    ....
}
Here, the local variable "a" in fun1 is distinct from the local variable "a" in fun2. Changes made to "a" in one function have no effect on the "a" in the other function. Also, note that "b" exists and can be used only in fun1. "C" exists and can be used only in fun2. The scope of b is fun1. The scope of c is fun2. Note that main is also a function. Variables declared after the opening bracket of main will have all of main as their scope.

External Variables

Variables may also be defined outside of any function. These are referred to as global or external variables. The scope of an external variable is from its declaration to the end of the file.
int j;
...
int main()
{
    ....
}

int k;
float funA()
{
}
int l;
float funB()
{
}
The variable "j" will be visible in main, funA and funB. The variable "k" will be visible in funA and funB only. The variable "l" will be visible only in function funB.
An important distinction between automatic (local) variables and external (global) variables is how they are initialized. External variables are initialized to zero. Automatic variables are undefined. They will have whatever random value happens to be at their memory location. Automatic, or local, variables must always be initialized before use. It is a serious error, a bug, to use a local variable without initialization.

Functions: TYPES OF FUNCTIONS

TYPES OF FUNCTIONS

1.  Function Without return_type and without parameters:

#include<stdio.h>
#include<conio.h>
 
void add()
{
    int x, y;
   
    printf("Enter value for x and y");
    scanf("%d %d", &x, &y);
 
    printf("Sum of x and y is %d", x+y);
}
main()
{
    add();
    getch();
}
void keyword is used since no return type is needed.

2.  Function Without return_type and with parameters:

#include<stdio.h>
#include<conio.h>
 
void add(int x, int y)
{
    printf("Sum of x and y is %d", x+y);
}
main()
{
    int x, y;
   
    printf("Enter value for x and y");
    scanf("%d %d", &x, &y);
   
    add(x,y);
 
    getch();
}
Above example is of without return type so void keyword is used. Variable x and y is used as parameter in function add() whose value is supplied from  main() function.

3.  Function With return_type and without parameters

#include<stdio.h>
#include<conio.h>
 
int add()
{
    int x, y;
   
    printf("Enter value for x and y");
    scanf("%d %d", &x, &y);
 
    return(x+y);
}
main()
{
    int sum;   
    sum=add();
 
    printf("Sum of x and y is %d", sum);
    getch();
}
In add() function int return type is used and at last line of add() function return keyword is used to return added value of x and y to main function to display.

4.  Function With return_type and with parameters

#include<stdio.h>
#include<conio.h>
 
int add(int x, int y)
{
    return(x+y);
}
main()
{
    int x, y, z;     
   
    printf("Enter value for x and y");
    scanf("%d %d", &x, &y);
 
    z=add(x, y);
   
    printf("Sum of x and y is %d", z);
    printf("Sum of x and z is %d", add(x,z));
 
    getch();
}
main() function calls add() function by passing two value. add() function those two value as parameter and performs addition and returns the added value to main() function so that main() function can display the added value.


Example 1: Write a program to find the factorial of N number using function.
#include <stdio.h>
#include<conio.h>
 
long int fact(int n);       //prototype
 
main()
{
    long int f;
    int x;
 
    printf("enter the value for x:")
    scanf("%d", &x);
 
    f = fact(x);
 
    printf(" Factorial of x is %ld", f);
    getch();
}
 
long int fact(int n)
{
    long int f=1;
    int i;
 
    for(i=1; i<=n; i++)
          f= f*i;
   
    return(f);
}
Example 2: Write a program to find the length of string using function.
#include<stdio.h>
#include<conio.h>
 
int slen(char str[]);
 
main()
{
    int len;
    char str[25];
 
    printf("Enter any string as input");
    scanf("%s", str);
 
    len = slen(str);
 
    printf("Length of string is %d", len);
    getch();   
}
 
int slen(int str[])
{
    int l;
   
    for(l=0; str[l] != '\0', l++);
 
    return(l);
}
 

Functions: RECURSIVE FUNCTION

RECURSIVE FUNCTION
Recursion in computer programming defines a function in terms of itself. One example application of recursion is in recursive descent parsers for programming languages. The great advantage of recursion is that an infinite set of possible sentences, designs, or other data can be defined, parsed, or produced by a finite computer program.
syntax:
void function()
{
   .. .. ..
   .. .. ..
   function();
   .. .. ..
   .. .. ..
}
Example 1: Write a program to find out the factorial of nth term using recursive function.
#include<stdio.h>
#include<conio.h>
 
long int fact(int n)
{
    long int f;
   
    if(n==1)
          return(1)
    else
          f = n * fact(n-1);
 
    return(f);
}
 
main()
{
    long int f;
    int x;
 
    printf("enter the value for x:")
    scanf("%d", &x);
 
    f = fact(x);
 
    printf(" Factorial of x is %ld", f);
    getch();
}

Example 2: Write a program to find out the sum of digit of an integer number using recursive function.
#include<stdio.h>
#include<conio.h>
 
int sumdigit(int n)
{
    int sum;
   
    if(n<10)
          return(n)
    else
          sum = (n%10) * sumdigit(n/10);
 
    return(sum);
}
main()
{
    int sum;
    int x;
 
    printf("enter the value for x:")
    scanf("%d", &x);
 
    sum = fact(x);
 
    printf(" sum of digit is %d", sum);
    getch();
}

Functions: Difference Between pass by value and pass by reference with example

 DIFFERENCE BETWEEN PASS BY VALUE AND PASS BY REFERENCE WITH EXAMPLE

Difference Between pass by value and pass by reference with example

Pass by value
Pass by reference
While calling by value, variable value is passed and its value is received by the arguments in the function
While calling by reference, variable's address is passed and the pointers as arguments in the function pointes to that variable's address.
Example:
#include<stdio.h>
#include<conio.h>

void swap(int x, int y)
{
int temp;
temp = x;
x = y;
y = temp;
}
main()
{
int x=5, y=10;
swap(x, y); //pass by value

printf("x=%d \n y=%d", x, y);

getch();
}

OUTPUT:
x=5
y=10
Example:
#include<stdio.h>
#include<conio.h>

void swap(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
main()
{
int x=5, y=10;
swap(&x, &y); //pass by reference

printf("x=%d \n y=%d", x, y);

getch();
}

OUTPUT:
x=10
y=5
In above example, from main() function value of x and y is sent to swap() function. The value swapped between x and y is within swap function only. So, when return back to main() function the value of x and y remains same. That is why value of x is displayed as 5 and y as 10.
Its like Ram and Laxman searing different room in Ram And Laxman story.
Here, from main() function x and y address (reference) is sent to swap() function. The value swapped between x and y is the value swapped for swap() and main() function because both's x and y points to same block of address. So, when return back to main() function the value of x and y is changed. That is why value of x is displayed as 10 and y as 5.
Its like Ram and Laxman searing same room in Ram And Laxman story.

DYNAMIC MEMORY ALLOCATION

DYNAMIC MEMORY ALLOCATION

Dynamic Memory Allocation

C language requires that the number of elements in an array should be specified at compile time. Our initial judgment of size, if it is wrong, may cause failure of the program or wastage of memory space. Many languages permit a programmer to specify an array?s size at run time. Such languages take the ability to calculate and assign, during execution, the memory space required by the variables in a program. The process of allocating memory at run time is known as dynamic memory allocation. The library functions used for allocating memory are :
Function - Task
malloc( ) -Allocates requested size of bytes and returns a pointer to the first byte of the allocated space
calloc() - Allocates space for an array of element, initializes them to zero and then returns a pointer to the memory

Memory Allocation Process

Let us first look at the memory allocation process associated with a C program. Fig. below shows the conceptual view of storage of a C program in memory.
  • Local Variable Stack
  • Free Memory Heap
  • Global Variables
  • C Program instructions
The program instructions and global and static variables are stored in a region known as permanent storage area and the local variables are stored in another area called stack. The memory space that is located between these two regions is available for dynamic allocation during execution of the program. The free memory region is called the heap. The size of the heap keeps changing when program is executed due to creation and death of variables that are local to functions and blocks. Therefore, it is possible to encounter memory "overflow" during dynamic allocation process. In such situations, the memory allocations functions mentioned above returns a NULL pointer.

Allocating a block of memory

A block of memory may be allocated using the function malloc. The malloc function reserves a block of memory of specified size and returns a pointer of type void. This means that we can assign it to any type of pointer. It takes the following form;
Ptr = ( Cast type * ) malloc ( byte size ) ;
Ptr is a pointer of type cast type. The malloc returns a pointer (of cast type) to an area of memory with size byte - size.
Example :
X = ( int * ) malloc ( 100 * size of ( int )) ;
On successful execution of this statement, a memory space equivalent to "100 times the size of an int" bytes is reserved and the address of the first byte of the memory allocated is assigned to the pointer X of type int.
Similarly, the statement
Cptr = ( char * ) malloc ( 10 ) ;
allocates 10 bytes of space for the pointer cptr of type char. This is illustrated below :
Cptr Address of first byte
10 bytes of Space
Remember, the malloc allocates a block of adjacent bytes. The allocation can fail if the space in the heap is not sufficient to satisfy the request. If it fails, it returns a NULL. We should therefore check whether the allocation is successful before using the memory pointer.

Allocating Multiple Blocks of Memory

Calloc is another memory allocation function that is normally used for requesting memory space at runtime for storing derived data types such as arrays and structures. While malloc allocates a single block of storage space, calloc allocates multiple blocks of storage, each of the same size, and then allocates all bytes to O. The general form of calloc is :
Ptr = (Cast type * ) Calloc ( n, elem-size );
The above statement allocates contiguous space for n blocks, each of size elem-size bytes. All bytes are initialized to zero and a pointer to the first byte of the allocated region is returned. If there is not enough space, a NULL pointer is returned.

INTRODUCTION OF POINTER

INTRODUCTION OF POINTER
Pointers are variables that hold addresses. They provide much power and utility for the programmer to access and manipulate data in ways not seen in some other languages.
A pointer is a special type of variable that contains a memory address rather than a data value. Just as data is modified when a normal variable is used, the value of the address stored in a pointer is modified as a pointer variable is manipulated.
Usually, the address stored in the pointer is the address of some other variable.
int *ptr;
ptr = &count /* Stores the address of count in ptr */   
To get the value that is stored at the memory location in the pointer it is necessary to dereference the pointer. Dereferencing is done with the unary operator "*".
int total;
total = *ptr;
    /* The value in the address stored in ptr is assigned to total */
 
Example 1: To take input and output for integer pointer variable
#include<string.h>   
#include<conio.h>    
main()
{
    int a;
    int *x;
 
    //taking input for general variable
    scanf("%d", &a);
    //taking input for printer
    scanf("%d", x);
 
    //displaying value for general variable
    printf("%d", a);
    //displaying value for pointer variable
    printf("%d", *x);
 
    getch();
}
Example 2: Program to convert uppercase string into lowercase using pointer
#include<string.h>   
#include<conio.h>    
main()
{
    char *str;
    int i;
 
    printf("Enter value for string:");
    scanf("%s", str);
   
    for(i=0; *(str+i)!='\0'; i++)
          if(*(str+i)>= 'A' && *(str+i)<= 'Z')
                *(str+i) = *(str+i) + 32;
 
    printf("converted into Lower case sting is %s ", str);
 
    getch();
}
 
Example 3: Write a program to input name of person. Reorder record in alphabetical order of name.
#include<stdio.h>
#include<string.h>   
#include<conio.h>
main()
{
    char *name[10], temp[25];
    int i, j;
 
    /*taking input for name and age*/
    for(i=0; i<10; i++)
          scanf("%s", name[i]);
 
    /*reordering record in order of name */
    for(i=0; i<10; i++)
          for(j=i+1; j<10; j++)
          {
                if(strcmp(name[i], name[j]) > 0)
                {
      //swapping name
      strcpy(temp, name[i]);
      strcpy(name[i], name[j]);
      strcpy(name[j], temp)  
                }    
          }
/*Displaying the reordered name */
    for(i=0; i<10; i++)
          printf("%s", name[i]);
 
    getch();
}

DIMENSION OF ARRAY

DIMENSION OF ARRAY

Important Note About Array Dimensions

The C language performs no error checking on array bounds. If you define an array with 50 elements and you attempt to access element 50 (the 51st element), or any out of bounds index, the compiler issues no warnings. It is the programmer's task alone to check that all attempts to access or write to arrays are done only at valid array indexes. Writing or reading past the end of arrays is a common programming bug and can be hard to isolate.
What will happen if a program accesses past the end of an array? Suppose a program has the following code.
int val;
int buffer[10];
val = buffer[10];
    /* Bug, remember that the indexes of buffer run from 0 to 9. */

What value will be in val? Whatever happens to be in memory at the location right after the end of the array. This value could be anything. Worse yet, the program may continue to run with the incorrect value and no warnings are issued.
What will happen if a program writes past the end of an array? Suppose a program has the following code.
int buffer[10];
buffer[593] = 99;
The value of 99 will be written at the memory location, buffer + 593. "buffer" is a pointer to the beginning of the array. buffer + 593 is pointer arithmetic for the address equal to the starting address of the array plus the size of 593 integers. The overwriting of the value at this memory location will change the value of whatever variable is stored there. Some other variable may have its value changed unintentionally. If the program writes unintentionally to memory locations that not valid, the program may crash.

Multidimensional Arrays

The C language also allows multidimensional arrays. They are defined as follows.
int matrix[3][3];

0
1
2
0
x1
x2
x3
1
x4
x5
x6
2
x7
x8
x9
To represent x5 it should be written as follows
matrix[1][1]
Similarly
x1 = matrix[0][0];
x2 = matrix[0][1];
x3 = matrix[0][2];
x4 = matrix[1][0];
and so on
Example:
int x[3][3];
x[0][0] = 5;          x[0][1] = 3;      x[0][2] = 9;
x[1][0] = 6;          x[1][1] = 22;     x[1][2] = 33;
x[2][0] = 32;         x[2][1] = 45;     x[2][2] = 7;

0
1
2
0
5
3
9
1
6
22
33
2
32
45
7
A common way to access the elements of multidimensional arrays is with nested for loops.
#define row 3
#define col 3

int i;
int j;
int x[row][col];

for (i = 0; i < row; i++)
{
    for (j = 0; j < col; j++)
    {
        values[i][j] = whatever;
     }
}
Example: Program to find the sum of matrix of 3x3
#include<stdio.h>
#include<conio.h>
main()
{
    int A[3][3], B[3][3], c[3][3];
    int i, j;
 
    /*taking input values in matrix A and matrix B */
    for(i=0; i<3; i++)
          for(j=1; j<3; j++)
                scanf("%d %d ", &A[i][j], &B[i][j]);
 
/*Adding matrix */
    for(i=0; i<3; i++)
          for(j=0; j<3; j++)
                C[i][j] = A[i][j] + B[i][j];
 
/*Displaying the result in screen */
    for(i=0; i<3; i++)
          for(j=0; j<3; j++)
                printf("%d", C[i][j]);
 
}
Example : Program to find the multiplication of matrix of 3x3
#include<stdio.h>
main()
{
    int A[3][3], B[3][3], c[3][3];
    int i, j, k, sum;
 
    /*taking input values in matrix A and matrix B */
    for(i=0; i<3; i++)
          for(j=0; j<3; j++)
                scanf("%d %d ", &A[i][j], &B[i][j]);
 
    /*multiplying matrix */
    for(i=0; i<3; i++)
          for(j=0; j<3; j++)
          {
                sum = 0;
                for(k=0; k<3; k++)
                      sum = sum + (A[i][k]*B[k][j]);
                C[i][j] = sum;
          }
 /*Displaying the result in screen */
    for(i=0; i<3; i++)
          for(j=0; j<3; j++)
                printf("%d", C[i][j]);
}
Example 3: Program to transpose matrix of 3x3
#include<stdio.h>
main()
{
    int A[3][3], B[3][3];
    int i, j;
 
    /*taking input values in matrix A and matrix B */
    for(i=0; i<3; i++)
          for(j=0; j<3; j++)
                scanf("%d %d ", &A[i][j]);
 
    /*transposing matrix */
    for(i=0; i<3; i++)
          for(j=0; j<3; j++)
                B[j][i] = A[i][j];
         
   /*Displaying the result in screen */
    for(i=0; i<3; i++)
          for(j=0; j<3; j++)
                printf("%d", B[i][j]);
}
Example 4: Write a program to input name and age of person. Reorder record in alphabetical order of name.
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
    char name[10][25], temp[25];
    int i, j, age[10], temp1;
 
    /*taking input for name and age*/
    for(i=0; i<10; i++)
          scanf("%s %d ",name[i], &age[i]);
 
    /*reordering record in order of name */
    for(i=0; i<10; i++)
          for(j=i+1; j<10; j++)
          {
            if(strcmp(name[i], name[j]) > 0)
                {
      //swapping name
      strcpy(temp, name[i]);
      strcpy(name[i], name[j]);
      strcpy(name[j], temp)
   
//swapping age
      temp1 = age[i];
      age[i] = age[j];
      age[j] = temp1;
                }    
          }
/*Displaying the reordered name and age*/
    for(i=0; i<10; i++)
          printf("%s %d", name[i], age[i]);
     getch();
}

Array And Strings :STRING (CHARACTER ARRAY)

STRING (CHARACTER ARRAY)

Character Arrays [String]

Strings are stored in C as character arrays terminated by the null character, '\0'.
Declaration of string if done as follows
char str[25];
char str1[30] = "MY STUDYROOM";
M
Y

S
T
U
D
Y
R
O
O
M
\0
............

0
1
2
3
4
5
6
7
8
9
10
11
12
............
29
Assigning a character literal to an array is done as follows.
char str1[] = "MY STUDYROOM";
char str2[] = "Nepal"
The compiler automatically sizes the arrays correctly. For this example, str1 is of length 16, str2 is of length 5.
Example 1: Program to find out the length of string
#include<stdio.h>
#include<conio.h>
main()
{
int len;
char str[25];

printf("Enter any string");
scanf("%s", str);

/*loop has semicolon(;) at the end coz loop doesn't contain any statement below it*/
for(len=0; str[len]!='\0' ; len++);

printf("length of string is %d", len);

getch();
}
Example: Write a program to reverse the string
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
    int i, j, len;
    char str[25], rstr[25];
   
    printf("Enter any string");
    scanf("%s", str);
 
    //finding out the length of string
    len = strlen(str);
 
//reversing the string
for(i=0, j=len-1; j>=0; j--, i++)
          rstr[i] = rstr[j];
 
printf("Reverse sting is %s", rstr);
 
getch();
}
Example : Write a program to find out no. of vowel, consonant, digit, white space and other character in a sentence provided by an user.
#include<stdio.h>
#include<conio.h>
main()
{
    int i, v=0, c=0, d=0, ws=0, oth=0;
    char str[25];
   
    printf("Enter any string");
    scanf("%s", str);
 
    for(i=0; str[i]!='\0' ; i++)
{
if(str[i]=='a'||str[i]=='e'||str[i]=='i'||str[i]=='o'||str[i]=='u')
                v = v + 1;
else
                if(str[i]>='a' && str[i]<='z')
                      c = c + 1;
                else
                      if(str[i]>='0' && str[i]<='9')
                            d = d + 1;
                      else
                            if(str[i]==' ' )
                                  ws = ws + 1;
                            else
                                  oth = oth + 1;
}
  printf(" No. of vowel=%d, Consent=%d, Digit=%d, White space=%d and Other=%d", v, c, d, ws, oth);
  getch();
}

Library Functions for String Manipulation

To use any of these functions in your code, the header file "strings.h" must be included.
strlen():
strlen finds the length of string.
Syntax:
int strlen(char* )
Example:
char str[]="MY STYDYROOM";
int len;
len=strlen(str);
output:
len=12

strcpy():
strcpy copies a string, including the null character terminator from the source string to the destination.
Syntax:
Char* strcpy(char* source_string, char* destination_string)
Example:
char dst[25], src[]="MY STYDYROOM";
strcpy(dst, src);
output:
dst = "MY STYDYROOM"
strcat():
This function appends a source string to the end of a destination string.
Example:
char dst[25]="MY ";
char src[ ] = "STUDYROOM";
strcat(dst, src);
Output:
dst = "MY STYDYROOM"
strcmp
This function compares two strings.
  • If the first string is greater than the second, it returns a number greater than zero.
  • If the second string is greater, it returns a number less than zero.
  • If the strings are equal, it returns 0.
int x;
char str1[25], str2[25];
x = strcmp(str1, str2);
o   x > 0 - if the str1 is greater than str2. [i.e. str1="nepal" and str2="japan" ]
o   x< 0  - if the str1 is less than str2. [i.e. str1="japan" and str2="nepal"]
o   x==0 - if str1 is equal to str2. [i.e. str1="nepal" and str2="nepal" ]

Example: Write a program to find out the string is palindrome or nor.
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
    char str[25], str1[25];
   
    printf("Enter any string");
    scanf("%s", str);
   
    str1 = strrev(str);
 
    if(str==str1)
          printf("Entered string is PALAINDROME");
    else
          printf("Entered string is NOT PALAINDROME");
   getch();
}

Array And Strings : Introduction to Arrays

INTRODUCTION OF ARRAY

Introduction to Arrays

Arrays are a data structure that is used to store a group of objects of the same type sequentially in memory. All the elements of an array must be the same data type.
An array is a collective name given to a group of similar quantities. These similar quantities could be percentage marks of 100 students, number of chairs in home, or salaries of 300 employees or ages of 25 students. Thus an array is a collection of similar elements. These similar elements could be all integers or all floats or all characters etc. Usually, the array of characters is called a "string", where as an array of integers or floats is called simply an array. All elements of any given array must be of the same type i.e we can't have an array of 10 numbers, of which 5 are ints and 5 are floats.
Some important points about Array:
  • First element of an array has zero index
  • All the data items in array are always stored in consecutive memory locations.
  • Arrays are always store under a common heading or a variable name
  • An array either be an integer, character, or floating point data item but initialized only on declaration time not afterwards.
  • An array can always be read or write through loops
Syntax:
datatype arrayName[size];
Examples:
int ID[30];
/* Could be used to store the ID numbers of students in a class */
 
float temperatures[31];
/* Could be used to store the daily temperatures in a month */
 
char name[20];
/* Could be used to store a character string. Character strings in C are terminated by the null character, '\0'. This will be discussed later in the this lesson. */

Advantage and Disadvantage of Array

Advantages:

1.       You can use one name for similar objects and save then with the same name but different indexes.
2.       Arrays are very useful when you are working with sequences of the same kind of data (similar to the first point but has a different meaning).
3.       Arrays use reference type and so.

Disadvantages:

1.       Sometimes it's not easy to operate with many index arrays.
2.       C environment doesn't have checking mechanism for array sizes.
3.       An array uses reference mechanism to work with memory which can cause unstable behavior of operating system (unless special methods were created to prevent it) and often even "blue screen" and so on.

Using Arrays

when we declare
int x[50];










.......

0
1
2
3
4
5
6
7
8
....... .....  49
if we assign as follows
x[7]=57;
then our block look as follows







57

.......

0
1
2
3
4
5
6
7
8
.......      49
Example 1: Here is a sample program that calculates and stores the squares from 1 to 100.
#include<stdio.h>
#include<conio.h>
void main()
{
    int x[100];
    int i, k;
   
    /* Calculate the squares */
    for (i = 0; i < 100; i++)
    {
k= i + 1;
x[i] = k*k;
printf("The square of %d is %d\n", k, x[i]);
      }
}
Example 2: Write a program to find out the greatest and smallest number entered in array.
#include<stdio.h>
#include<conio.h>

main()
{
    int x[100];
    int i, lrg, sml;
 
    printf("Enter 100 integer number in an array");
    for(i=0; i<100; i++)
          scanf("%d", &x[i]);
 
    //initially assigning the value in lrg and sml variables
    lrg = x[0];
    sml = x[0];
 
    //process of find out the largest and smallest number in an array
    for(i=0; i<100; i++)
    {
if(lrg < x[i])   
                lrg=x[i];
if(sml < x[i])
                sml=x[i];
    }
    printf("Smallest = %d and Largest = %d", sml, lrg);
     getch() ;
}
Example 3: Write a program asking any 10 numbers from the user. Sort them in ascending order and display them.
#include<stdio.h>
#include<conio.h>
void main()
{
    int x[10];
    int i, j, temp;
 
    printf("Enter 10 numbers in array");
    for(i=0; i<10; i++)
    scanf("%d",&x[i]);
    //reordering numbers in ascending order
    for(i=0; i<10; i++)
          for(j=i+1; j<10; j++)
          {
                if(x[i] > x[j])// for descending order just change > sign to <
                {
                      //swapping
                      temp = x[i];
                      x[i] = x[j];
                      x[j] = temp;
                }
          }
    //displaying the reordered numbers
    for(i=0; i<10; i++)
          printf("%d", x[i]);
 
    getch();
}

LOOP

LOOP
Loops can be created to execute a block of code for a fixed number of times. Alternatively, loops can be created to repetitively execute a block of code until a boolean condition changes state. For instance, the loop may continue until a condition changes from false to true, or from true to false. In this case, the block of code being executed must update the condition being tested in order for the loop to terminate at some point. If the test condition is not modified somehow within the loop, the loop will never terminate. This creates a programming bug known as an infinite loop.

While Loop:

Syntex:
while (condition)
{
    block of codes
}
Example: Here is a simple example of the use of while. This program counts from 1 to 100.
#include <stdio.h>

main()
{
    int count = 1;

    while (count <= 100)
    {
        printf("%d\n",count);
        count += 1; /* Shorthand for count = count + 1 */
    }
}

Do while Loop:

Syntax:
do {
    block of code
} while (condition is satisfied)
Example: Here is an example of the use of a do loop. The following program is a game that allows a user to guess a number between 1 and 100. A "do" loop is appropriate since we know that winning the game always requires at least one guess.
#include<stdio.h>
main()
{

    int number = 44;
    int guess;

    printf("Guess a number between 1 and 100\n");
    do {
        printf("Enter your guess: ");
        scanf("%d",&guess);

        if (guess > number) {
            printf("Too high\n");
        }
        if (guess < number) {
            printf("Too low\n");
        }
    } while(guess != number);

    printf("You win. The answer is %d", number);
}

For Loop:

Syntax:
for (initializations ;test conditions ;actions)
{
    block of code
}
Example 1: Displaying even numbers form 1 to 100
#include<stdio.h>
#include<conio.h>
 
main()
{
    int ctr;
 
    for (ctr = 1; ctr <= 10; ctr=ctr+2)
        printf("%d\n",ctr);
    getch();
}

Nested Loop:

Loop containing another loop with in it is what we call nested loop
Syntax:
for (initializations ;test conditions ;actions)
{
for (initializations ;test conditions ;actions)
{
block of codes;
}
    block of code
}
Example 1: Display the following output:
1
1      2
1      2        3
1      2        3        4
1      2        3        4      5
#include<stdio.h>
main()
{
    int i, j;
    for(i = 1; i <= 5; i++)
    {
           for(j=1; j<=i; j++)
              printf("%d ", j);
          printf("\n");
    }
     getch();
}

IF-ELSE STATEMENT

IF-ELSE STATEMENT

If Statements

The if statement is used to conditionally execute a block of code based on whether a test condition is true. If the condition is true the block of code is executed, otherwise it is skipped.
Syntax:
if(condition)
    {
          statement1;
          statement1;
          ...........................1;
    }
Example:
#include <stdio.h>

main()
{
    int number = 5;
    int guess;

    printf("I am thinking of a number between 1 and 10\n");
    printf("Enter your guess, please \n");
    scanf("%d",&guess);

    if (guess == number)
    {
        printf("Incredible, you are correct\n");
    }
}

if-else Statement

The else statement provides a way to execute one block of code if a condition is true, another if it is false.
Syntax:
if(condition)
    {
          statement1;
          statement1;
          ...........................1;
    }
else
    {
          statement1;
          statement1;
          ...........................1;
    }
Program: WAP a program to find out the entered number is even or odd.
#include<stdio.h>
#include<conio.h>
 
main()
{
    int x;
 
    printf("Enter any number");
    scanf("%d", &x);
   
    if(x%2==0
          printf("Even No.";
    else
          printf("Odd No.");
    getch();
}

Nested if-else Statement

The else statement provides a way to execute one block of code if a condition is true, another if it is false.
Syntax:
if(condition)
    {
          statement1;
          statement1;
          ...........................1;
    }
else if(condition)
    {
          statement1;
          statement1;
          ...........................1;
    }
Example : finding out the greatest number among three numbers

#include<stdio.h>
#include<conio.h>
 
void main()
{
    int A,B,C;
 
    printf("Enter Three No.:");
    scanf("%d %d %d",&A,&B,&C);
 
    if(A>B)
    {
          if(A>C)
                printf("A is the Greatest");
          else
                printf("C is the Greatest");
    }
    else
    {
          if(B>C)
                printf("B is the Greatest");
          else
                printf("C is the Greatest");
    }
    getch();
}