Computer Science | UNIT-4 | Programming in C | Class-12

SHARE:

Class-12 Computer Science UNIT 4. Programming in C Functions: Functions are the self-contained program that contains several block of stat...


Class-12
Computer Science

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

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

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

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 data’s.
  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;

}

Pointers with program examples in C

Pointers are almost same as any other variable in C, as we know variables stores values (actual data). However, Instead of containing actual data pointers stores the memory location of that variable where information can be found. This is a very useful and important concept, and many complex programs are designed using pointers.

Contrast of Pointers in C

Variable names are not sufficient to fulfill all the requirements of C program. Specially, when the program are complex and relies on several function. Local variables can be accessed only within their functions. However, memory addresses can be accessed globally by all functions. One function can pass the address of local variable to another function, and the second function can use this address to access the contents of first function's local variable. Hence, we use pointer variable, which can store the address or memory location and points to whatever that memory location holds.

Advantages / Pros / Merits of Pointes in C

  • It provides direct memory access.
  • It helps in global access of data. [I.e. actual data that variable holds can be accessed from outside of the function.]
  • It reduce length and complexity of program.
  • It reduces memory consumption of a program.
  • It increase execution speed.
  • It more efficient to data tables using pointers.
  • It helps to develop complex data structures i.e. stack, queue, list, linked list etc
  • It helps in Dynamic Memory Allocations.

Disadvantages / cons / Demerits of Pointes in C

  • Comparatively, pointers variables are slower than any other variables.
  • Memory leak can be a major issue if dynamically allocated memory are not freed on time.
  • If Pointers variable are not declared that it may lead to segmentation fault.

Why should we use Pointers?

Understanding pointer thoroughly,
Let us consider, an integer variable age which value is 16, which is declared as

int age =16;

This declaration tells the C compiler:

  • To reserve space in memory to hold the integer value.
  • Associate the name ‘age’ with this memory location.
  • Store the value 16 at this location.

[Note: Every value is stored in any memory location.]

We can display this address by following program C program


#include

int main()

{

int age=16;

printf("Address of age is %u”, &age);

printf(“Value of age is %d”, age);

return 0;

}

 

Output of the above program is

Address of age is 65676

Value of age is 16

[Note: &age return memory address, %u denotes unsigned integer generally used for large positive numbers i.e address of age in this case. Memory address may vary with computers. Same program may give different memory location but should give same value]

Declaration of Pointer Variable

Syntax:

datatype *pointer_varible;

For eg:

int *a;

char *b;

float *c;

Simple program example of pointers in C

 

#include

int main()

{

int age=16, *a;

a = &age;

printf("Address of age is %p”, a);

printf(“Value of age is %d”, *a);

return 0;

}

[Note: %p format specifier is used for printing the address to which pointer points in C]

Output of the above program is

Address of age is 65676

Value of age is 16

Explanation of above program

In above program two different operators are used: &(ampersand) and *(asterisk). '&' operator gives the address of the variable associated with it and called "address of” operator. ‘*’ operator gives the value stored at a particular address. It is called "value at address" operator or also called "indirection" operator.

We have declared two integer variable, first age=16 is normal integer variable where as *a is pointer variable. After declaration statement using above mentioned operators we store address of variable age in pointer variable p.

Thus, in output printing ‘a’ result to address of age=16, where as, printing ‘*a’ results to the actual value 16 because pointer variable point to the value at address.

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


Structure

Union

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;

}

COMMENTS

Name

Band TikTok in Nepal,1,Business Studies Notes XII,14,Class 12 Accounting-II Notes,6,Class 12 English Notes,39,Class 12 Nepali Notes,12,Compulsory English : Grade XII,1,Compulsory English XII,40,Computer Science : Grade XII (12),1,Computer Science Notes XII,7,English (Optional),1,Environmental Science,1,Essays,4,Grade XII (12),3,Kheer Recipe,1,Language Development,20,Library and Information Science,1,Model Questions,7,One Act Plays,3,Physics Grade XII (12),1,Poems,5,Recipe,1,Short Stories,7,Subject Table of Contain,1,खीरको रेसिपी,1,
ltr
item
Class 12 Notes Nepal | National Examinations Board(NEB) | +2 Class 12 Question with Solution : Computer Science | UNIT-4 | Programming in C | Class-12
Computer Science | UNIT-4 | Programming in C | Class-12
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjBN8rNB7TM8vWmv6NDF5gBkefQxwY6MAI_3gEE3NA_ScXxY_8LXcfLPDDRRBVAo_PrG_bPtjooGXR9Hu2Qk4Etn10tzhkLjNythVyaK9FL7tCCw3cuEC9si-FLOq1c5_PAj2qG8plEskoq49Agn3gb52l8X0eKeacvJA9PZV9xd7K4zw4TwCxFvW_A/w640-h388/Computer%20Science-Unit-4-Programming%20in%20C.jpg
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjBN8rNB7TM8vWmv6NDF5gBkefQxwY6MAI_3gEE3NA_ScXxY_8LXcfLPDDRRBVAo_PrG_bPtjooGXR9Hu2Qk4Etn10tzhkLjNythVyaK9FL7tCCw3cuEC9si-FLOq1c5_PAj2qG8plEskoq49Agn3gb52l8X0eKeacvJA9PZV9xd7K4zw4TwCxFvW_A/s72-w640-c-h388/Computer%20Science-Unit-4-Programming%20in%20C.jpg
Class 12 Notes Nepal | National Examinations Board(NEB) | +2 Class 12 Question with Solution
https://grade-12notes.blogspot.com/2022/05/computer-science-unit-4-programming-in.html
https://grade-12notes.blogspot.com/
https://grade-12notes.blogspot.com/
https://grade-12notes.blogspot.com/2022/05/computer-science-unit-4-programming-in.html
true
9174492420796559564
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content