Monday, January 3, 2022

UNIT 4. Programming in C

 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>
#include <conio.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>
#include <conio.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:

  1. The function should call itself.
  2. 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 
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 
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 
int main()
{
    int n,*ptr;
    printf("Enter any number");
    scanf("%d",&n);
    ptr =&n;
    printf("Value is %d\n",*ptr);
    return 0;
}

Click here for full details on Pointers 

Q) Differentiate between structure and union (v.imp)

StructureUnion
Keyword used is “struct”Keyword used is “union”
Memory occupied by structure is sum of a memory occupied by individual data type.Memory occupied by union is highest memory occupied by data type among all data type.
Memory allocation is the total sum of all elements.Memory allocation is performed by sharing memory with highest datatype.
Can be used un complex data structure.Cannot be used un complex data structure.
Cannot be used to interact with hardware.Suitable for interacting with hardware.
Example: struct sample{  int a; float p; char n[10] } a;                                   Example: union sample{  int a; float p; char n[10] } a;

File Handling in C

As we know, while program is in execution the content of variables are temporarily stored in main memory i.e. RAM. Data reside temporarily in RAM only at the time of program execution. After the completion of execution data gets erased away which means the data cannot be used for future references. To overcome this problem, file handling comes into existence through which we can store data permanently in our secondary storage and retrieve it whenever in future. Data are stored as datafile in our disk.

File handling in C

Opening a data file

Syntax:

FILE *fptr

fptr = fopen (“filename” , ”mode”)

Where, File name can be “library.txt”, “student.dat” ..etc

Mode:

“w” to write/store data in a data file.

“r” to display/read/retrieve/access data from a datafile.

“a” to add/append data in existing datafile.

Store/write data

Syntax:

fprintf(fptr , ”format specifiers” ,variables);

Eg; suppose if we want to store name, disease, age and bed number of a patient then, it is written as

fprintf(fptr , ”%s %s %d %d”, n, d, a, b);

Where, variable are initialized as:

char n[10], d[10];

int a, b;

Program example

1) Create a datafile “patient.txt” and store name, disease, age and bed number of a patient.

#include 
int main()
{
    char n[10], d[10];
    int a, b;
    FILE *fptr;
    fptr = fopen(“patient.txt”,”w”);
    printf("Enter name, disease, age and bed number");
    scanf(“%s %s %d %d”, n, d, &a, &b);
    fprintf(fptr,"%s %s %d %d\n”, n, d, a, b);
    fclose(fptr);
    return 0;
}

[Note: This program will store only single record to store multiple record we have to use loop as following programs.

2) Create a datafile “student.txt” and store name, class and marks obtained in 3 different subject for few students/n-students.

#include 
int main()
{
    char n[10];
    int c, e, ne, m, i, num;
    FILE *fptr;
    fptr = fopen("student.txt","w");
    printf("How many record?");
    scanf("%d",&num);
    for(i=1;i<=num;i++)
    {
    printf("Enter name class and 3 marks");
    scanf("%s %d %d %d %d",n, &c, &e, &ne, &m);
    fprintf(fptr,"%s %d %d %d %d \n",n, c, e, ne, m);
    }
    fclose(fptr);
    return 0;
}

3) Create a datafile “student.txt” and store name, class and marks obtained in 3 different subject until user press “y” / as per user requirement.

#include 
int main()
{
    char n[10],ch[3];
    int c, e, ne, m;
    FILE *fptr;
    fptr = fopen("student.txt","w");
    do
    {
    printf("Enter name class and 3 marks");
    scanf("%s %d %d %d %d",n, &c, &e, &ne, &m);
    fprintf(fptr,"%s %d %d %d %d\n",n, c, e, ne, m);
    printf("Press Y to continue");
    scanf("%s",ch);
    } while (strcmp(ch,"Y") == 0 || strcmp(ch,"y")==0);
    fclose(fptr);
    return 0;
}

Add/Append data

1) A datafile “student.txt” contain name, class and marks obtained in 3 different subject of few students. Write a C program to add 200 more records.

#include 
int main()
{
    char n[10];
    int c, e, ne, m, i;
    FILE *fptr;
    fptr = fopen("student.txt","a");
    for(i=1;i<=200;i++)
    {
    printf("Enter name class and 3 marks");
    scanf("%s %d %d %d %d", n, &c, &e, &ne, &m);
    fprintf(fptr,"%s %d %d %d %d \n",n, c, e, ne, m);
    }
    fclose(fptr);
    return 0;
}

2) A datafile “student.txt” contain name, class and marks obtained in 3 different subject of few students. Write a C program to add more records until user press “y” / as per user requirement.

#include 
int main()
{
    char n[10], ch[3];
    int c, e, ne, m;
    FILE *fptr;
    fptr = fopen("student.txt”,”a”);
    do
    {
    printf("Enter name class and 3 marks");
    scanf("%s %d %d %d %d", n, &c, &e, &ne, &m);
    fprintf(fptr,"%s %d %d %d %d\n", n, c, e, ne, m);
    printf("Press Y to continue");
    scanf("%s",ch);
    } while (strcmp(ch,"Y") == 0 || strcmp(ch,"y")==0);
    fclose(fptr);
    return 0;
}

Read/Display/retrieve/access data from a datafile

Syntax:

fscanf(fptr , ”format specifiers” ,variables);

Eg; suppose if we want to display/read name, disease, age and bed number of a patient from data file then, it is written as

fscanf(fptr , ”%s %s %d %d”, n, d, &a, &b);

Where, variable are initialized as:

char n[10], d[10];

int a,b;

EOF: End of file

Program example

1) A datafile “student.txt” contain name, class and marks obtained in 3 different subject of few students. Write a C program to read and display all records.

#include 
int main()
{
    char n[10];
    int c, e, ne, m;
    FILE *fptr;
    fptr = fopen("student.txt","r");
    printf("Name\tPercentage\n");
    while(fscanf(fptr,"%s %d %d %d %d",n,&c,&e,&ne,&m) != EOF)
    {      
        printf("%s %d  %d  %d  %d", n, c, e, ne, m);    
    }
    fclose(fptr);
    return 0;
}

2) A datafile “student.txt” contain name, class and marks obtained in 3 different subject of few students. Write a C program to read and display only records whose name is Ram.

#include 
int main()
{
    char n[10];
    int c, e, ne, m;
    FILE *fptr;
    fptr = fopen("student.txt","r");
    while(fscanf(fptr,"%s %d %d %d %d",n,&c,&e,&ne,&m) != EOF)
    {
       strlwr(n);    
       if (strcmp(n,”ram”) == 0)
       {
        printf("%s %d  %d  %d  %d", n, c, e, ne, m);    
       }
    }
    fclose(fptr);
    return 0;
}

3) A datafile “student.txt” contain name, class and marks obtained in 3 different subject of few students. Write a C program to read and display only records who pass in all subjects.

#include 
int main()
{
    char n[10];
    int c, e, ne, m;
    FILE *fptr;
    fptr = fopen("student.txt","r");
    while(fscanf(fptr,"%s %d %d %d %d",n,&c,&e,&ne,&m) != EOF)
    {      
       if (e>=40 && ne>=40 && m>=40)
        {
          printf("%s %d  %d  %d  %d", n, c, e, ne, m);    
        }
    }
    fclose(fptr);
    return 0;
}

4) A datafile “student.txt” contain name, class and marks obtained in 3 different subject of few students. Write a C program to read and display only records who fail in any one subject.

#include 
int main()
{
    char n[10];
    int c, e, ne, m;
    FILE *fptr;
    fptr = fopen("student.txt","r");
    while(fscanf(fptr, "%s %d %d %d %d", n, &c, &e, &ne, &m) != EOF)
    {      
       if (e<40 || ne<40 || m<40)
      {
        printf("%s %d  %d  %d  %d", n, c, e, ne, m);    
      }
    }
    fclose(fptr);
    return 0;
}

5) A datafile “student.txt” contain name, class and marks obtained in 3 different subject of few students. Write a C program to read and display only name and percentage of all students

#include 
int main()
{
    char n[10];
    int c, e, ne, m;
    float p;
    FILE *fptr;
    fptr = fopen("student.txt","r");
    while(fscanf(fptr, "%s %d %d %d %d", n, &c, &e, &ne, &m) != EOF)
    {      
        p = (e+ne+m)/3;
        printf("%s %f", n, p);    
    }
    fclose(fptr);
    return 0;
}

6) A datafile “student.txt” contain name, class and marks obtained in 3 different subject of few students. Write a C program to read and display only records of all students who secure distinction.

#include 
int main()
{
    char n[10];
    int c, e, ne, m;
    float p;
    FILE *fptr;
    fptr = fopen("student.txt","r");
    while(fscanf(fptr, "%s %d %d %d %d", n, &c, &e, &ne, &m) != EOF)
    {      
       p = (e+ne+m)/3;
       if (p>=80)
       {
        printf("%s %d  %d  %d  %d", n, c, e, ne, m);
       }
    }
    fclose(fptr);
    return 0;
}

No comments:

Post a Comment

Class 12 Computer Science MCQ set

  Class 12 Computer Science MCQ set According to the new curriculum and grid of NEB, there is an abrupt change in question pattern. Computer...