click on this link......

LinkGrand.com

Tuesday, 29 January 2013

Functions in C

    A function is a set of statements which performs a task.  A function has a name, and it must return some value, i.e, the result that it calculates.  It may or may not take arguments - values on which it performs the task.
e.g.
 A function sqrt(), that finds the square root ofa given number.
    The name of the function is "sqrt", it takes one argument i.e., the number whose square root is to be found, and it return the result, i.e, the square root of the number.
e.g.
 A function date(), that finds todays date.
    The name is "date" and it does not take any arguments. It returns the result, i.e., today's date.

Thus every function has the following:
a) A name
b) Arguments (optional)
c) return value

In C, functions help in modularizing a program -i.e, forming modules of a large program.  A large program is broken down into smaller programs - each called a module. For each module a function is written.

There are two types of functions:
1) Predefined functions :
    Functions all ready defined in C header files. To use these functions, only include the header file and call the function.


2) User defined functions :
    A programmer creates the user defined functions in C according to need.

For all the library functions given below do the following:
1) State the header file and the prototype of the function
2) Describe the use of the function
3) Give a C program that uses the function.

1)  isalnum
2) isdigit
3) islower
4) isupper
5) tolower
6) toupper
7) strcpy
8) strcat
9) strlen
10) strrev
11) strncpy
12) strcmp
13) abs
14) sqrt
15) log
16) log10
17) modf
18) pow
19) sin
20) cos
21) tan

NOTE:

 In C, a return type of integer can be used to indicate true or false.
 true - any non zero value
 false - a zero.



User Defined Functions
    A user defined function in C can be created to perform specific tasks.  It consists of the following steps:
1) Specifying a function prototype
    Specify the signature of the function, ie.
    - the return type
    - the name
    - the argument types of the function
2) Specify the function definition
    Specify the steps to be performed by the function.

Both the function prototype and definition must be given outside "main" function.
3) Call the function
    The function is called or invoked from within the main() function.

There are mainly 2 types of functions
1) A function which does not return a value, i.e., return type is "void".
2) A function which returns a value.

The arguments passed from main are called as actual arguments and the arguments of the function, where they are collected are called as formal arguments.



Function

Function is one of the most are important facility provided by C .
There are two types of function

1 library function
2 user defined function

l. library function
           
Library function are the function which are already defined in c
The user can only use these function depending upon the purpose.
He cannot change or modify the meaning or purpose of library function
Eg  
            sqrt( )   it is used to find the square root of a number
a)      sqrt( 25 ) à  5.00000
            int y =  1600;
            sqrt(y)à40.00000
Explain the function e  
Explain the functions
Char C1 = ‘a’, c2 = ‘B’

Function                      Result
topper (c1)                   A
topper  (‘X’)                X
topper (‘M’)                M

tolower (C2)                b
tolower (‘D’)               d
tolower (‘e’)                e

toascii (C1)                  97
toascii (C2)                  66
toascii (‘b’)                  98

            The functions toupper ( ) & tolower ( ) return a character value whereas toascii ( ) returns an int. value.

2) User defined functions (UDF):-
            The uses defined function is the facility by which a user can create his own functions.  This provides the modularity approach. i.e. a big problem can be divided into small sub-problems can be divided into small sub-problems & every sub-problem will be treated as a separate problem.  By solving every sub-problem we solve the whole task.  Every sub-problem is known as a module.
            Functions make the task of programming easy, because suppose. We want to perform a task number of times in a program at different places. Then for this if we want only main ( ), for every time you have to write the code in the program.  This will unnecessarily increase the length of code & the program becames a big program, then the debugging of this program becames very difficult.
            Another option is to use functions.  We just define the function for a single time and we can call (Use) it for any number of times, anywhere in the program.  Instead of handling a big single function, it is better to have no. of small functions.

            Related to functions, the following three things are necessary:-
1)      Function declaration (prototype)
2)       Function call
3)      Function Definition.
1)      Function declaration (prototype) :-
Function declaration is the first step in creating UDF.  In ‘C’ it is must that everything we are using must be declared, first.  Without declaring a function we cannot use it.  So, it is important that we must declare a function before using.  Function declaration will be alone only once. i.e. re-declaring a function is not possible.  The general format of function declaration is as follows.

Return type function name (datatype1, arg1, datatype2 arg……, datatypen, arg.n);

Where, Return type is the type of value the function will return.
            Function name is the name of the function we want to create.  For giving a function-name we must follow the rules of creating identifies.
            Arg1, arg2, ----, argn are the different arguments or parameters those are passed to the function.  For every argument we must specify the data type separately.

            e.g. :-   1) int add (int x, int y);
                        2) add (int x, int y );
            Both these statements declare a function add, to which two int values are passed and it returns an int value.
            Any ‘C’ function can return at the most only one value more than one values cannot be return from a function.

To the calling function.
When we don’t specify the return type compiler assumes that the function will return an int value .
When we don’t want any return value from function then the return value from function will be void.
Eg void fun1(int x , float y, char z);
           
            This statement declares a function fun1 to which these parameters are passed of int type , float type and char type .
When this function ends it returns nothing to the calling function .
Eg
1.      long int fact(int x);
2.      int add(int x ,int y);
3.      void message (void);
4.      float divide( int x, float y);

function call
Function call statement is necessary for executing a function because without calling a function we cannot execute it
If the function returns some value, the function return the same value , the function call statements will be in the form of an expression .
If it doesn’t return any value the function call statement will be a simple statement .
While calling a function we don’t specify the return type or the datatype of arguments.

Eg
1.                  message( );
2.                  c=add(a,b);
3.                  display(c);

function definition
function definition contains the actual code we want to execute .
every function must be defined independently i.e. every function must be outside of  other function .
eg
            int add (int x , int y)
            {
                        return(x+y);
            }

once you have defined a function you have defined the function you  can call it any no of times from anywhere in the program.
            Depending upon whether the function returns a value and whether any argument are passed to that function.

Functions are categorized as follows.

Function with  no argument no return value
When a function has no return argument it does not receive any data from calling function similarly when it does not  receive a value the calling function does not receive any type of data from called function.
i.e. there is no data transfer between calling function and called function.
main()                      
            {
            printf ( "\nl am in main" ) ;
            itaty( );
            brazil( ):
            argentina( );
            }
            italy( )
{
printf ( "\nl am in italy" ) ;
}
brazil( )
{
printf ( "\nl am in brazil" ) ;
}
argentina( )
{
printf ( "\nl am in argentina" ) ;
}
The output of the' above program when executed would be as under:
I am in main
I am in italy
I am in brazil
I am in araentina
Function with argument without return value
In this approach the we could make the calling function to read  data from  the terminal and pass it on to the called function.
main( )
{
int i=10;
display( i);
prinf(“value of i in function main is %d”,i);
getch();           
}
display(int x)
{
printf(“\n message from display function”);
}


Function with argument & return value

In this approach the function receives data from calling function through argument  and display the result of calculation are the terminal the function on called  transfer the control along which the copies of value of the actual argument to the called function .
The called function is executed line by line in a normal manner until the return statement is encountered .After execution of return statement the value of a return argument is passed to calling function in the main function.
main()
{
            float area;
            int radius = 1 ;
            area = circle ( radius ) ;
            printf("\n%f", area);
}
circle ( int r)
{

float a;
a=3.14*r*r;
return (a);

}
Recursion

Recurtion is a fundamental thing in computer science
Suppose function f calls to procedure p an  procedure p again calls to function f  then function f is called as recursive function .
Work through the above program carefully, till you understand the
logic of the program properly. Recursive factorial function can be
understood only if you are thorough with the above logic.
Following is the recursive version of the function to calculate the
fartorial value

main( )
{
int a, fact;
printf ( "\nEnter any number " ) ;
scant ( "%d", &a );
fact = rec(a);
printf ( "Fartorial vallue = %d", fact);
}
rec(x)
int x;
{
int f;
if(x==1)
return (1);
else
f=x*rec(x-1);
return (f);
}      


Friday, 25 January 2013

Loop control structure

We frequently need to perform an action over and over, often with variations in the details each times. The mechanism which meets this need is the loop.

Loops :

The versatility of computer lies in its ability to perform a set of instructions repeatedly. This involves repeating some portion of a program either a specified number of times or until particular condition is being satisfied. this repetitive operation is done through a loop control structure. There are 3 methods by which we can repeat a part of program. They are: 
  • Using a for statement
  • Using a while statement
  • Using a do - while statement
 For loop :

for(initialization;  condition; decrement or increment iterator)
{
           statements;
}

While loop:

It is often the case in programming that you want to do something a fixed number of times. perhaps you want to calculate gross salaries of 10 different persons or you want to convert temperature from centigrate or farenhite for 15 different cities. The while loop is ideally suited for such cases.

while(condition)
{
       statements;
}

    The while loop in C is also a top tested loop, i.e., the condition is tested first, and only if the condition is true, the statements in the body of the loop are executed.  The syntax is:

    <initialization>
    while (<testcondition>)
    {
     statements...
     ...
     increment/decrement
    };

Do - while loop :

do
{
      statements;
}while(condition);


case control structure in c

C provides a special control statement that allows us to handle such cases effectively rather than using a series of 'if' statements.
     
Decision using Switch:

the control statement that allows us to make a decision from the number of choices is called a 'switch' or more correctly a 'swicth' case default. since these three keywords go together to make a 'Control Statement'. The most of them appears as follows:

switch(Expression)
{
        case <constant 1> :
                     do this;
              break;
         case<constant 2> :
                    do this;
              break;
        case<constant n> :
                   do this;
              break;
       default:
            do this;
}

The expression following keyword switch is any 'C' expression that will yield on together value. It could be an integer constant like 1,2,3, or an expression. The keyword case is followed by an integer or character constant. Each constant in each case must be different from all other the "do this" in above form of 'switch' represents any valid 'C' statements.


Decision Control Structure

In the start of learning C, We use sequence control structure, in which various steps are executed sequentially i.e. in the same order in which they appear in the program. In fact to execute the instructions sequentially, we don't have to do anything at all. By default instructions in a program are executed sequentially. However, in serious programming situations, seldom do we want the instructions to be executed sequentially. Many a times we want a set of instructions to be executed in one situation and an entirely different set of instructions to be executed in another situation. This kind of situation is dealt in C programs using a decision control instruction. As mentioned earlier a decision control instruction can be implemented in C using:
1) The if statement
2) The if - else statement

1) The if statement :

Like most languages, the keyword if to implement the decision control instruction. The general form of if statement looks like this:

if(this condition is true)
{
           execute this statement;
}

The keyword if tells compiler that what follows, is a decision control instruction. The condition following keyword if is always enclosed within a pair of parenthesis ( ). If the condition, whatever it is true then the statement is executed and if the condition is not true then the statement is not executed, instead the program skips it. 

As a general rule, we express a condition using C's relational operation. the relational operators allow us to compose 2 values to see whether they are equal to each other, unequal or whether one is greater than or less than the other. Here's how they look and how they are evaluated in C

Expression                        is trueif
x == y                           x is equal to y
x !=y                             x is not equal to y
x < y                             x is less than y
x > y                             x is greater than y
x <= y                           x is less than or equal to y  
x >= y                           x is greater than or equal to y

2) If  - else statement: 

If the condition is true, it executes one set of statements and if the condition is false, it executes another set of instructions.

if(condition)
{
        statements;
}
else
{
        statements;
}

Wednesday, 23 January 2013

string copy using strcpy inbuilt function

#include<stdio.h>
#include<conio.h>
void main()
{
    char name[25],copy[25];
    clrscr();
    printf("\nEnter your name:");
    scanf("%s",name);
    strcpy(copy,name);
    printf("\nYour name is %s",name);
    printf("\n\ncopied string is  %s",copy);
    getch();
}

string copy using strcpy inbuilt function
string copy using strcpy inbuilt function

string copy using strcpy inbuilt function

string concatenation without inbuilt function

#include<stdio.h>
#include<conio.h>
void main()
{
    char str1[25],str2[25],str3[25];
    int i=0,j=0;
    clrscr();
    printf("\nEnter the first string:");
    gets(str1);
    printf("\nEnter the second string:");
    gets(str2);
    while(str1[i]!='\0')
    {
        str3[i]=str1[i];
        i++;

    }
    while(str2[j]!='\0')
    {
        str3[i]=str2[j];
        i++;
        j++;
    }
    str3[i]='\0';
    printf("\nconcatenated string is %s ",str3);
    getch();
}

string concatenation without inbuilt function
string concatenation without inbuilt function

string concatenation using inbuilt function

#include<stdio.h>
#include<conio.h>
void main()
{
    char str1[25],str2[25];
    int y;
    clrscr();
    printf("\nEnter first string:");
    scanf("%s",str1);
    printf("\nEnter second string:");
    scanf("%s",str2);
    strcat(str1,str2);
    printf("\nstr1 contains  %s\n",str1);
    printf("\nstr2 contains  %s\n",str2);

    getch();
}

string concatenation using inbuilt function
string concatenation using inbuilt function

string concatenation using inbuilt function
string concatenation using inbuilt function

To find prime numbers in an array and to calculate the sum of those prime numbers

#include<stdio.h>
#include<conio.h>
void main()
{
    int a[50],count,c,n,i,j,sum=0;
    clrscr();
    printf("Enter the no. of elements:");
    scanf("%d",&n);
    for(i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
    }
    count=0;
    printf("\nprime numbers are:\n");
    for(i=0;i<n;i++)
    {
        c=0;
        for(j=2;j<a[i];j++)
        {
            if(a[i]%j==0)
            {
                   c=1;
                   break;
            }
        }
         if(c==0)
         {
            printf("%d\t",a[i]);
            sum=sum+a[i];
            count++;

         }

    }
    printf("\nThe number of prime numbers is %d",count);
    printf("\nThe sum of prime no. is %d",sum);

    getch();
}

To find prime numbers in an array and to calculate the sum of those prime numbers
To find prime numbers in an array and to calculate the sum of those prime numbers

To find whether the given number is palindrome or not.

#include<stdio.h>
#include<conio.h>
void main()
{
    int num,no,i,rem,reverse=0;
    clrscr();
    printf("Enter the number:");
    scanf("%d",&num);
    no=num;
    while(num! = 0)
    {
        rem = num % 10;
        reverse = reverse * 10 + rem;
        num= num / 10;
    }
    printf("Reversed number is %d",reverse);
    if(no==reverse)
    {
    printf("Number is palindrome");
    }
    else
    {
    printf("Number is not palindrome:");
    }
    getch();
}

To find whether the given number is palindrome or not.
To find whether the given number is palindrome or not.

To find whether the given number is palindrome or not.
To find whether the given number is palindrome or not.

Tuesday, 22 January 2013

To find number of characters in a string

#include<stdio.h>
#include<conio.h>
void main()
{
    char str[25];
    int i=0;
    clrscr();
    printf("Enter the string:");
    gets(str);
    while(str[i]!='\0')
    {
        i++;
    }
    printf("Number of character in %s is %d",str,i);


    getch();
}

To find number of characters in a string
To find number of characters in a string

To find number of characters in a string
To find number of characters in a string


Addition of two matrix


#include<stdio.h>
#include<conio.h>
void main()
{
    int a[3][3],i,j,b[3][3],c[3][3];
    clrscr();
    printf("Enter the elements for 1st matrix:");
    for(i=0;i<3;i++)
    {
        for(j=0;j<3;j++)
        {
            scanf("%d",&a[i][j]);
        }
    }
    printf("Enter the elements for 2nd matrix:");
    for(i=0;i<3;i++)
    {
        for(j=0;j<3;j++)
        {
            scanf("%d",&b[i][j]);
        }
    }
    for(i=0;i<3;i++)
    {
        for(j=0;j<3;j++)
        {
            c[i][j]=a[i][j] + b[i][j];
        }
    }

    printf("The addition of two matrix is :\n");
    for(i=0;i<3;i++)
    {
        for(j=0;j<3;j++)
        {
            printf("%d\t",c[i][j]);
        }
        printf("\n");

    }
    getch();
}

Addition of two matrix
Addition of two matrix





Getche() function

#include<stdio.h>
#include<conio.h>
void main()
{
    char ch;
    clrscr();
    printf("Enter the character:");
    ch=getche();
    printf("The character is %c",ch);


    getch();
}

Getche() function
Getche() function

Getche() function
Getche() function

Getchar() function



#include<stdio.h>
#include<conio.h>
void main()
{
    char ch;
    clrscr();
    printf("Enter the character:");
    ch=getchar();
    printf("The character is %c",ch);
    getch();
}

Getchar() function
Getchar() function

Getchar() function
Getchar() function

getch function

#include<stdio.h>
#include<conio.h>
void main()
{
    char ch;
    clrscr();
    printf("Enter the character:");
    ch=getch();
    printf("The character is %c",ch);


    getch();
}

getch function

getch function

To find sumof even numbers and product of odd numbers in an array


#include<stdio.h>
#include<conio.h>
void main()
{
    int a[50],i,even[50],odd[50],sum=0,prod=1;
    clrscr();
    printf("Enter 10 elements:");
    for(i=0;i<10;i++)
    {
        scanf("%d",&a[i]);
    }
    printf("\nEven nos are:");
    for(i=0;i<10;i++)
    {
        if(a[i]%2==0)
        {
            even[i]=a[i];

            printf("%d\t",even[i]);
            sum=sum+even[i];

        }
    }
    printf("\nodd nos are:");
    for(i=0;i<10;i++)
    {
        if(a[i]%2!=0)
        {
            odd[i]=a[i];

            printf("%d\t",odd[i]);
            prod=prod*odd[i];

        }

     }
     printf("\nSum of even nos is %d",sum);
     printf("\nproduct of odd numbers is %d",prod);

       getch();
}

To find sumof even numbers and product of odd numbers in an array

Two dimensional array to store roll number and marks

#include<stdio.h>
#include<conio.h>
void main()
{
    int stud[30][20],i,j;
    clrscr();
    printf("\nEnter the rollno and marks:");
    for(i=0;i<3;i++)
    {
        scanf("%d%d",&stud[i][0],&stud[i][1]);

    }
    printf("\nRoll no \t marks");
    for(i=0;i<3;i++)
    {
        printf("\n%d\t%d\n",stud[i][0],stud[i][1]);
    }
    getch();
}

Two dimensional array to store roll number and marks
Two dimensional array to store roll number and marks

Two dimensional array to store roll number and marks


Friday, 11 January 2013

Structure2 (using for loop)

Program to display the following structure:

1
1 2
1 2 3
1 2 3 4

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


            


structure1 (using for loop)

Program to display the following structure:

1 2 3 4 5 6 7 8 9
2 3 4 5 6 7 8 9
3 4 5 6 7 8 9
4 5 6 7 8 9
5 6 7 8 9
6 7 8 9
7 8 9
8 9
9

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


            


Program to find sum of integers from 1 to n

#include<stdio.h>
#include<conio.h>
void main()
{
               int i,a,sum=0;
              printf("Enter the last integer:");
             scanf("%d",&a);
             for(i=1;i<=a;i++)
            {
                      sum=sum + i;
            }
            printf("The sum of integers from 1 to %d is %d",a,sum);
           getch();
}

Program to find sum of integers from 1 to n
Program to find sum of integers from 1 to n
Output for sum of integers from 1 to n
Output for sum of integers from 1 to n