Showing posts with label C lecture. Show all posts
Showing posts with label C lecture. Show all posts

Friday, October 18, 2019

Function

FUNCTION

C enables programmer to break up a program into segments commonly known as functions, each of which can be written more or less independently of the others. Every function in the program is supposed to perform a well-defined task. Therefore, program code of one function is completely insulated from the other function.
Every function interfaces to the outside world in terms of how information is transferred to it and how result generated by the function are transmitted back from it. This interface is basically specified by function name.
For example, 
main( )
{
...............
................
function 1( );
...............
return(0);
}
function 1( )
statement block;
}

In this example, the main () function call the function named func1(). Therefore, main() is the calling function and func1() is called function. The moment the compiler encounters the function call,instead of executing the next statement the control jumps to the statement that are part of the called function. After the called function is executed, the control is returned back to the calling program.
It is not necessary that the main() can call only one function, it can call as many function as it wants and as many time as it wants. Another point is that it is not only the main () that can call other functions. A function can call any other function.
For example,
main( )
{..........
..........
Func1( );
.........
return();
}
Func1( )
{.......
.......
Func2();
.......
........
return( );
}
Func2( )
{
..........
..........
}

Therefore,function is self contained block of statements which can execute and perform the specific task.
Following are the advantages of function approach : 
1- Increases the efficiency (time & space) of a program.
2- Normally function approach decreasing the complexity of the program and increases the understandability.
3- It is more easy to debug the program when we are using function approach.

WHY FUNCTIONS ARE NEEDED?

Dividing the program into to separate well defined function facilitate each function to written and tested separately. This simplifies the process of getting the total program to work.
Understanding,coding and multiple separate function are easier than doing the same for one huge function.
 If a big problem has to be developed without the use of any function other than the main() function ,then there will be countless lines in the main function and maintaining this program will be very difficult.
When a big problem is broken into comparatively smaller function, then different  programmers working on that project can divide the workload by writing different functions.
Like C libraries,programs can also write their functions and use them from different points in the main program or any other program that need its functionalities.

DEFINITION OF FUNCTION

Before using the function,the compiler must know about the number of parameters and type of parameter that the function expect to receive and the data type of the value that it will return to the calling program.
Hence, "function declaration" is a declaration statement that identifies a function with its name,a list of argument that it accept and the type of data it return.
The general format of declaring a function that accepts some argument and returns some value as a result can be given as :

return _datatype    function_name (data_type var.1,data_type var.2,...);

Here, function name is a valid name for the function. The function name is used to call it for execution in a program. Every function must have a different name that indicates a particular job that the function does.
return data_type specifies the data type of the value that will be returned to the calling function as a result of processing performed by the called function.

data_type variable 1, data_type  variable 2,...  is a list of variable of a specified data types. These variables are passed from calling function to call function. They are also known as parameter or argument that the call function accept to perform its task.
For example, 
int func (int, char, float);

1. After declaration of every function there should be a semicolon.
2. The function may be declared globally so that the declared function can be called from any point in the program.
3. A function cannot be declared within the body of another function.
4. If the function declaration does not specify any return type then by default, the function return an integer type.
5. A function having void as it return type cannot return any value.
6. Function having void as a parameter list cannot accept any value.

FUNCTION DEFINITION

main() function is defined the space is allocated for that function in the memory. A function comprises of two part:
1. Function header
2. Function body

The sentence of a function definition can be given as:
return_data_type  function_name (data_type var 1,data_type var 2,...)
{.........
............
Statement;
.........
return (statement) ;
}

Hence,  the function definition consist of a function header that indicates the function, followed by the body of the function containing the executable code for that function.
The number of argument and the order of argument in the function header must be same.
In the above syntax statement,
return_data_type function_name (data_type var 1,data_type var 2,...)

is the function header and the rest of the portion comprising of program statement within curly braces is the function body which contains the code to perform the specific task.
The function header is same as that of a function declaration. The only difference between the two is that the function header is not followed by a semicolon.

FUNCTION CALL

The function call statement invokes the function. When a function is invoked the compiler jumps to the call function to execute the statement that are the part of that function. Once  the called function is executed, the program control passes back to the calling function.
Function call statement has the following syntax:

function_name (variable 1,variable 2,...);

Function definition are often placed in a separate header file which can be included in other c source file that wish to use the function.
Function name and the number and the type of argument in the function call must be same as that given in the function declaration and function header of the function definition.
#). If by mistake the parameter passed to a function are more or less than what is specified to accept then the extra argument will be discarded and the unmatched argument will be initialised to some garbage value.
#). The parameter list must be separated with commas.

RETURN STATEMENT

The return statement is used to terminate the execution of a function and return to the calling function. When the return statement is encountered, the program execution resumes in the calling function at the point immediately following the function call.
Return statement may or may not return a value to the calling function. The syntax statement can be given as:
return (expression) ;
The value of the expression if present is returned to the calling function. However, in case, expression is omitted, the return value of the function is undefined.
A function that has a void as it return value they cannot return any value to the calling function.
An error is generated when the function does not return data of the specified type.

USING VARIABLE NUMBER OF ARGUMENT

Some function have a variable number of arguments and data types that cannot be known at the compile time.
Typical examples of such function include the printf ( ) and scanf ( )function. ANSI C offers a symbol called ellipses to handle such functions. The ellipses consists of three periods (...). It can be used as-
int func(char ch,...);
The function declaration statement given above states that function is a function that has an arbitrary number and type of argument. However, one must ensure that both the function declaration and function definition should use the ellipse symbol.

PASSING PARAMETER TO THE FUNCTION

When a function is called, the calling function may have to pass some value to the called function. 
Basically there are two ways in which argument of parameters can be passed to the called function. They include-
1. CALL BY VALUE

call by value in which values of the variable are passed by the calling function to the called  function.  The program that we have written so far all call the function using call by value method of passing parameter.
In call by value method, the call function creates new variable to store the value of the argument passed to it. Therefore, the called function uses a a copy of the actual parameter to perform it's intended task.
Value of the variable in the calling function remain unaffected when the argument passed using call by value technique.
Therefore, call by value method of passing argument to a function must be used only in two cases:

  1. When the call function does not modify the value of the actual parameter.
  2. When we want that the called function should only temporarily modify the value of the variable and not permanently so all the called function may modify the value of the variables, but this variable remain unchanged in the calling program.

2. CALL BY REFERENCE

Call by reference in which address of the variable are passed by the calling function to the called function.
In call by reference we declare the function parameter as reference rather than the normal variable. When this is done any changes made by the function to the argument it receives are visible to the calling program.
To indicate  that an argument is a password using call by reference an ampersand (&)sign is  placed after the type in the parameter list. This way, changes made to the parameter in the called function body will then be reflected in its value in the calling program.

ADVANTAGES

The advantages of using call by reference technique of passing argument are as follows:

  1. Since argument are not copied into new variables, it provides greater time and space efficiency.
  2. The function can change the values of the argument and the change is reflected in the caller.
  3. A function can return  only one value. In case we need to return multiple values, pass those arguments by reference so that modified values are visible in the calling function.

DISADVANTAGES

When an argument is a passed using call by address, it become difficult to tell whether that argument is meant for input, output or both.

Thursday, May 30, 2019

C Programming : program to find sum and product of two numbers;

/* Program to find the sum and product of two numbers */

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,sum=0,product=0;
printf("\n Enter the value of a and b );
scanf("%d%d",&a,&b);
sum=a+b;
product=a*b;
printf("\n The sum of a and b is = %d",sum);
printf("\n The product of a and b is = %d",product);
getch( );
}

Output

Enter the value of two numbers     60  

 3

The sum of a and b is 63
The product of a and b is 180

In this program we are adding two numbers and multiplying two numbers with the help of programming language.
First we are declaring the two variable i.e., a and b and the variable sum and product with zero.
Then we are entering the message to enter two numbers. Then the condition of sum and product are written so that it can execute the program.
Lastly the answers of the above mentioned question are printed.
Finally it will look like as shown below-


 And the outputs are as follows:





Tuesday, May 28, 2019

C Programming : Program to swap two numbers

/* Program to swap two numbers */

#include<stdio.h>
#include<conio.h>
void main( )
{
float A,B;
printf("\n Enter the value of A  ");
scanf("%f ",&A);
printf("\n Enter the value of B  ");
scanf("%f ",&B);
printf("\n  Numbers before swapping are :- \n A=%f\nB=%f",A,B); 
A=A+B;
B=A-B;
A=A-B;
printf("\n Numbers after swapping are :-");
printf("\n A=%f \nB=%f",A,B);
getch();
}

Output

Enter the value of
30.0

Enter the value of B
90.0
Numbers before swapping are :-
A=30.000000
B=90.000000
Numbers after swapping are:-
A=90.000000
B=30.000000
 
Now the demonstration of the output is shown below:


C Programming : Program to check whether a given string is palindrome or not.

/* Program to check whether a given string is palindrome or not without using string function */

#include<stdio.h>                                                 // header file
#include<conio.h>                                                 // header file
#include<string.h>                                                // header file
int main( )
{
char name[50];                                       // variable declaration
int i,length,len;                                       // variable declaration
printf("\n Enter the string ");
gets(name);
len=strlen(name); 
                            // calculating the length of the  given string
for(i=0;i<len/2;i++)                                    // looping statement
{
if(name[i]!=name[ len-1-i ])             // conditional statement
{
printf("\n Not a palindrome ");                // printing message
break;
}}
if( i==len/2)                                         // conditional statement
printf("\n It is Palindrome ");                   // printing message
getch( );
}

Output

Enter the string
mayanmar
Not a palindrome


Enter the string
malymylam
 It is Palindrome
The Output will be shown as given below:



In this program we are checking the given string is palindrome or not without using the strcmp( ), strcpy( ),and strrev( ) function.
Firstly, we use the header file which replaces the necessary files into the source code file.
Then we declare the variable and printing the message to enter the string.
Then we calculate the length of the given string and then conditional statement is used. If the condition is true then the first message is printed and if the conditional statement is false then the control statement executes the  second conditional statement. The output is shown above:
In the first statement , the entered statement is not a palindrome and  in the second statement, the entered statement is palindrome.

Sunday, May 26, 2019

C language : Array


Array :     An array is a collection of similar type of data element. It can store only those elements which are of same datatype .
   for eg.             int n[10];

Characteristic of an array:

1. This is homogeneous collection of data elements.

2. Sometimes it is called sub-scripted variable (Index/dimension).

3. When we are assigning array, its type and dimension must be declared.

4. Arrays always stores the elements in contiguous memory location.

5. Whatever, size of the array by default may be it starts to store the element from the zero (0) location location will be one less than the  size of the array.

Declaration of an array:
Every variable must be declared before it is used. The same concept is true in case of array variable also. The array must be declared before its use. Declaring an array means specifying three things:
1. Data type- What kind of value it can store.
  for eg. int, char, float , double.
2. Name to identify the array.
3. Size- The maximum number of values that the array can hold.

Syntax of array:- datatype name[size];
                             eg. int a[10];

Accessing elements of the array:
For accessing an individual elements of array, the array subscript must be used.
 For eg.
 To access the fourth element of the array, we must write arr[3]; . The subscript/ index must be an integral value or an expression that evaluates to an integral value . To access all the elements of the array , we must use a loop. There is no single statement that can do the work i.e., we can access all the elements of the array by varying the value of the subscript into the array. But note that the value of the subscript must be an integral for an expression that evaluates to an integral value. To process all elements of the array we will use a loop as shown:
int i,a[10];
printf (" enter the element");
for(i=0;i<=9;i++)
scanf ("%d",&a[i]);

Calculating the address of array element
An array store all its data element in contiguous memory location.So storing just the base address, i.e, the address of the first element in the array is sufficient. The  address of other data element can simply be calculated using the base address. The formula for doing this calculation is:
Address of data element, A[K]=BA(A)+W(K-lower_bound)
Here A is the array, K is the index of the element for which we have to calculate the address, BA is the base address of the array A, w is the word size of one element in memory ( for example, size of int is 2) and lower bound is the index of the first element in the array.
for eg.
Q.  calculate the address of marks [4] if base address = 1000 given an array int marks[] = {99,67,52,92,71,63}
A.                       99            67            52               92           71          63
       marks        [0]           [1]           [2]            [3]           [4]          [5]
                        1000        1002        1004       1006        1008      1010
we know that storing an integer value we require 2 bytes therefore here,word size is 2 bytes.
marks[4] =1000+2(4-0)
                 = 1000+2*4
                 =1000+8
                 =1008

Storing values in array:
When we declare and define an array, we are just allocating space for the element; no values are stored in the array. To store values in the array there are three ways-
First to initialize the array element; second to input value for every individual element; third to assign values to the element.

Initialization of array:
Elements of the array can also be initialized at the time of declaration as in the case of every other variable.When an array is initialized we need to provide a value for every element in the array. Array are initialized by writing,

data_type array_name[size] = {list of values };
The values are written with curly braces and every values is separated by a comma.
for eg.          int marks[5] = {90,43,65,66,85};

 While initializing the array at the time of declaration, the programmer may omit to mention the size of the array.
 for eg.    int marks[ ] = {56,47,77,92,18};
The above statement is absolutely true, Here the compiler will allocate space for all initialized elements.
If the number of values provided is less than the number of element in the array, then  an unassigned elements are filled with zeros.

for eg.      int marks[5] = {1,2,3,4,5};

                  1      2        3         4           5
                 [0]    [1]     [2]     [3]         [4]

                 int marks[5] = {1,2};
                
                 1       2         0        0          0
                 [0]    [1]     [2]      [3]       [4]

                 int marks[ ] = {1,2,3,4,5};
             
                  1         2       3         4         5
                 [0]       [1]    [2]      [3]       [4]
             
                 int marks[5] = {0};

                 0       0          0           0        0
                 [0]    [1]        [2]       [3]      [4]

If we have more initializers than the declared size of the array, then a compile time error will be generated.
 for eg.   The following statement will result in error:
                    int marks[3] = {1,2,3,4,5};

Calculating the length of array:
Length of an array is given by the number of elements stored in it. The general formula to calculate the length of the array is -
Length = upper bound- lower bound + 1
where upper bound is the index of the last element and lower bound is the index of the first element in the array. Usually lower bound is zero but this is not a compulsion as we can have an array whose index start from non-zero value.

for eg.    int A[2] = {0,1};
           Here, lower bound = 0 and upper bound  = 1
           By formula, it's length is UB -LB +1
                                                 = 0+1+1=> 2
                   Therefore, length is 2


  ONE DIMENSIONAL ARRAY FOR INTER FUNCTION COMMUNICATION


PASSING INDIVIDUAL ELEMENTS:    The individual elements of an array can be passed to a function either by passing their address or their data values.

 PASSING DATA VALUES:      The individual elements can be passed in the same manner as we  pass variables of any other data type condition is just that the data type of the element must match the type of the function parameter.
for eg.             main()
                        {
                           int arr[5] = {1,2,3,4,5};
                               func(arr[3]);
                           }
                          void func(int num)
                         {
                         printf("%d",num);
                       }

In the above example only one element of the array is passed to the calling function. This is done by using the index expression.
So arr[3] ; actually evaluates to single integer value . The called function hardly bothers weather a normal integer variable is passed to it or an array value is passed.

PASSING ADDRESS:  Like a ordinary variable we can pass the address of an individual element by preceding the address operator (&) to the element index reference. Therefore to pass the address of the fourth element of the array to the called function we will write &arr[3].
However, in the called function, the value of the array element must be accessed using the indirection operator (*).          
for eg             main()
                             int arr[3] = {0,1,2};
                          func(&arr[2]);
}
                           void func(int *num)
{
                             printf("%d",num);
}

PASSING THE ENTIRE ARRAY:     The array name refers to the first byte of the array in the memory. The address of the rest of the element in the array can be calculated using the array name      and the index value of the element Therefore, when we need to pass an entire array to a function we can simply pass the name of the array.
for eg.                               main ()
                                    {
                                      int arr[5] = {1,2,3,4,5};
                                         func(arr);
                                      }
                                        void func(int arr[5])
                                   {
                                             int i;
                                             for(i=0;i<=4;i++)
                                      printf("\n   %d",arr[i]);
                                         }

TWO DIMENSIONAL ARRAY: One dimensional array is organized linearly and only in one direction but at times, we need to store data in the form of matrics or tables.
Two dimensional array specified using two subscript or index one subscript denotes row and another subscripts denotes column .
                                    
DECLARATION OF A TWO DIMENSIONAL ARRAYS
Similar to one dimensional array, two dimensional array must be declared before being used. The declaration statement tells the compiler the name of the array, the data type of each element in the array and the size of each dimension. A two dimensional array is declared as:
data_type  array_name [row_size][column];
Therefore, a two dimensional array mXn array is an array that contain mXn data elements and each element is accessed using two subscript i and j where i is less than or equal to m and j is less than or equal to n.
For example.
If you want to store the marks obtained by 3 student in five different subjects then we can declare two dimensional array as-
int marks[3][5];



INITIALIZATION OF TWO DIMENSIONAL ARRAY
Two dimensional array is initialized in the same way as one dimensional array
for eg. 
   int marks[2][3] ={90,87,76,34,72,66};
The initialization of a two dimensional array is done row by row.The above statement can also be written as as-
      int marks[2][3] = {{90,87,76},{34,72,66}};
The given two dimensional array has a 2 row and 3 columns. Here the element in the first row are initialized first and then the elements of a second row are initialized.
Therefore,
   marks [0][0] = 90                   marks [0][1] = 87             marks [0][2] = 76
   marks [ 1][0] = 34                   marks [1][1] = 72            marks [1][2] = 66

In the case of one dimensional array,if the size of the array is completely initialized ,we may omit the size of the array.Same concept can be applied to a two dimensional array except that only the size of the first dimensional  can be omitted. Therefore, the declaration statement given below is valid
for eg.  int marks[ ][3]={{90,87,76},{34,72,66}};

ACCESSING THE ELEMENT
The element in a multidimensional array are stored in contiguous memory allocation. While accessing the elements, remember that the last subscript varies  most rapidly where the first varies least rapidly.
   In case of one dimensional array be used, we used a single for loop to vary the index i in every pass so that all the elements could be scanned. Similarly, since a two-dimensional array contain two subscript, we will use two for loop to scan the element.

TWO DIMENSIONAL ARRAY FOR INTER FUNCTION COMMUNICATION



There are three ways of passing parts of the two-dimensional array to the function.
First we can pass individual element of the array as in case of one dimensional array.
Second we can pass a single row of the two dimensional array. This is equivalent to passing the entire one dimensional array to a function.
Third we can pass the entire two dimensional to the function.

PASSING A ROW
A row of two dimensional array can be passed by indexing the array name with row number. When we send a single row of the two-dimensional array, then the called function receives a one-dimensional array.
For example
main()
{
int arr[2][3]= {{1,2,3},{4,5,6}};
func(arr[1]);
}
void func(int arr[ ])
{
int i;
for (i=0;i<5;i++)
printf("\n %d",arr[i]*10);
}

PASSING AND ENTIRE 2D ARRAY
To pass a 2D array to a function, we use the array name as actual parameter. However, the parameter in the called function must indicate that the array has two dimensions.

MULTIDIMENSIONAL ARRAY
Multidimensional arrays in simple terms is an array of arrays. Like we have one index in One dimension, two indices in two dimension, in the same way we have n number of indices in a n dimensional array.
      Multidimensional array contains as many indices as needed and the requirement of the memory increases with the number of indices used. However, practically, we will hardly used more than three indices in any program.
For example    int arr[2][2][2];


C programming : Program to reverse a number

/* Program to find a reverse of a number */

#include<stdio.h>
#include<conio.h>
void main( )
{
int a,b,c,n,rev;
printf("\n Enter the value of n ");
scanf("%d",&n);
a=n%10;
b=(n/10)%10;
c=(n/10)/10;
rev=a*100+b*10+c*1;
printf("\n The reverse of a given number is %d",rev);
getch();
}

Output 

Enter the value of n
123
The reverse of a given number is321
 
The output will be seen as shown below:
 

C programming : Program to find the sum of digits of three digit numbers.

/* Program to find the sum of the digits of a three digit numbers */

#include<stdio.h>
#include<conio.h>
void main( )
{
int n,a,b,c,sum=0;
printf("\n Enter the value of n ");
scanf("%d",&n);
a=n%10;
b=(n/10)%10;
c=(n/10)/10;
sum=a+b+c;
printf("\n Sum of the digits of three digit numbers is %d",sum);
getch();
}

Output

Enter the value of n
678
Sum of the digits of three digit numbers is 21
 

 

C programming : Program to find the average of natural numbers

/* Program to find the average of natural numbers */

#include<stdio.h>
#include<conio.h>
void main()
{
int i,n,sum=0;
float avg;
printf("\n Enter the value of n :");
scanf("%d",&n);
for (i=1;i<=n;i++)
sum=sum+i;
avg=sum/n;
printf("\n The average of natural numbers is %f",avg);
getch();
}

Output 

Enter the value of n
10
The average of natural numbers is 5.0000
 
Now the output will be seen as:
 


Friday, May 10, 2019

C programming : Program to find the sum of natural numbers


/* Program to find the sum of natural numbers in C programming langu */

#include<stdio.h>
#include<conio.h>
void main ()
{
int i,n,sum=0;
clrscr();
printf ("\n Enter the value of n ");
scanf ("%d",&n);
for (i=1;i<=n;i++)
{
sum=sum+i;
}
printf ("\n The sum of n natural numbers is %d",sum);
getch();
}

Output

Enter the value of n
10
The sum of n natural numbers is 55
 
Now the output will be seen as:

 
 

C programming : Program to find the sum and product of two numbers


/* Program to find the sum and product of two numbers */

#include<stdio.h>
#include<conio.h>
void main ()
{
int a,b,sum=0, product=0;
clrscr();
printf ("\n Enter the value of a and b ");
scanf ("%d %d",&a,&b);
sum=a+b;
printf ("\n The sum of two numbers is %d",sum);
product=a*b;
printf (" \n The product of two numbers is=%d",product );
getch();
}

Output:

Enter the value of a and b
12
6
The sum of two numbers is 18
The product of two numbers is72
 
Now the output will be seen as given below:


C language : Iterative statement

                      Iterative statement in C language          

  Iterative statement:-  Iterative statements are used to repeat the execution of a list of statement, depending on the value of an integer expression.C language support three types of iterative statement. It is also known as the looping statement. They are-

1. While loop
2 .Do while loop
3. For loop

1 .while loop- 
 The while loop provides a mechanism to repeat one or more statement while a particular condition is true. The syntax of while loop are given below:

statement X;
while(condition)
{
statement block;
}
statement Y;

In the while loop, the condition is tested before any of the statement in the statement block is executed. If the condition is true, only then the statement will be executed otherwise if the condition is false, the control will jump to statement Y, which is the immediate statement  outside the while loop block.

For eg.            /*print first ten numbers */

#include<stdio.h>
#include<conio.h>
void main()
{
int i=0;
while(i<=0)
{
printf("%d",i);
i=i+1;
}
getch();
}

2. do-while loop-
The do-while loop is similar to the while loop. The only difference is that in a do-while loop, the test condition is tested at the end of the loop. Now that the test condition is tested at the end, this clearly means that the body of the loop gets executed at least one time (even if the condition is false ). The syntax of a do-while loop is shown in below: 

statement X;
do
{
statement block;
}
while (condition);
statement Y;

The main disadvantage of using a do-while loop is that it always execute at least once, even if the user enter some invalid data, the loop will execute.
However, the do-while loop are widely used to print a list of option for a menu driven program.

For eg.            /* program for sum and average of first n natural numbers. */

#include<stdio.h>
#include<conio.h>
void main()
{
int n,i=0,sum=0;
float avg=0.0;
printf("Enter the value of n ");
scanf("%d",&n);
do
{
sum=sum+i;
i=i+1;
}
while(i<=n);
avg=sum/n;
printf("\n The sum of first n natural numbers is %d ",sum);
printf("\n The average of first n natural numbers is %f ",avg);
getch();
}

3. for loop-

Like the while and do-while, the for loop provides a mechanism to repeat a task until a particular condition is true. "for loop " is usually known as a determinate or definite loop because the programmer knows exactly how many times the loop will repeat. The number of times the loop has to be executed can be determined mathematically by checking the logic of the loop. The syntax of for loop is given below:

for(initialization ; condition; increment/decrement update )
{
statement block;
}
statement Y;

When the for loop is used, the loop variable is initialized only once. With every iteration of these loops, the value of loop variable is updated and the condition is checked. If the condition is true, the statement block of the loop is executed else the statement comprising the statement block of the loop are skipped and the control jumps to the immediate statement following the for loop body.
            The for loop is widely used to execute a single or a group of statement a limited number of times. Another point to consider is that in a for loop, condition is tested before the statement contained in the body are executed. So if the condition does not hold true, then the body of the loop may never get executed.

For eg.              /* program to print the following pattern */

#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,count=0;
for(i=1;i<=5;i++)
{
printf("\n ");
for(j=1;j<=i;j++)
printf("\n %d",count++);
}
getch();
}

Monday, April 29, 2019

C language : conditional statement

                      Conditional statement in C language

Conditional statement: The conditional statement help us to jump from one part of the program to another depending on whether a particular condition is satisfied or not. These decision control statement include:

1. if statement
2. if else statement
3. if else if statement
4. switch case statement

1. if statement-
The if statement is the simplest form of decision control statement that is frequently used in decision making. The syntax of if statement is shown in figure:

if (test expression)
{
Statement 1;
..........
............
Statement n;
}
Statement x;

The if statement may include one statement or more statements enclosed within curly braces. First the test expression is evaluated, if the test expression is it true then statement of if block, statement 1 to n are executed otherwise these statements will be skipped and execution will jump to the statement x . In control statement no semicolon is used after the test expression.

For example,
/* Program to find whether a person is eligible for vote or not. */

#include<stdio.h>
#include<conio.h>
void main ()
{
clrscr();
int age;
printf ("\n Enter the age ");
scanf ("%d",&age);
if(age>=18)
printf ("\n Person is eligible for vote.");
getch();
}

2 . if else statement
       The decision control statement in which, the test expression is first evaluated. If the expression is true, statement Block 1 is executed and the statement Block 2 is skipped otherwise if the expression is false statement 2 is executed and statement 1 is skipped or ignored. The syntax for simple if else statement is shown in figure:

if (test expression)
{
Statement 1;
}
else
{
Statement 2;
}
Statement x;

Now in any case after the statement Block 1 and 2 gets executed ,the control will pass to statement x. Therefore, statement x is executed in every case.

For example,

/* Program to find whether a given number is even or odd. */

#include<stdio.h>
#include<conio.h>
void main ()
{
clrscr();
int n;
printf ("\n Enter the value of n  ");
scanf ("%d",&n);
if(n%2==0)
printf ("\n Entered number is even. );
else
printf ("\n Entered number is odd.");
getch();
}

3 . If else if statement
      C language supports if else if statement to test an additional condition apart from the initial test expression. The if else if construct work in the same way as a normal if statement.
if else if statement is also known as nested if construct. It is not necessary that every if statement should have an else block as C language supports simple if statement. After the first expression or the first if branch the programmer can have many else if branches as he wants depending on the test expression that has to be tested . The syntax for if else if statement is shown in figure:

if (test expression)
{
statement 1;
}
else if (test expression 2)
{
statement 2;
}
.....................
......................
else

statement X;
}


For example,

/* Program to find whether a given number is greater or smaller or equal. Only for positive numbers */

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
printf("\n Enter the value of a and b ");
scanf("%d %d",&a,&b);
if(a>b)
printf("\n a is greater than b ");
else if(b>a)
printf("\n b is greater than a ");
else
printf("\n a is equal to b ");
getch();
}

4. Switch case statement
     A switch-case statement is a multiway decision statement that is simplified version of an if else block that evaluates only one variable. The syntax of switch case is shown in figure:

switch (variable)
{
case 1:
statement 1;
break;
case 2:
statement 2;
break;
................
...................
case n:
statement n;
break;
default:
statement y;
}

Switch case mostly used in two situation-
1. When there is only one variable to evaluate in the expression.
2 . When many condition are being tested for.

              When there are many condition to test, using if -else- if construct become a bit complicated and confusing. Therefore, switch case statement are often used as an alternative to long if statement that compares a variable to several integral values. The switch case statement compares the value of a variable given in the switch statement with the value of each case statement that follows. If the value of a switch and the case statement matches then the statement block of that particular case is executed.
In the switch case, the break statement must be used at the end of each case because if it were not used then all the cases from one met will be executed.

For example,
/* program for switch case statement */

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main()
{
    int choice;
   while(1)
    {
  printf("\n 1. DAYS   ");
  printf("\n 2. MONTHS   ");
  printf("\n 3. Exit");
    printf("\n Enter your choice  ");
    scanf("%d",&choice);
    switch(choice)
    {
  case 1:
       printf(" Name of the days are ");
       printf("\n ");
       printf("\n Monday ");
       printf("\n Tuesday ");
       printf("\n Wednesday ");
       printf("\n Thrusday ");
       printf("\n Friday ");
       printf("\n Satday ");
       printf("\n Sunday ");
        break;
  case 2:
       printf(" Name of the months are ");
       printf("\n ");
       printf("\n January ");
       printf("\n Febuary ");
       printf("\n March ");
       printf("\n April ");
       printf("\n May ");
       printf("\n June ");
       printf("\n July ");
       printf("\n August ");
       printf("\n September ");
       printf("\n October ");
       printf("\n November ");
       printf("\n December ");
                break;
 
  default:
        printf("wrong choice");
         break;
case 3:
        exit(0);
     
   
    }
    getch();
}}

Function

FUNCTION C enables programmer to break up a program into segments commonly known as functions, each of which can be written more or...