C PROGRAM

 


UNIT 4. Programming in C (25 marks)

 

 

What is c programming language?

It is a High Level Programming Language, developed by Dennis Ritchie at AT & T’s Bell Laboratories of USA, in 1970. It is a very powerful programming language. It is used for both system programming and application programming. So, often known as Middle Level Programming Language, also. It means, it supports or works as the low level language and high level language, both.

 

What are the features of c language?

The features of c language are:

It supports high level and level programming both, so known as mid level programming language.

It is mostly used for System programming but very popular for Application programming, too.

The program development is faster and more efficient.

It has very powerful tools and keywords.

It uses its own text editor.

It has its own compiler.

It supports structured programming.

It is portable easily.

It has very powerful library functions set.

Flexible in programming.

What are the advantages and disadvantages of c language?

 

The advantages are:

Suitable for system programming.

It is easier to interact with hardware.

Easy to learn.

Program code is secure.

It is compact and efficient.

 

The disadvantages are:

It does not contain runtime checking.

There is no strict data type checking.

As the program extends, the debugging becomes more complex because it uses compiler instead of interpreter for the compilation.

Semi-colon requires for each statement.

 

 

 

 

 

 

 Define the following terms:

a) Editor: This is the area, in which we type the program. C language has its own text editor but we can use any other text editor program also.

 

b) Pre-processor: This is the collection of complex codes to instruct the machine to understand the certain keywords. It is written with preceding # symbol. For example: #include, in this example, include pre-processor with the hash symbol, uses the instruction or complex codes from the file ‘stdio.h’, which is already stored by c language. These .h files are called header files. So, include pre-processor is used for using the header files.

 

c) Compiler: It is a type of software to change the source code of high level programming language into machine readable form called object code.

 

d) Linker: It is also a type of software, which links the various library files with the object codes and creates an executable file with .exe extension. Then, exe file can run independently.

 

FUNDAMENTAL OF C

Define the character set. Also define the character set used in c language.

 

The set of alphabets, digits, white characters and other symbols used in any programming language is called a character set. The character set used in c are:

 

Alphabet – A, B, C, ……..Z and a, b, c, ….z

 

Digits – 0, 1, 2, …………9

 

Special Symbols - ~ ‘ ! @ % ^ & * ( ) - _ + = | \ { }  []  : ; “ ‘ <> , . ? /

 

Define comment. Comment is a text or set of other characters, which is not compiled or executed from the compiler. It is written in the program to give required information to other programmers and the developers themselves. There are two types of comment writing methods:

 

a. Single line comment: It is written with the // symbol.

 

Eg. // This is my first program.

 

b. Multi-line comment: It is written with /*………….*/ symbols.

 

Eg. /* This is

 

              multi line

 

           comment style */

 

Define C Tokens.

 

The set of identifiers, keywords, constants, variables and operators is known as C Tokens. It remains as a single unit and compiler does not break in the time of compilation.

 

Define the following terms:

 

a) Identifiers: Identifiers are names for entities in a C program, such as variables, arrays, functions, structures, unions and labels.

 

b) Keyword: Keyword is a reserved word that is already stored by the c language developer. The reserved word cannot be used as the identifiers. There 32 Keywords in C according to the ANSI (American National Standard Institute) in c language. They are: void, printf, scanf, if, else, while, getch, do, for, break, continue etc

 

c) Data types in c: The term Data Types in any language refers to the types of data which can be used in the program execution for entering and manipulating as the values. In the same way, the data types in c also refer to the data types, which can be used as the values. Basically it is of four types. They are:

 

int : It represents the integer type data. It means the numbers without the decimal points. It consumes 2 bytes memory. The derived data types from int are short int and long int.

float : It means the real numbers with the decimal points. It consumes 4 Bytes memory space. It can also be signed and unsigned. Derived data types of it are double and long double.

char : It is used for a single character (alphabet or symbol) like ‘A’, ‘f’, ‘@’ etc. It requires 1 byte memory. It can also be signed  or unsigned.

void : void means no value. It means null value. It is used for returning null value to the modules.

d) Constants

 

e) Variables

 

f) Statements : The set of keywords, identifiers, operators, variables and constants ended with the semicolon or a curly bracket is called statement. It is of two types:Simple

 

Statement : The statement written in a single line and ended with the semicolon is simple statement.  Eg. printf (“My program”);

Compound Statement:  The group of simple statements grouped by the curly bracket open and close is the compound statement. Eg.

if (n>0)

{

   a=b+c;

   x=x*x;

   printf(“%d %d”, a,x);

}

g) Escape Sequences: The symbol \ or ‘ is supposed as the Escape character. It means, the compiler of c programming language understands this character and the text after this to take as a special case. And the set of this symbol and the character behind it is known as the Escape Sequence. Some common escape sequences are:

 

Character            Escape

New Line             \n

Horizontal tab    \t

Null character    \0

Quotation mark \”

Apostrophe        \’

Backslash (\)      \\

h) Operators: (imp)The symbols, which are used to operate on the operands for the mathematical and logical calculations are known as operators. C programming language has a rich set of built-in operators. Operator that requires two operands are binary (dyadic) operators, operators that require one operand is unary (monadic) and the operator that requires three operands is ternary operator. Eg. a+b, here + is an operator.

 

Types of operators:

 

Arithmetic Operator

Relational Operator

Equality Operator

Logical Operator

Assignment Operator

Increment/Decrement Operator

Conditional Operator (Ternary Operator)

Bitwise Operator

Special Operator

i) Library Functions: Functions are the independent sections or the block of statements given a specific name and they can be used by any program according to the requirements. They are developed to perform a certain task. They are of two types:

 

a) Library Functions: These are the ready-made formula-like functions stored in c language library. They can be used in any program. abs(), printf (), scanf (), clrscr(), getch(), strlen(), sqrt(), etc. are some examples of Library functions.

 

b) User defined function: The functions developed by the users in their own program are called User-defined functions.

 

INPUT/OUTPUT (I/O) functions

 

1. printf() : It is a formatted output function.

 

Eg. printf(“My School”);

 

2. scanf() : It is to enter any value to the program.

 

Eg. scanf(“%d”, &x);

 

Program Example

 

a) Write a c program to enter any two numbers and print the sum of them.

# include

void main()

{

 int a, b, s;

 clrscr();

 printf(“Enter First Number”);

 scanf(“%d”, &a);

 printf(“Enter Second Number”);

 scanf(“%d”, &b);

 s = a + b;

 printf (“The sum is %d”, s);

 getch();

}

b) Write a c program to calculate the area of a rectangle, where the length is 20 and breadth is 15.

# include 

void main( )

{

 int l = 20, b = 15;

 int a;

 clrscr();

 a = l * b;

 printf (“The area is %d”, a);

 getch();

}

c) WAP to calculate the area of a rectangle in c. [Hints: a = l x b]

# include

void main()

{

 int l, b, a;

 printf (“Enter Length: ”);

 scanf (“%d”, &l);

 printf (“Enter Breadth: “);

 scanf (“%d”, &b);

 a = l * b;

 printf (“The area is %d”, a);

 getch();

}

d) Write a program to enter length and breadth of a rectangle and calculate the perimeter. [p = 2 (l + b) ]

# include

void main ()

{

 int l, b, p;

 printf (“Enter Length :”);

 scanf (“%d”, &l);

 printf (“Enter Breadth :”);

 scanf (“%d”, &b);

 p = 2 * (l + b);

 printf (“The perimeter is : %d”, p);

 getch();

}

e) WAP to calculate the area of a triangle .

# include

# include

void main()

{

 int b, h, a;

 printf (“Enter base and height”);

 scanf (“%d %d”, &b, &h);

 a = ½ * b * h;

 printf (“The area is %d”, a);

 getch();

}

 

f) WAP to enter the length of any one side of a square and calculate the area and perimeter in c language.

# include 

void main ()

{

 int l, a, p;

 clrscr ();

 printf (“Enter length”);

 scanf (“%d”, &l);

 a = l * l;

 p = 4 * l;

 printf (“The area is %d and the Perimeter is %d”, a, p);

 getch();

}

g) WAP to calculate the volume of a box.[v=l*b*h]  (Do yourself)

 

j) WAP to enter the radius of a circle and print the circumference of it. [c = 2 pi r] (Do yourself)

 

CONTROL STRUCTURE IN C (important)

 

Normally, the program execution flows top to the bottom lines of the programs. It means program executes one line after another. But sometime we need to execute other part of the programs or we need to divert the program flow from its normal execution. In such a case, we need some program statements, which are known as Control Structures. They are of three Types of control structure : a. sequence  b.selection and c. looping

 

A) Sequence: Program generally flows from top left top right bottom.

 

WAP to enter the length, breadth and height of a box and calculate the total surface area (TSA). [TSA = 2 * (L*B + B*H + L*H)]

# include

void main ()

{

 int l, b, h, tsa;

 clrscr();

 printf (“Enter length, breadth and height”);

 scanf (“%d %d %d”, &l, &b, &h);

 tsa = 2 * (L*B + B*H + L*H);

 printf (“Total surface area is %d”, tsa);

 getch ();

}

WAP to enter the radius of a circle and calculate the area . [a = pi r 2]

# include

void main ()

{

 float r, a;

 printf (“Enter radius”);

 scanf (“%f”, &r);

 a = 22/7 * r * r;

 printf (“The area is %f”, a);

 getch();

}

j) WAP to enter the radius of a circle and print the circumference of it. [c = 2 pi r]

 

B) Selection/branching/condition: These type of control structure changes the flow of program execution with or with out conditoon.

 

B.1) Conditional Statements: They break the program flow if the condition is matching. Eg. if, if….else and if…..else….if

 

if condition

 

This condition is used for a single condition and single block of statements.

 

Syntax:

if (condition)

{

Block of statements'

}

Example:

 

1. WAP to enter the marks of English and print “Pass” if it is 40 or more.

# include

void main ( )

{

 float e;

 printf (“Enter English Marks \n”);

 scanf (“%f”, &e);

 if (e >=  40)

{

 Printf (“Pass”);

}

 getch ( );

}

Note: The above program states only about pass. If the marks is less than 40, it displays blank.

 

2. WAP to enter the age of a person and print “He can vote”, if the age is 18 or above.

# include

void main ( )

{

 float a;

 printf (“Enter age \n”);

 scanf (“%f”, &a);

 if (a >=  18)

{

 Printf (“You can vote”);

}

 getch ( );

}

If….else condition

 

This condition is used for a double conditions and double blocks of statements.

 

Syntax:               

if (condition)

{

Block of statements'

}

else

{

Block of statements'

}

Example:

 

1. WAP to enter the marks of English and print “Pass” if it is 40 or more, otherwise “Fail”.

# include

void main ( )

{

 float e;

 printf (“Enter English Marks \n”);

 scanf (“%f”, &e);

 if (e >=  40)

 {

  printf (“Pass”);

 }

 else

 {

   printf (“Pass”);

 }

 getch ( );

}

Example 2: WAP to enter the age of a person and print “He can vote” if the age is 18 or above, otherwise print “He cannot vote”.

# include

void main ( )

{

 float e;

 printf (“Enter age\n”);

 scanf (“%f”, &a);

 if (a >=  18)

 {

  printf (“You can vote”);

 }

 else

 {

   printf (“You cant vote”);

 }

 getch ( );

}

Example 3: WAP to check whether given numvber if odd or even

# include

void main ( )

{

 int n;

 printf (“Enter number\n”);

 scanf (“%d”, &n);

 if (n%2 ==  0)

 {

  printf (“%d is even”,n);

 }

 else

 {

  printf (“%d is odd”,n);

 }

 getch ( );

}

Example 3: WAP to find greatest among two number.

# include

void main ( )

{

 int a,b;

 printf (“Enter two number\n”);

 scanf (“%d %d”, &a,&b);

 if (a>b)

 {

  printf (“%d is greatest”,a);

 }

 else

 {

  printf (“%d is greatest”,b);

 }

 getch ( );

}

else if statement: This statement is used for the multiple conditions and multiple blocks of statements.

 

Syntax:

if (condition 1)

{

 Statement Block 1;

}

else if (condition 2)

{

 Statement Block 2;

}

..

..

else

{

default staement

}

 

Example 1: WAP to enter a number and print “Positive” if it is greater than 0, print “Negative” if it is less than 0, otherwise print “Zero”.

# include

void main ( )

{

int n;

printf("Enter number");

scanf("%d",&n);

if (n > 0 )

{

 printf (“Positive”);

}

else if (n < 0 )

{

  printf (“Negative”);

}

else

{

 printf (“Zero”);

}

getch ( );

}

Example 2: WAP to enter the percentage and print the division

# include

void main ()

{

 float p;

 clrscr ( );

 printf (“Enter percentage:”);

 scanf (“%f”, &p);

 if (p > = 80 && p<=100)

 printf (“Distinction”);

 else if (p>=60 && p<80)

 printf (“First”);

 else if (p>=50 && p<60)

 printf (“Second”);

 else if ( p>=40 && p<50)

 printf (“Third”);

 else

 printf("fail");

getch ();

}

Example 3: WAP to enter 3 number and print gratest number

# include

void main ( )

{

int a,b,c;

printf("Enter number");

scanf("%d %d %d",&a,&b,&c);

if (a>b && a>c)

{

 printf (“%d is greatest”,a);

}

else if (b>a && b>c)

{

  printf (“%d is greatest”,b);

}

else

{

   printf (“%d is greatest”,c);

}

getch ( );

}

B.2) Unconditional Statements: They break the program flow with out any condition. Eg. goto statement

 

Syntax

label:

goto label;

OR

goto label;

label:

Program example of goto [This program allows user to only enter value under 100]

# include

void main ()

{

 float p;

 clrscr ( );

 label:

 printf (“Enter percentage:”);

 scanf (“%f”, &p);

 if (p > 100)

 {

 printf (“Invalid input”);

 goto label;

 }

 getch();

 }

 

C) Looping: Loop is the process of repeating any block of statements up to the given number of times or until the given condition is not over.

 

There are three types of Loop: 1. for loop 2. while loop and 3. do while loop

 

FOR… loop: Syntax of for loop

 

for (initialization; condition; increment/decrement)

            {

                        Statements (s);

            }

Examples:

 

a) 1, 2, 3, 4, ………….100.

#include

int main()

{

    int i;

    for (i=1;i<=100;i++)

    {

        printf("%d\n",i);

    }

    return 0;

}

b) 1, 3, 5, 7, ……………..99.

 

c) 2, 4, 6, 8, ………………100.

 

d) 5, 10, 15, ………………….50.

#include

int main()

{

    int i,s;

    for (i=1;i<=10;i++)

    {

        s=5*i;

        printf("%d\n",s);

    } 

    return 0;

}

WAP to calculate sum of n-natural number.

#include

int main()

{

    int n,i,s=0;

    printf("Enter any number\t");

    scanf("%ld",&n);

    for (i=1;i<=n;i++)

    {

        s=s+i;

    }

    printf("Sum  is %d\n",s);

    return 0;

}

WAP to calculate product of n-natural number. (Factorial of a given number.

#include

int main()

{

    int n,i,p=1;

    printf("Enter any number\t");

    scanf("%d",&n);

    for (i=1;i<=n;i++)

    {

        p=p*i;

    }

    printf(“Product  is %d\n”,p);

    return 0;

}

WAP to generate fibonacci series. [ 0,1,1,2,3,5,8 …..10th term]

#include

int main()

{

    int i,a=0,b=1,c;

    printf(“%d%d””,a,b);

    for (i=1;i<=10;i++)

    {

       c=a+b;

       printf(“%d”,c);

       a=b;

       b=c;       

    }

    return 0;

}

WAP to generate 1 2 4 7 11 ...............10th term

#include

int main()

{

    int i,a=1,g=1;

    for (i=1;i<=10;i++)

    {

       printf(“%d”,a);

       a=a+g;

       g=g+1;

    }

    return 0;

}

WAP to generate 1 2 5 10 17 ...............10th term

#include

int main()

{

    int i,a=1,g=1;

    for (i=1;i<=10;i++)

    {

       printf(“%d”,a);

       a=a+g;

       g=g+2;

    }

    return 0;

}

WAP to generate  3 12 27 48 ................10th term

#include

int main()

{

    int a,i;

    for (i=1;i<=10;i++)

    {

       a=3*I*I;      

       printf(“%d”,a);

    }

    return 0;

WHILE Loop (Entry Control loop)

 

Syntax:

while(condtion)

{

Block of statements;

}

WAP to calculate sum of n-natural number.

#include

int main()

{

    int n,s=0,i=1;

    printf("Enter any number\t");

    scanf("%d",&n);

    while (i<=n)

    {

         s = s+i;

  i=i+1;   

    }

    printf("Sum of digits is %ld\n",s);

    return 0;

}

WAP to calculate product of digits of a given number.

#include

int main()

{

    int n,p=1,i=1;

    printf("Enter any number\t");

    scanf("%d",&n);

    while (i<=n)

    {

         p = p*i;

         i=i+1;   

    }

    printf(“Product of digits is %d\n”,p);

    return 0;

}

WAP to generate 1 2 4 7 11 ...............10th term

#include

int main()

{

    int i=1,a=1,g=1;

    while (i<=10)

    {

       printf(“%d”,a);

       a=a+g;

       g=g+1;

       i=i+1;

    }

    return 0;

}

WAP to calculate sum of digits of a given number.

#include

int main()

{

    int n,s=0,r;

    printf("Enter any number\t");

    scanf("%d",&n);

    while (n!=0)

    {

        r = n%10;

        s = s+r;

        n = n/10;

    }

    printf("Sum of digits is %d\n",s);

    return 0;

}

WAP to calculate product of digits of a given number.

#include

int main()

{

    int n,p=1,r;

    printf("Enter any number\t");

    scanf("%d",&n);

    while (n!=0)

    {

        r = n%10;

        p = p*r;

        n = n/10;

    }

    printf(“Product of digits is %d\n”,p);

    return 0;

}

WAP to reverse a given number.

#include

int main()

{

    int n,p=0,r;

    printf("Enter any number\t");

    scanf("%d",&n);

    while (n!=0)

    {

        r = n%10;

        p = p*10+r;

        n = n/10;

    }

    printf(“Reverse is %d\n”,p);

    return 0;

}

WAP to check whether given number is palindrome or not.

#include

int main()

{

    int n,p=0,r,z;

    printf("Enter any number\t");

    scanf("%d",&n);

    z=n;

    while (n!=0)

    {

        r = n%10;

        p = p*10+r;

        n = n/10;    

    }

    if (z==p)

    {

    printf(“%d is palindrome \n”,z);

    }

   else

   {

    printf(“%d is not palindrome \n”,z);

   }

    return 0;

}

WAP to check whether given number is armstrong or not. [153 is Armstrong]

#include

#include

int main()

{

    int n,s=0,r,z;

    printf("Enter any number\t");

    scanf("%d",&n);

    z=n;

    while (n!=0)

    {

        r = n%10;

        s = s+pow(r,3);

        n = n/10;

    }

    if (z==s)

    {

    printf(“%d is armstrong \n”,z);

    }

   else

   {

    printf(“%d is not armstrong \n”,z);

   }

    return 0;

}

DO Loop

 

Syntax:

do

{

Block of statements;

}while(condition);

WAP to calculate sum of n-natural number.

#include

int main()

{

    int n,s=0,i=1;

    printf("Enter any number\t");

    scanf("%d",&n);

    do

    {

         s = s+i;

         i=i+1;   

    }while (i<=n);

    printf("Sum of digits is %ld\n",s);

    return 0;

}

Array

 

An array is a collection of variables of same type that are represented by a common name i.e. array is the collection of homogenous data type (Contains similar datas). If we declare array as int then it must only contain all integer data and same for floats and char. Each array element is specified by array name followed by index or subscript enclosed in square bracket (eg, a[10]). Hence, it is also called indexed or subscripted variables. In an array index of array represent the size of an array.

 

Let us consider, int age[5]

 

This mean array name is age which is capable of storing 5 different data under integer datatype.

 

age[0] = 15

 

age[1] = 25

 

age[2] = 13

 

age[3] = 22

 

age[4] = 17

 

Types of array

 

Depending upon the number of subscript or index number array are of 2 types:

 

1-Dimension

N-Dimension (Multi-dimension)

1-Dimension:

 

This type of array has only one subscript.

 

Declaration:

 

Data_type array_name[size]

 

Example:

 

int salary[100]

 

Program example.

 

Q1. WAP to input 10 different number and print them all.

#include

int main()

{

    int a[10], i;

    printf ("Enter any 10 number");

    for(i=0;i<10;i++)

    {

        scanf("%d",&a[i]);

    }

    for(i=0;i<10;i++)

    {

        printf(“%d”,&a[i]);

    }

        return 0;

}

Q2. WAP to input salary of 1000 employees and calculate average salary.

#include

int main()

{

    int sal[1000], i, s=0;

    float av;

    printf ("Enter any 10 number");

    for(i=0;i<1000;i++)

    {

        scanf(“%d”,&sal[i]);

    }

    for(i=0;i<1000;i++)

    {

        s=s+sal[i];

    }

   av = s/1000;

   printf(“Average salary of 1000 employee is %f”, av);

   return 0;

}

Q3. WAP to input salary of 1000 employees and count total number of employee getting salary between 30000 and 50000.

#include

int main()

{

    int sal[1000], i, c=0;

    for(i=0;i<1000;i++)

    {

        scanf(“%d”,&sal[i]);

    }

    for(i=0;i<1000;i++)

    {

        if(sal[i]>=30000 && sal[i]>=50000)

            {

               c=c+1;

            }

     }

   printf(“Total number of employee is %d”, c);

   return 0;

}

Q5. WAP to input 10 different number and find the greatest among them.

#include

int main()

{

    int a[10], i, g;

    printf ("Enter any 10 number");

    for(i=0;i<10;i++)

    {

        scanf("%d",&a[i]);

    }

    g = a[0];

    for (i=0;i<10;i++)

    {

        if (g>a[i])

        {

            g=a[i];

        }

    }

    printf("Greatest number is %d\n",g);

    return 0;

}

Q6. WAP to input 10 different number and sort the in ascending order.

#include

int main()

{

    int a[10], i, j, temp;

    printf ("Enter any 10 number");

    for(i=0;i<10;i++)

    {

        scanf("%d",&a[i]);

    }

    for (i=0;i<10;i++)

    {

        for (j=0;j<10;j++)

        {

            If (a[j]>a[j+1])

                                                                {

                                                                temp = a[j];

                                                                a[j] = a[j+1];

                                                                a[j+1] = temp;

                                                                }

        }

    }

    printf(“Ascending order is”);

    for (i=0;i<10;i++)

    {

        Printf(“%d \t”,a[i]);

    }

    return 0;

}

Q3. WAP to input salary of n-employees and count total number of employee getting salary between 30000 and 50000.

#include

int main()

{

    int sal[1000], i, c=0, n;

    printf("Enter the number of employees");

    scanf("%d",&n);

    for(i=0;i=30000 && sal[i]>=50000)

            {

               c=c+1;

            }

     }

   printf(“Total number of employee is %d”, c);

   return 0;

}

N-Dimension (Multidimension array)

 

This type of array has more than one subscript.

 

Declaration:

 

Data_type array_name[size][size]

 

Example:

 

int n[3][3]

 

Program example

 

Q1. WAP to input 3x3 matrix data and display the data of it.

#include

int main()

{   int a[3][3],i,j;

    printf("Enter 9 number");

    for (i=0;i<3;i++)

    {

        for (j=0;j<3;j++)

        {

            scanf("%d",&a[i][j]);

        }

    }

    for (i=0;i<3;i++)

    {

        for (j=0;j<3;j++)

        {

            printf("%d\t",a[i][j]);

        }

        printf("\n");

    }

    return 0;

}

Q2. WAP to input 3x3 matrix and perform matrix addition

#include

int main()

{   int a[3][3], b[3][3], c[3][3],I ,j;

    printf("Enter 9 number");

    for (i=0;i<3;i++)

    {

        for (j=0;j<3;j++)

        {

            scanf(“%d%d”,&a[i][j],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("\n");

    }

printf(“Added matrix is”);

for (i=0;i<3;i++)

    {

        for (j=0;j<3;j++)

        {

            printf(“%d \t”,c[i][j]);

        }

printf(“\n”);

    }

    return 0;

}

Q2. WAP to input 3x3 matrix and perform matrix multiplication

#include

int main()

{   int a[3][3], b[3][3], p[3][3],i ,j, k;

    printf("Enter 9 number");

    for (i=0;i<3;i++)

    {

        for (j=0;j<3;j++)

        {

            scanf(“%d%d”,&a[i][j],b[I][j]);

        }

    }

    for (i=0;i<3;i++)

    {

        for (j=0;j<3;j++)

        {

                                                p[I][j] = 0;

                                                for(k=0;k<3;k++)

                                                 {

                               p[i][j] = p[i][j] + a[i][k]*b[k][j];

                                 }

       }  

     }

printf(“Multiplied matrix is”);

for (i=0;i<3;i++)

    {

        for (j=0;j<3;j++)

        {

            printf(“%d \t”,p[i][j]);

        }

printf(“\n”);

    }

    return 0;

}

String: String is a group of characters that can be represented only by character array. To represent a character/string we use ‘char’ datatype.

 

i.e. char a, char a=‘x’

 

Where, char is data type and a is string variable and ‘x’ is a character.

 

Similarly, we can initialize string as one-dimension character array as:

 

Char a[5] = “hello” which is stored in array as follow

 

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

‘h’           ‘e’           ‘l’            ‘l’            ‘o’           \0

we can initialize array of string as two-dimension array as:

 

Char a[2][5] = {“ball” , “cat” , “apple”}, which is stored in array as follow

 

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

a[0]        ‘b’           ‘a’           ‘l’            ‘l’            \0           

a[1]        ‘c’           ‘a’           ’t’            \0                            

a[2]        ‘a’           ‘p’           ‘p’           ‘l’            ‘e’           \0

String handling function [Library function / Inbuilt function] V.imp

 

As we know, functions are the self contained program that performs certain task. Similarly the function which are given by C-library itself or inbuilt in C-library are known as library or inbuilt-function. String handling function or string function are the library functions which are used to manipulate strings in our program for simplicity and convenience. This inbuilt functions are defined under the header file ’string.h’ . In C we have several string handling functions which are as follows:

 

[Note: don’t miss ’string.h’ header file]

 

1) strlen( )

Function: This function returns total number of characters in a given string.

Syntax: strlen(string);

Program example:

#include <stdio.h>

#include <string.h>

int main()

{

    char a[10];

    int l;

    printf("Enter any string");

    scanf("%s",a);

    l=strlen(a);

    printf("The length is %d",l);

    return 0;

}

2) strrev( )

Function: This function returns reverse of given string i.e. if we enter ‘ball’ it will return ‘llab’

Syntax: strrev(string);

Program example:

#include <stdio.h>

#include <string.h>

int main()

{

    char a[10];

    printf("Enter any string");

    scanf("%s",a);

    strrev(a);

    printf("The reverse is %s”,a);

    return 0;

}

3) strlwr( )

Function: This function returns given string in lower case i.e. small letters.

Syntax: strlwr(string);

Program example:

#include <stdio.h>

#include <string.h>

int main()

{

    char a[10];

    printf("Enter any string");

    scanf("%s",a);

    strlwr(a);

    printf("The lower case is %s”,a);

    return 0;

}

4) strupr( )

Function: This function returns given string in upper case i.e. capital letters.

Syntax: strupr(string);

Program example:

#include <stdio.h>

#include <string.h>

int main()

{

    char a[10];

    printf("Enter any string");

    scanf("%s",a);

    strupr(a);

    printf("The upper case is %s”,a);

    return 0;

}

5) strcpy( )

Function: This function copies one string to another i.e. source_string to destination_string

Syntax: strcpy(destination_string,source_string);

Program example:

#include <stdio.h>

#include <string.h>

int main()

{

    char a[10],b[10];

    printf("Enter any string");

    scanf("%s",a);

    strcpy(b,a);

    printf("The copied string is %s”,b);

    return 0;

}

6) strcat( )

Function: This function adds two strings into one.The process of adding strings is known as string concatenation.

Syntax: strcpy(string1,string2);

Program example:

#include <stdio.h>

#include <string.h>

int main()

{

    char a[10],b[10];

    printf("Enter first string");

    scanf("%s",a);

    printf("Enter second string");

    scanf(“%s”,b);

    strcat(a,b);

    printf("The added string is %s”,a);

    return 0;

}

7) strcmp( )

Function: This function compare two strings and return 0 if both string are equal else return -1/1 if not equal.

Syntax: strcmp(string1,string2);

Program example:

#include <stdio.h>

#include <string.h>

int main()

{

    char a[10],b[10];

    Int x;

    printf("Enter first string");

    scanf("%s",a);

    printf("Enter second string");

    scanf(“%s”,b);

    x = strcmp(a,b);

    printf("The compared value is %d”,x);

    return 0;

}

Some important program using string functions

 

WAP to count total number of vowels and consonant

#include <stdio.h>

#include <string.h>

int main()

{   char a[10];

    int y, i, c=0, v=0;

    printf("Enter string");

    scanf("%s",a);

    strlwr(a);

    y= strlen(a);

    for(i=0;i<y;i++)

    {

        if(a[i]=='a' || a[i]=='e' || a[i]=='i' || a[i]=='o' || a[i]=='u')

        {

            printf("Vowel %s",a[i]);

            v=v+1;

        }

        else

        {   printf("Consonant %s",a[i]);

            c=c+1;

        }

    }

    printf("No %d",v);

    printf("No %d",c);

    return 0;

}

WAP to check whether the given string is palindrome or not [MADAM is palindrome]

#include <stdio.h>

#include <string.h>

int main()

{   char a[10],b[10];

    printf("Enter string");

    scanf("%s",a);

    strcpy(b,a)

    strrev(a);

    if(strcmp(a,b)==0)

        {

            printf("%s is palindrome”,b);

        }

        else

        {  

printf("%s is not palindrome”,b);

        }

    return 0;

}

Functions: Functions are the self-contained program that contains several block of statement which performs the defined task. In C language, we can create one or more functions according to the requirements.

 

Usually, In C programs flows from top left to right bottom of main() functions. We can create any number of functions below that main() functions. These function are called from main() function. Requirement while creating a functions.

 

a) Declare a function

 

b) Call statement

 

c) Definition of function.

 

After the function is called from the main(), the flow of control will return to the main() function.

 

Program example of function

 

WAP to calculate simple interest using function

#include <stdio.h>

float interest(void); //function declaration

int main()

{   float si;

    si=interest(); //function call

    printf("Simple interst is %.2f\n",si);

    return 0;

}

float interest() //function definition

{

    float p,t,r,i;

    printf("Enter Principal, Time and Rate");

    scanf("%f%f%f",&p,&t,&r);

    i=(p*t*r)/100;

    return i; //function return value

}

WAP to calculate area of rectangle using function.

#include <stdio.h>

Int area (void);

int main()

{  

                int a;

                a = area();

                printf(“area is %d”,a);

                return 0;

}

int area()

{  

                int l,b,ar;

                printf(“Enter length and breadth”);

                scanf(“%d%d”,&l,&b);

                ar = l*b

                return ar;

}

Advantage:

 

1. Big programs can be divided into smaller module using functions.

 

2. Program development will be faster.

 

3. Program debugging will be easier and faster.

 

4. Use of functions reduce program complexity.

 

5. Program length can be reduced through code reusability.

 

6. Use of functions enhance program readability.

 

7. Several developer can work on a single project.

 

8. Functions are used to create own header file i.e mero.h

 

9. Functions can be independently tested.

 

Recursive functions: (V.Imp)

 

Those function which  calls itself is known as recursive function and the concept of using recursive functions to repeat the execution of statements as per the requirement is known as recursion. The criteria for recursive functions are:

 

The function should call itself.

There should be terminating condition so that function calling will not be for infinite number of time.

Program example of  recursive function

 

WAP to calculate factorial of a given number using recursion/recursive function. (V.IMP)

#include <stdio.h>

int fact (int);

int main()

{

    int n,f;

    printf("Enter any number");

    scanf("%d",&n);

    f = fact(n);

    printf("factorial is %d",f);

    return 0;

}

int fact (int n)

{

    if (n<=1)

        return 1;

    else

        return (n*fact(n-1));

}

WAP to calculate sum of n-natural number using recursion/recursive function.

#include <stdio.h>

int sum (int);

int main()

{

    int n,s;

    printf("Enter any number");

    scanf("%d",&n);

    s = sum(n);

    printf("Sum is %d\n",s);

    return 0;

}

int sum (int n)

{

    if (n<=0)

        return 0;

    else

        return (n+sum(n-1));

}

Pointer (v-imp)

 

Pointers in C are similar to as other variables that we use to hold the data in our program but, instead of containing actual data, they contain a pointer to the address (memory location) where the data or information can be found.

 

These is an important and advance concept of C language since, variables names are not sufficient to provide the requirement of user while developing a complex program. However, use of pointers help to access memory address of that entities globally to any number of functions that we use in our program.

 

Importance of Pointer.

 

While using several numbers of functions in C program, every functions should be called and value should be passed locally. However, using pointer variable, which can access the address or memory location and points whatever the address (memory location) contains.

 

Pointer declaration

 

Data_type *variable_name

 

Eg, int *age;

 

Advantages

 

1. It helps us to access a variable that is not defined within a function.

 

2. It helps to reduce program length and complexity i.e. faster program execution time.

 

3. It is more convenient to handle datas.

 

4. It helps to return one or more than one value from the functions.

 

Program example:

 

#include <stdio.h>

int main()

{

    int n,*ptr;

    printf("Enter any number");

    scanf("%d",&n);

    ptr =&n;

    printf("Value is %d\n",*ptr);

    return 0;

}

No comments:

Post a Comment

OOP

  UNIT 5. Object Oriented Programming (3 marks)     1. What are the programming methods or approaches of program development?   Th...

designs

designs

Pages