Tuesday 5 May 2020

C programming Solution (Function) For Grade XII

Exercises

Theoretical Questions

1.         What is a function? List out the advantages of functions.

A function is a routine or a set of instruction or code that performs a specific task and can be processed independently.

When the program passes control to a function the function perform that task and returns control to the instruction following the calling instruction. The most important reason to use the function is make program handling easier  as only a small part of the program is dealt with at a time.

Advantages of Functions:

i)    The length of  a source program can be reduced by using functions at appropriate places. This factor is particularly critical with microcomputers where memory space is limited.

ii)  It is easy to locate and isolate a faulty function for further investigations.

iii)  A function may be used by many other programs. This means that a C programmer can build on what others have already done, instead of starting all over again from scratch.

iv) It facilitates top-down modular programming. In this programming style, the high level logic of the overall problem is solved first while the details of each lower-level function are addressed later.

2.         What do you mean by library function? How list is it different from user-defined function ? or

            What is the difference between a library funciton and user-defined function ?

 

Library functions are pre defined functions. Inorder to ease the work of the user, the developer provides some built in functions. For some operations we need not write our own code. We can simply use one of those library functions to get our work done.

The difference between the library and user-defined functions is that we do not need to write a code for a library function. It is already present inside the header file which we always include at the beginning of a program. You just have to type the name of a function and use it along with the proper syntax. Printf, scanf are the examples of a library function.

 

Whereas, a user-defined function is a type of function in which we have to write a body of a function and call the function whenever we require the function to perform some operation in our program.

 

A user-defined function is always written by the user, but later it can be a part of 'C' library. It is a major advantage of 'C' programming.

 

3.         What are the different components of functions? Explain.

 

A function usually has three components. They are:

 

1.    Function Prototype/Declaration:

Function declaration is a statement that informs the compiler about

 

Name of the function

Type of arguments

Number of arguments

Type of Return value

Syntax for function declaration

 

returntype function_name ([arguments type]);

2.    Function Definition:

Function definition consists of the body of function. The body consists of block of statements that specify what task is to be performed. When a function is called, the control is transferred to the function definition.

Syntax for function definition:

returntype function_name ([arguments])

{

    statement(s);

    ... ... ...

}

Return Statement

A return statement is used to return values to the invoking function by the invoked function. The data type of value a function can return is specified during function declaration. A function with void as return type don't return any value. Beside basic data type, it can return object and pointers too. A return statement is usually place at the end of function definition or inside a branching statement.

Syntax of return statement

return value;

 

3.    Function Call:

A function call can be made by using a call statement. A function call statement consists of function name and required argument enclosed in round brackets.

Syntax for function call

 

function_name ([actual arguments]);

4.         Explain different types of user-defined functions with an example.

 

Ø  There can be 4 different types of user-defined functions, they are:

 

1.    Function with no arguments and no return value

Such functions can either be used to display information or they are completely dependent on user inputs.

Ex:

#include<stdio.h>

 

void greatNum();       // function declaration

 

int main()

{

    greatNum();        // function call

    return 0;

}

 

void greatNum()        // function definition

{

    int i, j;

    printf("Enter 2 numbers that you want to compare...");

    scanf("%d%d", &i, &j);

    if(i > j) {

        printf("The greater number is: %d", i);

    }

    else {

        printf("The greater number is: %d", j);

    }

}

 

2.    Function with no arguments and a return value

In this method, We won’t pass any arguments to the function while defining, declaring, or calling the function. This type of function will return some value when we call the function from main() or any sub function.

Ex:

#include<stdio.h>

 

int greatNum();       // function declaration

 

int main()

{

    int result;

    result = greatNum();        // function call

    printf("The greater number is: %d", result);

    return 0;

}

 

int greatNum()        // function definition

{

    int i, j, greaterNum;

    printf("Enter 2 numbers that you want to compare...");

    scanf("%d%d", &i, &j);

    if(i > j) {

        greaterNum = i;

    }

    else {

        greaterNum = j;

    }

    // returning the result

    return greaterNum;

}

 

3.    Function with arguments and no return value

This method allows us to pass the arguments to the function while calling the function. But, This type of function will not return any value when we call the function from main () or any sub function.

Ex:

#include<stdio.h>

 

void greatNum(int a, int b);       // function declaration

 

int main()

{

    int i, j;

    printf("Enter 2 numbers that you want to compare...");

    scanf("%d%d", &i, &j);

    greatNum(i, j);        // function call

    return 0;

}

 

void greatNum(int x, int y)        // function definition

{

    if(x > y) {

        printf("The greater number is: %d", x);

    }

    else {

        printf("The greater number is: %d", y);

    }

}

 

4.    Function with arguments and a return value

This Types of Functions in C program allows the user to enter 2 integer values. And then, We are going to pass those values to the user-defined function to multiply those values and return the value using the return keyword.

Ex:

#include<stdio.h>

 

int greatNum(int a, int b);       // function declaration

 

int main()

{

    int i, j, result;

    printf("Enter 2 numbers that you want to compare...");

    scanf("%d%d", &i, &j);

    result = greatNum(i, j); // function call

    printf("The greater number is: %d", result);

    return 0;

}

 

int greatNum(int x, int y)        // function definition

{

    if(x > y) {

        return x;

    }

    else {

        return y;

    }

}

5.         Explain recursive function with an example.

A function that calls itself is known as a recursive function. And, this technique is known as recursion. This enables the function to repeat itself several times, outputting the result and the end of each iteration. Below is an example of a recursive function.

Ex: The following example calculates the factorial of a given number using a recursive function

#include <stdio.h>

 

unsigned long long int factorial(unsigned int i) {

 

   if(i <= 1) {

      return 1;

   }

   return i * factorial(i - 1);

}

 

int  main() {

   int i = 12;

   printf("Factorial of %d is %d\n", i, factorial(i));

   return 0;

}

 

Practical based Questions

1.         Write a c program to input a number and calculate its reverse using function.

#include<stdio.h>

 int findReverse(int n)

 {

   int sum=0;

   while (n!=0)

   {

     sum = sum*10 + n%10;

     n /= 10;

   }

   return sum;

 }

 

 int main()

 {

   int number, reverse;

 

   printf("Enter a positive interger: ");

   scanf("%d", &number);

 

   reverse = findReverse(number);

 

   printf("The reverse of %d is: %d", number, reverse);

 

   return 0;

 }

2.         Write a c program to find the sum of ‘n’ integer numbers using the function.

#include<stdio.h>

int sum(int n)

{

   int add = 0;

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

   {

     add += i;

   }

   return add;

}

int main()

{

   int range, result;

   printf("Upto which number you want to find sum: ");

   scanf("%d", &range);

   result = sum(range);

   printf("1+2+3+….+%d+%d = %d",range-1, range, result);

}

3.         Write a c program to input a number and check if it is even or odd using the function.

#include <stdio.h>

int isEven(int num)

{

    return !(num & 1);

}

 

 

int main()

{

    int num;

    printf("Enter any number: ");

    scanf("%d", &num);

    if(isEven(num))

    {

        printf("The number is even.");

    }

    else

    {

        printf("The number is odd.");

    }

   

    return 0;

}

 

4          Write a c program to input principle, rate and time and calculate simple interest using the function.

#include<stdio.h>

void main()

{

float p;

int t,r;

printf(“Enter principal:\n”);

scanf(“%d”,&p);

printf(“Input rate of interest:\n”);

scanf(“%d”,&r);

printf(“Enter time in years:\n”);

scanf(“%d”,&t);

printf(“simple interest =rs. %f”,simple (p, r, t));

}

// simple interest function

float simple(float p, int r, int t)

{

float si=(p * r * t) / 100;

return (si);

}

 

5.         Write a c program to store Kathmandu Valley’s 7 days maximum and minimum temperature (in centigrade) and callculate the average, maximum, minimum temerature using funciton and print 7 days temperature, miimum, maximum and average temperature using any high-level programming language.

6.         Write a c program to calculate the factorial of a given number using functions.

#include<stdio.h>

#include<math.h>

void main()

{

    //clrscr();

    printf("Enter a Number to Find Factorial: ");

    fact();

    getch();

}

fact()

{

    int i,fact=1,n;

    scanf("%d",&n);

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

    {

        fact=fact*i;

    }

    printf("\nFactorial of a Given Number is: %d ",fact);

    return fact;

}

7.         Write a c program using a user-defined function to calculate y raise to power x.

 

#include <stdio.h>

#include <conio.h>

#include <math.h>

long int yraisex(int, int);

void main()

{

int bese,exp;

long int result;

clrscr();

pr1ntf(”\n Input base and exponent values:-);

scanf("%d%d",&base,&exp);

result=yraisex(base,exp);

printf("\n Result = %ld",result);

getch();

long int yraisex(int x,int y)

{

long int z;

z=pow(x,y);

return (z);

}

 

8.         Write a c program to calculate a term of Fibonaci series using a recursive function.

#include<stdio.h>

 

int Fibonacci(int);

 

int main()

{

   int n, i = 0, c;

 

   scanf("%d",&n);

 

   printf("Fibonacci series\n");

 

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

   {

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

      i++;

   }

 

   return 0;

}

 

int Fibonacci(int n)

{

   if ( n == 0 )

      return 0;

   else if ( n == 1 )

      return 1;

   else

      return ( Fibonacci(n-1) + Fibonacci(n-2) );

}

 

9.         Write a c program to calculate the factorial of a given number using recursive function.

#include<stdio.h>

long int multiplyNumbers(int n);

int main() {

    int n;

    printf("Enter a positive integer: ");

    scanf("%d",&n);

    printf("Factorial of %d = %ld", n, multiplyNumbers(n));

    return 0;

}

 

long int multiplyNumbers(int n) {

    if (n>=1)

        return n*multiplyNumbers(n-1);

    else

        return 1;

}

 

10        Write a c program with function and input menu from the keyboard and activate these functions:

            i. print area of a circle ( )

            ii. reverse string()

#include<stdio.h>

#include<conio.h>

#include<string.h>

#include<math.h>

float area(int r)

{

return(22*r*r)/7;

}

void reverse(char c);

void main()

{

int r,choice;

char c[25];

float result;

clrscr();

printf("enter 1 for area. 2 for reverse\n");

printf("enter your choice:");

scanf("%d",&choice);

switch(choice)

{

case 1: {

printf("enter the radius:");

scanf("%d",&r);

result=area(r);

printf("the area of circle is %f",result);

break;

}

case 2: {

printf("enter the strin:g");

scanf("%s",&c);

strrev(c);

printf("the reversed string is: %s",c);

break;

}

default:

printf("wrong input");

}

getch();

}

 

end

 

Exercises

Theoretical Questions

1.         Define the term pointer with its key features.

A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before using it to store any variable address. The general form of a pointer variable declaration is −

 

type *var-name;

 

Uses and features of pointer:

 

Ø  Pointers provide direct access to memory

Ø  It provides a way to return more than one value to the function.

Ø  Reduces the storage space and complexity of the program.

Ø  Reduces the execution time of the program.

Ø  Provides an alternative way to access array elements.

Ø  It allows us to perform the dynamic memory allocation.

2.         Write down the advantages and disadvantages of using a pointer.

 

Advantages

·         Pointers provide direct access to memory

·         Pointers provide a way to return more than one value to the functions

·         Reduces the storage space and complexity of the program

·         Reduces the execution time of the program

·         Provides an alternate way to access array elements

·         Pointers can be used to pass information back and forth between the calling   function and called function.

Disadvantages

·         Uninitialized pointers might cause segmentation fault.

·         Dynamically allocated block needs to be freed explicitly.  Otherwise, it would lead to memory leak.

·         Pointers are slower than normal variables.

·         If pointers are updated with incorrect values, it might lead to memory corruption.

3.         What do you mean by the term address of (&) and indirection (*) operator?

The address operator (&) can be used with an lvalue, such as a variable, as in &var. This expression yields the address of variable var, i.e., a pointer to it. Note that the address operator cannot be used with constants and non-lvalue expressions. Thus, the expressions &100,&(a+5) and &'X' are invalid. If the type of variable var is T, the expression &var returns a value of type T *,i.e., a pointer to type T.

We can use the addressoperator to obtain its address, whatever it may be. This address can be assigned to a pointervariable of appropriate type so that the pointer points to that variable.

The dereference/indireciton operator (*) is a unary prefix operator that can be used with any pointer variable, as in *ptr_var. This expression yields the value of the variable pointed at by that pointer. Although the symbol for the dereference operator is the same as that of the multiplication operator, its use is unambiguous from the context as the latter is a binary infix operator used, as in expr1 * expr2.

 

4.         Explain the importance of pointer in C programming. Illustrate pointer operations with an example. Show the relation between array and pointers with example.

The importance of pointer is given bellow:-

Ø  It is more efficient to handling data stored in array or table.

Ø  Pointer can be used to turn multiple values from a function via function arguments.

Ø  Pointer permits references to functions and there by facilitating passing from function as arguments to other functions.

Ø  Pointer allows dynamic memory management.

Ø  It provides an efficient to manage structures, link list, stacks and binary trees.

Ø  It reduces length and complexity of program.

Ex:

#include <stdio.h>

int main()

{

   int num = 10;

   printf("Value of variable num is: %d", num);

printf("\nAddress of variable num is: %p", &num);

   return 0;

}

 

Arrays and pointers are closely related in C. In fact an array declared as int A[10];

can be accessed using its pointer representation. The name of the array A is a constant pointer to the first element of the array. So A can be considered a const int*. Since A is a constant pointer, A = NULL would be an illegal statement. Arrays and pointers are synonymous in terms of how they use to access memory. But, the important difference between them is that, a pointer variable can take different addresses as value whereas, in case of array it is fixed.

 

Ex:

#include <stdio.h>

int main() {

  int i, x[6], sum = 0;

  printf("Enter 6 numbers: ");

  for(i = 0; i < 6; ++i) {

      scanf("%d", x+i);

      sum += *(x+i);

  }

  printf("Sum = %d", sum);

  return 0;

}

 

5.         Differentiate between structures and pointers with example.

Structures are basically “named data records”.

The structure is a “blueprint” of how to store the data in memory, the pointer is the location of the data in memory

 an example would be for a “person” structure, you might have:

struct person

{

    int dateOfBirth;

    char * firstName;

          char * lastName;

          int socialSecurityNumber;

};

Whereas,

A pointer is the address of that structure (or anything else) in memory.

The idea of a pointer is that rather than pass the data around your program, you pass the location of the data.

 

6.         What are the differences between array and pointer?

Difference between Arrays and pointers

 

Array

Pointer

·         An array is a single, pre-allocated chunk of contagious element (all the same type), fixed in size and location. 

·         A pointer is a place in memory that keeps the address of another place inside. 

·         They are static in nature. Once the memory is allocated, it cannot be resized or freed dynamically according to users requirement.

·         Pointer is dynamic in nature. The memory allocation can be resized or freed later at any point in time. 

·         Arrays are allocated at compile time i.e at the time when programmer is writing program

·         Pointers are allocated at runtime i.e after executing program. 

·         An array size decides the number of variables it can store. 

·         A pointer variable can store the address of only one variable. 

 

7.         Differentiate between call by value and call by reference.

Call by value

call by reference

·         While calling a function, when you pass values by copying variables, it is known as "Call By Values."

·         While calling a function, in programming language instead of copying the values of variables, the address of the variables is used it is known as "Call By References.

·         In this method, a copy of the variable is passed.

·         In this method, a variable itself is passed.

·         Does not allow you to make any changes in the actual variables.

·         Allows you to make changes in the values of variables by using function calls.

·         Original value not modified

·         The original value is modified.

 

Practical based Questions

1.         Write a c program to calculate two numbers using pointers.

#include <stdio.h>

int main()

{

   int first, second, *p, *q, sum;

 

   printf("Enter two integers to add\n");

   scanf("%d%d", &first, &second);

 

   p = &first;

   q = &second;

 

   sum = *p + *q;

 

   printf("Sum of the numbers = %d\n", sum);

 

   return 0;

}

 

2.         Write a c program to  calculate factorial of given numbers using pointers.

#include<stdio.h>

 #include<conio.h>

void findFactorial(int,int *);

int main(){

  int i,factorial,num;

 

  printf("Enter a number: ");

  scanf("%d",&num);

 

  findFactorial(num,&factorial);

  printf("Factorial of %d is: %d",num,*factorial);

 

  return 0;

}

 

void findFactorial(int num,int *factorial){

    int i;

 

    *factorial =1;

 

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

      *factorial=*factorial*i;

}

Getch();

}

3.         Write a c program to swap two numbers using call by reference.

#include <stdio.h>

 #include<conio.h>

void swap(int*, int*);

 

int main()

{

   int x, y;

   printf("Enter the value of x and y\n");

   scanf("%d%d",&x,&y);

 

   printf("Before Swapping\nx = %d\ny = %d\n", x, y);

   swap(&x, &y);

 

   printf("After Swapping\nx = %d\ny = %d\n", x, y);

 

   return 0;

}

 

void swap(int *a, int *b)

{

   int temp;

 

   temp = *b;

   *b = *a;

   *a = temp;  

}

Getch();

}

4.         Write a c program to input principle, rate and time and calculate simple interest suing pointers.

 

#include<stdio.h>

#include<conio.h>

void main()

{

 float p,r,t,si,*p1,*p2,*p3;

 clrscr();

 p1=&p;

 p2=&r;

 p3=&t;

 printf("Enter principal amount: ");

 scanf("%f",p1);

 printf("Enter rate of interest: ");

 scanf("%f",p2);

 printf("Enter time: ");

 scanf("%f",p3);

 si=(*p1**p2**p3)/100;

 printf("\n\nSimple Interest = %f",si);

 getch();

}

 

5.         Write a c program to check whether a number is even or odd using pointers.

#include<stdio.h>

#include<conio.h>

void main()

{

  int a;

  int *p1;

 

  p1=&a;

  clrscr();

  printf("Enter The Number You Want to Check \n\n");

  scanf("%d",&a);

 

 if(*p1%2==0)

  {

  printf("Number Is even \n");

 }

  else

  {

  printf("Number Is odd\n");

 }

  getch();

 

}

 

6.         Write a c program to input a number, calculate its square and display the memory address of the inputted number and the square.

#include<stdio.h>

#include<conio.h>

void main()

{

int num;

int square;

clrscr();

printf("enter the number:");

scanf("%d",&num);

square=num*num;

printf("the square of %d is %d\n",square);

printf("the address of num is %p\n",&num);

getch();

}

 

 

7.         Write a c program to input a number and display its multiplication table using pointers.

# include < stdio.h >

int  main( )

{

int  num, i ;

int  *ptr ;

printf(" Enter the number for Print multiplicaiton Table: ") ;

scanf("%d ",& num) ;

ptr = &num ;

printf("\n Multiplicaiton Table of %d are :\n",num) ;

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

{

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

}

return ( 0 );

}

Exercises

Theoretical Questions

1.         What is a data file? Write down the syntax to create a new file.

A data file is generally used as real-life applications that contain a large amount of data.

C programming provides built-in support to create, read, write and append data to file. To perform any operation on file we use a built-in FILE structure. You need to create pointer to FILE type.

Syntax:

FILE * fPtr;

 

2.         List our all the file manipulation functions with examples of each.

There are 4 basic operations that can be performed on any files in C programming language. They are,

1.    Opening/Creating a file

2.    Closing a file

3.    Reading a file

4.    Writing in a file

 

fopen() – To open a file

          Declaration: FILE *fopen (const char *filename, const char *mode)

fopen() function is used to open a file to perform operations such as reading, writing etc. In a C program, we declare a file pointer and use fopen() as below. fopen() function creates a new file if the mentioned file name does not exist.

 

FILE *fp;

fp=fopen (“filename”, ”‘mode”);

 

Where,

fp – file pointer to the data type “FILE”.

filename – the actual file name with full path of the file.

mode – refers to the operation that will be performed on the file. Example: r, w, a, r+, w+ and a+. Please refer below the description for these mode of operations.

 

fclose() – To close a file    

Declaration: int fclose(FILE *fp);

fclose() function closes the file that is being pointed by file pointer fp. In a C program, we close a file as below.

fclose (fp);

 

fgets() – To read a file      

Declaration: char *fgets(char *string, int n, FILE *fp)

fgets function is used to read a file line by line. In a C program, we use fgets function as below.

fgets (buffer, size, fp);

 

where,

buffer – buffer to  put the data in.

size – size of the buffer

fp – file pointer

 

fprintf() – To write into a file       

Declaration:int fprintf(FILE *fp, const char *format, …);

fprintf() function writes string into a file pointed by fp. In a C program, we write string into a file as below.

fprintf (fp, “some data”); or

fprintf (fp, “text %d”, variable_name);

 

3.         Write the functions of rename () and remove () with example.

The remove( ) and rename( ) functions in the stdio.h library

can be used to manipulate files. 

The remove( ) function deletes a file from memory.

 

//Remove a file

Using remove() function in C, we can write a program which can destroy itself after it is compiled and executed.

 

#include<stdio.h>

#include<stdlib.h>

 

int main(int c, char *argv[])

{

          printf("By the time you will compile me I will be destroyed \n");

         

          remove(argv[0]);    

         

return 0;

}

 

// This code is contributed by MAZHAR IMAM KHAN.

 

The rename( ) function takes the name of a file as its argument, and the new name of the file as a second argument.  For example,  rename("myfile.dat", "newfile.dat");  renames the file myfile.dat as newfile.dat.  The rename( ) function also requires C-style string arguments.

 

// C program to demonstrate use of rename()

#include<stdio.h>

 

int main()

{

          // Old file name

          char old_name[] = "geeks.txt";

 

           

          char new_name[] = "geeksforgeeks.txt";

          int value;

          value = rename(old_name, new_name);

          if(!value)

          {

                   printf("%s", "File name changed successfully");

          }

          else

          {

                   perror("Error");

          }

          return 0;

}

 

4.         Explain the functions of fprint() and fscanf() with example.

The fprintf() function is used to write set of characters into file. It sends formatted output to a stream.

Ex:

#include <stdio.h> 

main(){ 

   FILE *fp; 

   fp = fopen("file.txt", "w");//opening file 

   fprintf(fp, "Hello file by fprintf...\n");//writing data into file 

   fclose(fp);//closing file 

} 

 

The fscanf() function is used to read set of characters from file. It reads a word from the file and returns EOF at the end of file.

 

#include <stdio.h> 

main(){ 

   FILE *fp; 

   char buff[255];//creating char array to store data of file 

   fp = fopen("file.txt", "r"); 

   while(fscanf(fp, "%s", buff)!=EOF){ 

   printf("%s ", buff ); 

   } 

   fclose(fp); 

} 

 

5.         Define the terms FILE and EOF in file handling.

The collection of different data or information or instructions wich is stored in secondary storage devices under a unique file name is known as file.

 

End Of File or EOF is a specific designation for a file marker that indicates the end of a file or data set.

6.         Describe any five ‘file handling function’ with examples.

File handling is a process to create a data file, write data to the data file and read data from the specified data file.

fopen():The fopen() function is used to open a file and associates an I/O stream with it. This function takes two arguments. The first argument is a pointer to a string containing name of the file to be opened while the second argument is the mode in which the file is to be opened.

Syntax:

FILE *fopen(const char *path, const char *mode);

fread()and fwrite():The functions fread/fwrite are used for reading/writing data from/to the file opened by fopen function. These functions accept three arguments. The first argument is a pointer to buffer used for reading/writing the data. The data read/written is in the form of ‘nmemb’ elements each ‘size’ bytes long.

Syntax:

size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);

 

size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);

 

fseek():The fseek() function is used to set the file position indicator for the stream to a new position. This function accepts three arguments. The first argument is the FILE stream pointer returned by the fopen() function. The second argument ‘offset’ tells the amount of bytes to seek. The third argument ‘whence’ tells from where the seek of ‘offset’ number of bytes is to be done. The available values for whence are SEEK_SET, SEEK_CUR, or SEEK_END.

Syntax

int fseek(FILE *stream, long offset, int whence);

 

fclose():The fclose() function first flushes the stream opened by fopen() and then closes the underlying descriptor. Upon successful completion this function returns 0 else end of file (eof) is returned. In case of failure, if the stream is accessed further then the behavior remains undefined.

Syntax:

int fclose(FILE *fp);

 

ex:

#include<stdio.h>

#include<string.h>

 

#define SIZE 1

#define NUMELEM 5

 

int main(void)

{

    FILE* fd = NULL;

    char buff[100];

    memset(buff,0,sizeof(buff));

 

    fd = fopen("test.txt","rw+");

 

    if(NULL == fd)

    {

        printf("\n fopen() Error!!!\n");

        return 1;

    }

 

    printf("\n File opened successfully through fopen()\n");

 

    if(SIZE*NUMELEM != fread(buff,SIZE,NUMELEM,fd))

    {

        printf("\n fread() failed\n");

        return 1;

    }

 

    printf("\n Some bytes successfully read through fread()\n");

 

    printf("\n The bytes read are [%s]\n",buff);

 

    if(0 != fseek(fd,11,SEEK_CUR))

    {

        printf("\n fseek() failed\n");

        return 1;

    }

 

    printf("\n fseek() successful\n");

 

    if(SIZE*NUMELEM != fwrite(buff,SIZE,strlen(buff),fd))

    {

        printf("\n fwrite() failed\n");

        return 1;

    }

 

    printf("\n fwrite() successful, data written to text file\n");

 

    fclose(fd);

 

    printf("\n File stream closed through fclose()\n");

 

    return 0;

}

 

7.         Write a program which reads name, roll-number and age from a file named “student.dat” and display them.

 

#include <stdio.h>

#include <conio.h>

void main ()

{

char name [30], add [20],

long int phone;

FILE *fp;

fp = fopen ("STUD.DAT", "w+");

 

for (I = 0; i<5; i++)

{

printf ("Enter anme : /n");

scanf ("%s", name [i]);

printf ("Enter address : /n");

scanf ("%s", add [i]);

printf ("Enter phone : /n");

scanf ("%ld", &phone [i]);

fprintf (fp, "%s%s%d", name[i],phone[i]);

}

rewind (fp); //Sets the file pointer at the beginning of a file

for (I = 0; i<5; i++)

{

fscanf (fp, "%s %s %ld', name, add, &phone);

printf ("Name = %s /t Address = %s /t phone = % /d", name [i], add [i], phone [i];

}

fclose (fp);

getch ();

}

 

8.         Describe fscanf and fprintf function.

Refer question number 4

 

Practical based Questions

1.         Write a program in C for writing data in the file.

#include<stdio.h>

#include<conio.h>

 

void main()

{

    FILE *fptr;

    char name[20];

    int age;

    float salary;

    fptr = fopen("emp.txt", "w");

 

    if (fptr == NULL)

    {

        printf("File does not exist.\n");

        return;

    }

    printf("Enter the name:\n");

    scanf("%s", name);

    fprintf(fptr, "Name  = %s\n", name);

 

    printf("Enter the age:\n");

    scanf("%d", &age);

    fprintf(fptr, "Age  = %d\n", age);

 

    printf("Enter the salary:\n");

    scanf("%f", &salary);

    fprintf(fptr, "Salary  = %.2f\n", salary);

 

    fclose(fptr);

}

 

2.         Write a c program to show data writing and reading operation to/from a data file.

#include <stdio.h>

#include <stdlib.h>

#define DATA_SIZE 1000

int main()

{

    char data[DATA_SIZE];

    FILE * fPtr;

    fPtr = fopen("data/file1.txt", "w");

    if(fPtr == NULL)

    {

printf("Unable to create file.\n");

        exit(EXIT_FAILURE);

    }

    fgets(data, DATA_SIZE, stdin);

    fputs(data, fPtr);

    fclose(fPtr);

    printf("File created and saved successfully. :) \n");

return 0;

}

3.         Write a c program to enter name, roll-number and marks of 10 students and store them in the file.

#include<stdio.h>

#include<conio.h>

Void main()

{

File *fp;

Char name[10][20];

Int roll_number[10], marks[10];

Int I, n;

Fp=fopen("c:\play.dat","w");

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

{

Printf("enter roll number:");

Scanf("%d", &roll_number[i]);

Printf("enter name");

Scanf("%s", name[i]);

Printf("enter marks");

Scanf("%d", &marks[i]);

Fprintf(fp, %d %s %d", roll_number[i], name[i], marks[i]);

}

Fclose(fp);

Getch();

}

 

4.         Write a c program to store std-no, name and mark of ‘n’ students in a data file. Display the records in appropriate format reading from the file.

#include <stdio.h>

#include <conio.h>

#define MAX 500

void main()

{

FILE *fp;

int std_no[MAX],marks[MAX];

char name[MAX] [20];

int i,n;

printf("How many data?");

scanf("%d",&n);

fp=fopen("record.dat","w+");

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

{

printf("Enter roll number:");

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

fflush(stdin);

printf("Enter name");

scanf("%s",name[i]);

print("Enter marks:");

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

fprint(fp, "%d%s%d", std_no[i],marks[i]);

}

rewind (fp);

printf("Roll number/tName/tMarks/n");

printf("------------------------/n");

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

{

fscanf(fp, "%d%s%d",&std_no[i],name[i],&marks[i]);

printf("%d/r%s/t%d/n",std_no[i],name[i]marks[i]);

}

fclose(fp);

getch();

}

 

5.      Write a c program using C language that reads successive records from the new data file and display each record on the screen in an appropriate format.

#include<stdio.h>

#include<conio.h>

struct student

{

char name[30];

int roll,age;

}s;

 

void main()

{

FILE *ptr;

char choice;

clrscr();

ptr=fopen("record.txt","w");

do

{

printf("\n Input name:-");

gets(s.name);

printf("\n Input roll number and age:-");

scanf("%d%d",&s.roll,&s.age);

fwrite(&s,sizeof(s),1,ptr);

fflush(stdin);

printf("\n Any more record:-");

choice==getche();

}while(choice=='y'||choice=='Y');

fclose(ptr);

ptr=fopen("record.txt","r");

printf("\n Name \t Roll \t Age");

while(fread(&S,sizeof(s),1,ptr)==1)

printf("\n %s \t %d \t %d",s.name,s.roll,s.age);

fclose(ptr);

getch();

}

6.         Write a c program to rename and delete a data file using rename and remove command.

#include<stdio.h>

#include<conio.h>

#include<string.h> 

struct student

{int roll;

char name[30];

}s;

 void main() {

char temp_name[30];

FILE *ptr1;

FILE *ptr2;

clrscr();

ptr1=fopen("student.txt","r");

ptr2=fopen("temp.txt","w");

printf("\n Input name to deleted:-");

gets(temp_name);

while(fscanf(ptr1,"%d%s",&s.roll,s.name)!=EOF)

{

if(strcmp(temp_name,s.name)==0)

fprintf(ptr2,"%d\t%s",s.roll,s.name);

}

fclose(ptr1);

remove("student.txt");

rename("temp.txt","student.txt");

fclose(ptr2);

getch();

}

7.         Write a c program to open a new file and read roll-no, name, address and phone number of students until the user says “no”, after reading the data, write it to the fie then display the content of the file.

#include<stdio.h>

#include<conio.h>

struct student

{

char name[30],address[50];

int roll;

long int phone;

}s;

 

void main() {

FILE *ptr;

char choice;

clrscr();

ptr=fopen("record.txt","w");

do

   {

  printf("\n Input Name:-");

  gets(s.name);

printf("\n input address");

gets(s.address);

printf("\n Input roll number and phone number:-");

scanf("%d%1d",&s.roll,s.phone);

fwrite(&s,sizeof(s),1,ptr);

fflush(stdin);

printf("\n Any more record:- ");

choice==getche();

}

while(choice=='y'||choice=='Y');

fclose(ptr);

ptr=fopen("record.txt","r");

printf("\n Name \t Address \t Roll \t Phone");

while(fread(&s,sizeof(s),1,ptr)==1)

  printf("\n%s \t %s \t %d \t %1d",s.name,s.address,s.roll,s.phone);

fclose(ptr);

getch();

}

 

8.         Write a c program which asks name, age, roll number of student and write it in a file student.dat.

#include <stdio.h>

#include <conio.h>

void main ()

{

char name [30], add [20],

long int phone;

FILE *fp;

fp = fopen ("STUD.DAT", "w+");

 

for (I = 0; i<5; i++)

{

printf ("Enter anme : /n");

scanf ("%s", name [i]);

printf ("Enter address : /n");

scanf ("%s", add [i]);

printf ("Enter phone : /n");

scanf ("%ld", &phone [i]);

fprintf (fp, "%s%s%d", name[i],phone[i]);

}

rewind (fp); //Sets the file pointer at the beginning of a file

for (I = 0; i<5; i++)

{

fscanf (fp, "%s %s %ld', name, add, &phone);

printf ("Name = %s /t Address = %s /t phone = % /d", name [i], add [i], phone [i];

}

fclose (fp);

getch ();

}

 

 

v  17.            Write an algorithm, flowchart, and C program that checks whether the number entered by the user is exactly divisible by 5 but not by 11.

#include<stdio.h>

#include<conio.h>

 void main()

{

int num;

clrscr();

printf("\n Input a number:-");

scanf("%d",&num);

if(num%5==0&&num%11!=0)

printf("\n The number %d is exactly divisible by 5 but not by 11",num);

else

printf

printf("\n The number %d is not required number",num);

getch();

}


No comments:

Post a Comment

MCQ Question Bank Microsoft PowerPoint