Chapter 4: Programming in C

What is C? Explain its development process.

C is a high level language because no need for any architecture knowledge in normal English form. C is a compiler because it can translate the whole program at a time so we can call compiler. C is structured  programming language. It is called also procedural oriented programming language, function oriented  language, module programming language. It is simple, reliable and easy to use.

What are the features of C? What are its advantages and disadvantages?

C is a computer language and a programming tool which has grown popular because programmers  preferred it. It is a tricky language but a masterful one.

The C programming languages has the following features:

  1. It has small size.
  2. It has extensive use of function call.
  3. It is a strong structural language having powerful data definition methods.
  4. It has low level (Bitwise) programming available.
  5. It can handle low level activities.
  6. Pointer makes it very strong for memory manipulations.
  7. It has level constructors.
  8. It can produce efficient programs.
  9. It can be compiled on variety of computers.

Advantage of C language:

⮚  It is machine independent programming language.

⮚  It is easy to learn and implement C language.

⮚  It can be implemented from mobile device to mainframe computers.

⮚  It is the mother of all modern programming language.

Disadvantage of C Language:

⮚  There is no runtime checking.

⮚  It has poor error detection systems.

⮚  On large programs, it is hard to fix errors.

⮚  It does not support modern programming methodologies oriented programming language.

What is preprocessor? Explain with its types.

The compiler of C has a preprocessor built into it. Lines that begin with # are called pre-processor  directives. Each C program must start with proper header files (i.e.<stdio.h>) starting with ‘#’, sign, ‘include’  and a header file name enclosed within triangle brackets.

What is header file? List the header files with some functions, where are they used?

A file that is defined to be included at the beginning of a program in C language that contains the  definitions of data types and declarations of variables used by the functions in the program is called header  file.

  1. Header files commonly contain forward declarations of classes, subroutines, variables, and other identifiers.
  2. The header file in c is called standard library functions.
  3. The entire header file has the extension .h
  4. A header file is used to define constants, variables, macros and functions that may be common to several applications.
  5. The updating and reading data of any function can be performed by using the header files.

Some of the frequent used header files are explain below:

S.N. Header File Description Main Functions
1. stdio.h Standard input and output fpen(), fclose(), rename(), gets(), puts(),  getchar(), scanf(), printf() etc.
2. conio.h Old MS-DOS compiler header file,  used for console input & output. getch(), getche()
3. math.h Mathematical calculation in C  program. sin(x), cos(x), log(x), pow(x,2), sqrt(x),  cbrt(x), ceil(x), floor(x) etc.
4. complex.h Complex arithmetic cpow(x,p), csqrt(x), ctan(x), ctanh(x),  cabs(x)
5. string.h String / Words manipulation  function strlen(y), strcpy(z,y), strcmp(z,y),  strcat(z,y), strupr(y), strlwr(y) etc.
6. ctype.h Character manipulation type  header file toupper(y), tolower(y), isupr(y), isspace(),

isalnu(y), toascii(y) etc.

7. stdlib.h General purpose standard  library. rand(), malloc(), calloc(), abort(), exit()  abs(), free() etc.

Fundamentals of C

  1.  What are the character set used in C?

A group of alphabetic, numeric and other characters that have some relationship with C programming  language and recognized by compiler is called Character set. A character set can also contain additional  characters with other code values.

The keywords, identifiers and other variables are constructed by using character set. The character set  consists of following elements.

 

   2. Define the term identifier, keywords and Tokens.

Identifiers:- Identifiers can be defined as the name of the variables, functions, arrays, structures etc  created by the programmer. They are the fundamentals requirement of any language. The identifiers  are defined according to the following rules:

⮚  Identifiers consists letters and digits.

⮚  First character must be an alphabet or underscore.

⮚  Uppercase and lowercase are allowed but not same, i.e. Text not same as text.

⮚  Only one special character underscores (_) will used.

For example, int a_b; Where a and _b are valid identifiers.

Keywords:-Keywords are the reserved words which have standard, predefined meaning in C language. Keywords  cannot be used as names for the variables or other user defined program elements. There are 32 keywords  available in C.

Common examples are as follows.

Tokens:

In a C source code, the basic element recognized by the compiler is known as tokens. A token is source program text that the compiler does not break down into components elements.

⮚  The keywords like int, float, if, for etc.

⮚  Identifiers like main, printf, void etc.

⮚  Constants like a,b,c etc.

⮚  String literals like name, address, phone etc.,and

⮚  Operators like &&, ! etc.

⮚  Punctuation characters such as [ , ] , { , } , ( , ) , ; , : are also tokens.

3. Explain data types used in programming with examples.

Data types:

It is the set of keywords to declare variables. A set of data that specifies the possible range of values in a  program and stored in memory are called data types. Data types are used to define variables before use it.

Types of data types in C

1) Primary data types

2) Secondary data types

Primary Data Types: The basic fundamental of data having unit feature on C programming is called Primary  Data Type.

Example :

Data Type Type Memory Require

Format Specifies

Char Character 1 byte % C
Int Integer 4/2 byte %d
Float Floating point number 4 byte %f
Long Floating number 4 byte %ld
Double Large floating point number 8 byte %lf
long double Very large floating number 12 byte %lf

 

Variable:

Variable are simply names that can change the value while executing a program. It allocates memory  space inside a memory of computer. A variable can have only one value assigned to it in every time of  execution of the program. Its value can change in different executions.

  • Rules for variable declaration

✔  They must always begin with a letter, although some systems permit underscore as the first  character.

✔  White space is not allowed.

✔  A variable should not be a keyword.

✔  It should not contain any special characters.

Types of variable 

  1. Numeric Variable: The variable that store numeric data only is called numeric variable. The numeric data may be whole number or fractional number. Examples are integer, floating point and double.
  2. String Variable: The variable that stores character data only is called string variable. The string data may be single character or string. Examples are character, array of character (string), table of string.

Constant variable: 

A constant is fixed entity. It does not change its value during the entire program execution. Constants can  be classified as:

  1. Integer constants
  2. Floating point constants
  3. Characters constants
  4. String constants
  5. Symbolic constants
  6. Escape sequence constants

 

Specifier:

The input and output data are formatted by specific pattern. These Patterns are generated by using specific tokens in C programs. These tokens used to format data are called specifier. Most of the specifier used by printf and scanf functions. Types of mostly used specifier are explained below.

Escape Sequence: They are a type of specifier. These non printable characters are used to format text on the output screen. These escape sequence character are place after backslash \.

Escape sequence Name Meaning
\’ Single quote It prints ‘ in output
\” Double quote It prints ” in output
\n New line It creates new line in output display
\t Tab It creates tab or 8 spaces in place of \t

 

❖  Format Specifier: The output and input data are display and receive in specific pattern. Format  specifier uses the token % and character(s) after it. It is used to format for all types of data i.e.  integer, float, character and string.

Format Specifier Used by scanf() function
%d , % i Signed integer + or – number o to 9
%f Scans floating point numbers.
%s String, Collection of character i.e. word
%c Character, one single key stroke.

 

Operator:

An operator is a symbol that operates on a certain data type. The operator generally remains between the  two operands. An expression is a combination of variables, constants, and operators written according to  the syntax of the language. The data items that operators act upon are called operands.

Types of operator:

  1. Arithmetic Operator(Binary Operator)
  2. Relational Operator (Comparison Operator)
  3. Logical Operator (Boolean Operator)
  4. Assignment Operator
  5. Increment and Decrement Operators (Unary Operator)
  6. Conditional Operator (Ternary Operator)
  7. Bitwise Operator
  8. Comma Operator
  9. Size of Operator
  1. Arithmetic Operator

The arithmetic operators perform arithmetic operations and can be classified into unary and binary  arithmetic operations. The arithmetic operators can operate on any built-in data type. A list of arithmetic  operators and their meanings are given below:

Operator Meaning
+

*

/

%

additional or unary plus

subtraction or unary minus

multiplication

division

modulo division (returns remainder after division)

  1. Relational Operator

The relational operators help to compare two similar quantities and depending on their relation, take some  decisions. If the condition is true, it evaluates to an integer 1 and zero if the condition is false. The basic  types of relational operator are:

Operator Meaning
<

>

<=

>=

==

!=

less than

greater than

less than or equal to

greater than or equal to

equal to

not equal to

  1. Logical Operator

The logical operators are used to give logical value either true or false. They compare or evaluate logical  and relational expressions. There are three logical operators.

Operator Meaning Examples
&& Logical AND (a>b) && (a>c)
|| Logical OR (a>b) || (a>c)
! Logical NOT !(a==b)
  1. Increment and Decrement Operators:

The increment and decrement operators are very commonly used in C language. The increment operators  and decrement operators are extensively used in the loops using structures such as for, while, do, etc. The  syntax of the operators is given below:

++<variable name>

–<variable name>

<variable name>++

<variable name)–

Pre increment

Pre decrement

Post increment

Post decrement

The pre increment operator increases the value of the variable by 1 and then the processing does whereas  post increment first processes and increase the value of it by 1.

  1. Conditional Operator:

A conditional operator is very rarely used. This can be carried out with the conditional operator (? : ) An  expression that makes use of the conditional operator is called a conditional expression. This can replace  the if-else statement. The syntax of conditional operator is:

Expression_1 ? expression_2: expression_3

During evaluating the conditional expression, expression_1 is evaluated at the first step. If expression_1 is  true (nonzero), then expression_2 is evaluated and this becomes the value of the conditional expression.

Library function:

The special functions that are well defined in C programming languages are called library functions such as  printf(), scanf(),strlen(), sqrt(), tolower(), toupper(), getchar(), putchar() etc.

Control Structure:

Control structures are those programming constructs which control the flow of program statements  execution in a program. Types of Control Structure

i) Branching / Decision ( Selective Control Structure)

ii) Looping (Repetitive Control Structure)

iii) Jumping (Unconditional Control Structure)

  1. Decision (Selective) Control Structure

It is mainly used for decision making. It is also called conditional statements. Selection is made on  the basis of condition. We have options to go when the given condition is true or false. The flow of  program statements execution is totally directed by the result obtained from checking condition.  Types

a) Conditional Statements:

i. if statements:

It is used to execute an instruction or block of instructions only if a condition is fulfilled. Syntax,

if(condition)

{

Statements;

}

E.g. Write a program to read a number and find even or odd by using if().

Output:

 

ii. if else statements:

If the condition is true then the if() portion statements are evaluated otherwise else part of the  statements are evaluated.

Syntax,

if( condition)

{

Block of statements;

}

else

{

Block of statements;

}

E.g. Write a program to input any two numbers and display the largest one.

Output:

 

iii. if() else if() statements

When we have two or more condition to be checked in a series we can use if else if statement. It is  also known as multiple conditional statement or multipath conditional statement /if else ladder. Syntax,

e.g. Write a program to find the largest number among three input number .

Output:

 

iv. Nested if else statements

An entire if else statement written within the body of if part or else part of another if else statement is  called nested if else statement. It is used when a condition is to be checked inside another condition at a  time in the same program to make decision.

Syntax,

E.g. Write a program that reads marks of five subject and calculate total mark and percentage. Also awards the division on the basis of following criteria.

Percentage                                                                      division 

p>=75                                                                              distinction 

p>=60 and <75                                                             first 

p>=45 and <60                                                          second 

p>=35 and <45                                                         third 

otherwise                                                                  failed

Output:

 

b) Switch case statements:

The switch statement can be used instead of multiple if() else conditional statements. The switch  control statement is mainly used to generate menu based programs.

Switch(expression 1)
{
    Case condition 1 : Statements ….break;
    .
            .Case condition n –
        1 : Statements…….break;
default:
    statement n;
}

E.g. Write a program which reads any two integer values from the user and calculates sum, difference and  product using switch case statements.

Output:

 

  1. Looping Statement

The looping statement is also called repetitive or iterative control structure. Looping statements are the  conditional control flow statements that repeats a certain portion of the program either a specified  number of times or until a particular condition is satisfied or true.

Types of loop

i) For Loop

ii) While Loop

ii) Do while Loop

i. For Loop:-

The execution of for loop until the condition is true. The for loop is a entry control loop because it  checks the condition at entry point. 

Syntax,

  1. Write a program to print the natural number from 1 to 10.

Output:

 

2. Write a program to display even numbers from 1 to 20 and display their sum also. 

Output:

 

3. Write a program to find out sum of the cubes of first 10 numbers.

Output:

 

Nested for loop:

When for loop is declared inside another for loop is called nested for loop. The life of the inner for loop  is depending over the outer for loop. If the outer for loop condition is true then inner for loop is  evaluated. And will executes all the statements until condition is true if the inner for loop to be false  then the outer for loop condition is reevaluated and so on.

For example:

  1. Display the following output :

10 20 30 40 50

10 20 30 40 50

10 20 30 40 50

10 20 30 40 50

10 20 30 40 50

Program:

Output:

2. Write a program to display following output:

55555

4444

333

22

1

Program:

Output:

While Loop:-

The while loop is also a entry control loop. While loop first checks whether the initial condition is  true or false and finding it to be true, it will enter the loop and execute the statement.

Syntax,

1. Write a program to print even number from 1 to 100.

Output:

 

Do while loop:- 

This loop is an exit control loop. This loop runs at least the once even though the termination  condition is set to false. This loop test the condition at exit point hence it is called exit control loop.  The syntax of the loop is similar to while loop.

 

1. Write a program to display odd numbers from 100 to 1.

Output:

2. Write a program to read the employee name, address for the N employee and display by  using while loops.

Output:

Difference between While loop and Do while loop:
S.N.  While loop  S.N.  Do while loop
It is an entry controlled loop.  It is an exit controlled loop.
Testing starting in top  Testing started at the bottom.
It has keyword while  It has the keywords do and while.
If the first condition is true then the statement is  executed otherwise no. But in case at least one time executed  statement if the condition is false.
Loop is not terminated with a semicolon.  Loop is terminated with a semicolon.
Syntax,

while (expression) 

 //statements 

}

6 Syntax,

do 

 //statements 

} while (expression);

 

The jump Statements 

  1.  break statements 
  2.  continue statements 
  3. goto statements

1) break statements: 

 The break statement is used to terminate a loop or to exit from a switch. it can be used within a  for, while, do while switch statement. 

Output:

 

2) The continue Statement  :

It skips the remaining statements in the body a while, for or do ……while structure proceeds with  the next iteration of the loop. The continue statement is used to bypass the execution of the further  statements.

Output:

 

3) Go to statement: 

The goto statement is used to send the pointer to the specified label. If the label is not  defined then the goto statement will not work.

Output:

 

Some important C programs:

  1. Reverse order 
  2. Factorial number 
  3. Fibonacci series 
  4. Prime or composite number 
  5. Even or odd number 
  6. Palindrome or not. 
  7. Sum of individual digits 
  8. Armstrong number or not 
  9. Multiplication table 
  10. Find list of prime number  
  11. Display a perfect square number.

1. Write a program to input any value and display that value in reverse order.

Output:

 

2. Write a program to input a positive number and find its factorial number. 

Output:

 

3. Write a program to display the Fibonacci series. 1 1 2 3 5 8 13 …………………n.

Output:

 

4.Write a program to read a number and to check the number is prime or not.

Output:

 

5.Write a program to find out even numbers from 1 to 100 and find their sum also.

Output:

 

6.Write a program to input a number and find out if the number is palindrome or not.

Output:

 

7.Write a program to input a positive number and find out the sum of its individual digits.

Output:

 

8.Write a program to input a number and check if it is an Armstrong number or not.

Output:

 

9.Write a program to display the multiplication table of a given number. 

Output:

 

10.Write a program to display all prime numbers upto 1000. 

Output:

 

11.Write a program to display all perfect square numbers from 100 to 500.  

Output:

 

Arrays and String Function: 

Arrays :

An array is a collection of data of the similar type all of which are referred by a single variable  name. For example, instead of using 50 individual variables to store the names of 50 students, we can use an  array to store the names of 50 students. 

Advantage of arrays: 

  1. It is easier for handling similar types of data in a program. 
  2. It is efficient for solving problems like sorting, searching, indexing etc. 
  3. It is easier to solve matrix related problems. 
  4. Graphics manipulations can easily be done using arrays. 

Disadvantages of arrays:

  1. It is not possible to hold dissimilar types of data in an array. 
  2. It is difficult to visualize the multi dimensional array. 
  3. It is static in nature so it is difficult to define the size of the array during running

 There are two types :

  1. One/signal dimensional: The values on an array variable assigned in one row and more than one  column are called signal dimensional array. 

Syntax: type array_name[max. size]; 

Example int n[10]; 

int age[]= {18,12,19,20,16,16,17}; 

  1. Two/Double dimensional: Two dimensional arrays are capable of storing data in multiple row and  columns. 

Syntax: type array_name[No.Rows] [No.Cols]; 

Example int n[10][5];

int matrix[3][3]= {{0,1,2},{3,4,5},{6,7,8}};

 

Program: Write a program to read 50 students’ marks and display them. 

Output:

 

Program: Write a program to input 5 numbers with constant values initialization in array to display the  sum. 

Output:

 

Program: Write a program to input the age of 20 students and count the number of students having age  in between 20 to 25. 

Output:

 

Program: Write a program to find the largest number among ‘n’ numbers. 

Output:

 

Program: Write a program to read a matrix, store it in an array and display it. 

Output:

 

Program: Write a program to calculate the average age of 10 students. 

Output:

 

Program: Write a program to accept the age of 10 different employees and count the no. of employees.

i) Whose age is more than or equal to 60

ii) Whose age is less than 35

Output:

 

Program: Write a program to store N numbers in array and print out the sum with the entire array  variable. 

Output:

 

Program: Write a program to accept 10 different numbers in array and sort in descending order.

Output:

 

Program: Write a program to store twelve numbers in a double dimensional array and print out the values  in table with row wise addition.

Output:

 

Program: Write a program to enter elements for 2×2 matrix and display its transpose.

Output:

Program: Write a program to enter elements for 3×3 matrix and display its sum.

Output:

 

String Function: 

The strings are manipulated by specific string function. These are inbuilt functions and defined within  string.h header file. 

  1. strlen( ): It returns the number of character present in the string. 

                                   Syntax: strlen(string);

Program: Write a program to store string in array variable and find the length.

Output:

     2. strrev( ): It helps to reverse the character of the string. 

                                 Syntax: strrev(string); 

      3. strupr( ): It converts lowercase letters in string to uppercase.

                                Syntax: strupr(string); 

     4. strlwr( ): It converts uppercase letters in string to lowercase.

                              Syntax: strlwr(string); 

     5. strcpy( ): It is used to copy the content of one string to another. 

                              Syntax: strcpy(target,source); 

     6. strcat( ): It is used to concatenate source string to the target string.

                              Syntax: strcat(target,source); or strcat(source,target); 

     7. strcmp( ): It compares two strings on the following basis. 

                             Syntax: strcmp(string1,string2);

Program: Write a program to show use of trcpy,strrev,strupr and strlwr.

Output:

Program: Write a program to read two strings in an array and concatenate strings.

Output:

Program: Write a program to read two strings in an array and compare two strings and check that string is  palindrome or not.

Output:

Function:

Functions are the building block of statements, which take some data, manipulate them and can return a  value. Bug free functions can be used repeatedly from other parts of the program. There are two types of  functions:

  1. Library Functions (built in or ready made): C has the facilities to provide library functions for  performing some operation. These functions are present in the c library and they are predefined.  for eg. 
    1. scanf( ); 
    2. printf( ); 
    3. getchar( ); 
    4. putchar( ); 

2. User Defined functions (Defined by user according to need): users can create their own function  for performing this type of function called user defined function.

Syntax  of user defined functions;

  1. Write a program to calculate simple interest using function.

Output:

2. Write a program to calculate the area of a rectangle using function. 

Output:

Advantage: 

  1. Big programs can be divided into smaller modules using functions. 2. Program development will be faster. 
  2. Program debugging will be easier and faster. 
  3. Use of functions reduces program complexity. 
  4. Program length can be reduced through code reusability. 6. Use of functions enhance program readability. 
  5. Several developers can work on a single project. 
  6. Functions are used to create your own header file i.e. mero.h 
  7. Functions can be independently tested.

 

With passing arguments 

Program: Write a program to find out the area of a circle through a given radius as an argument using a function.

Output:

Program: Write a program in C to create a function to pass two numbers as an argument and to return a  sum to the calling function. 

Output:

 

Without passing arguments 

Program: Write a program to find out the sum and square of two input number without passing arguments  function.

Output:

 

Recursive Function:  

The function which performs recursion is called a recursive function. Recursion is a process by which a  function calls itself repeatedly until some specified condition has been satisfied. 

The 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 a terminating condition so that function calling will not be for an infinite number of  times.

Program: Write a program to calculate factorials by using a recursion process. 

Output:

 

Program: Write a program to read a number and make the sum of individual digits & print using recursion  technique. 

Output:

 

Program: Write a program to calculate sum of n-natural numbers using recursion/recursive function.

Output:

 

Accessing a Function: 

There are two types of accessing a function. 

1. Call by value: Only the values of arguments are the same to the function and any change made to the  formal arguments does not change the actual arguments.

Program: Write a C program trying to exchange two values by using a call by value accessing function.

Output:

2. Call by reference: When we pass an address to a function the parameters receiving the address should  be pointers. The process of calling a function by using a pointer to pass the address of the variable is  known as call by reference.

Program: Write a C program to exchange two values by using call by reference accessing function.

Output:

 

Structure and Union 

Structure:  

Structure is a collection of variables under a single name. As an example, if we want to store data  with multiple data types like roll number, student name, address, phone number and class of a student  then C supports a structure which allows us to wrap one or more variables with different data types. Each  variable in a structure is called a structure member. To define a structure, we use the struct keyword. Syntax;

We can also declare a structure ,

We can also declare array of variables at a time of declaring a structure as: 

Union:  

Unions like structure contain members whose individual data types may differ from one another.  However the members that compose a union all share the same storage area within the computer memory  where as each member within a structure is assigned its own unique storage area. Syntax;

Union union_name 

Union_member (s); 

}

 

Difference between Structure and Union:
S.N.  Structure  S.N.                                                     Union
1. Structure is designed by using the ‘struct’  keyword. 1.  Union is designed by using ‘union’ keyword.
2. Syntax: struct structure_name 

 { 

 Data_type member1; 

 Data_type member1; 

 }

2.  Syntax: union union_name 

 { 

 Data_type member1; 

 Data_type member1; 

 }

3.  All the members of the structure variable  can be processed at a given time. 3.  Only one member of the union variable can be  processed at a time because only one member  of the union variable can be active at a time.
4. We use structure variables if memory is  large and have to store values of all of the  variables. 4.  We use union variables if memory is less and  have to store one variable in one of the  declared variables or members.
5.  Structures are broadly used in  

programming.

5.  Unions are not used broadly as much as  structures.
6. Structure declaration takes a large amount  of spaces to store data and values. 6.  Union declaration shares the same area of  memory to save storage space.

 

Example 1: Write a C program to read different structure variables and display them.

Output:

 

Program: Write a program to input the employee name and their basic salary of n employees and display  the record in proper format. 

Output:

 

Program: Write a program that reads different names and addresses into the computer and rearrange the  names into alphabetical order using the structure variables.

Output:

 

 

Pointer 

A pointer is a variable that points to a memory location where data is stored. Each memory  cell in the computer has an address which can be used to access its location. A pointer variable points to a  memory location rather than a value.  

– We can access and change the contents of the memory location.  

– A pointer variable contains the memory location of another variable. 

– The asterisk tells the compiler that you are creating a pointer variable. 

The pointer declaration syntax is as shown below. 

Pointer_type *pointer_variable_name; 

For e.g. int *p;

Address (&) and indirection (*) operator 

The address (&) operator and immediately preceding variable returns the address of the variable  associated with it. Hence, the address of (&) operator returns the address of memory location in which the  variable is stored.  

The indirection (*) operator is used to extract value from the memory location stored in the  particular memory location whose address is stored in a pointer variable. 

The syntax of declaring address operator to pointer variable is as follows. 

Pointer_variable = &variable_name;  

For Example;

int *ptr, num=25; 

ptr = &num;

Program: Write a complete program to display address and value of the pointer variable.

Output:

Pointer to Arithmetic 

Output:

 

Write a C program to increment a pointer.

Output:

 

Assignment pointer value to function 

Program: Write a program to pass pointer variables to function sum them and display after returning it.

Output:

 

Array of pointers: 

Program: Write a C program to assign an array, place these arrays in a pointer variable and display array value  along with its address.

Output:

 

Pointer to Pointer 

Program: Write a program to demonstrate the use of pointer to pointers:

Output:

 

Advantage of Pointer 

  • Runtime memory creation. 
  • Runtime memory deletion. 
  • Hard Access through pointer. 
  • Data Structure Based Pointer. 
  • Applications of Pointer Ms-word, Excel, Access, SQL.

 

Working with files 

Data file requires that information be written and stored on the memory device in the form  of a data file. Thus, data file access and alter that information whenever information in C.

Sequential and Random Access File 

Sequential Access File: 

The sequential access files allow reading the data from the file in one after another i.e. in sequence. There  is no predefined order for accessing data file. All the processes are declare and assigned by the compiler  during run time of the program.  

Random Access File:  

The random access files allow reading data from any location in the file. Sometimes, we need to read data  file from reverse, middle and from specific location. To achieve this, C defines a set of functions to  manipulate the position of the file. The inbuilt function fseek( ), lseek( ), rewind( ) and ftell( ) are the some  of the common examples of random access files.  

Opening, Reading, Writing and Appending on/from Data File: 

Once the file pointer has been declared, the next step is to open file. There is an inbuilt function to open a  file. The function fopen( ) is used to create a steam for use and links of new open file. This function return a  file pointer and takes two parameter one for name of file and other for mode for the file. The syntax is as  follows; 

FILE *f; 

f = fopen (“file_name.extension”, “mode_of_open”);

The modes of the data file are as follows:

S.N.  Mode  Description
“r” / “rt”  It opens a text file to read only mode.
“w” / “wt”  It creates a text file to write only mode.
“a” / “at”  It appends text to already data containing file.
“r+t”  It opens a text file for read and write mode.
“w+t”  It creates a text file for read and write mode.
“a+t”  It opens or creates a text file and read mode.
“rb”  It opens a binary file for read only mode.
“wb”  It creates a binary file for write only mode.
“ab”  It opens or create a binary file for append mode.
10  “r+b”  It opens a binary file for read and write mode.
11  “w+b”  It creates a binary file for read and write mode.
12  “a+b”  It opens or creates a binary file for append mode.

 

Functions;

  1. fputc= Store character into the file. 
  2. fputs= Store string into the file. 
  3. fgetc= fetch character from the file. 
  4. fgets= fetch string from the file. 
  5. fwrite= store data (structure) into the file. 
  6. fread= fetch data (structure) from the file. 
  7. fprintf= store data into file. 
  8.  fscanf= fetch variable from the file.

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.

Output:

[Note: This program will store only a single record. To store multiple records we have to use a 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.

Output:

 

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. 

Output:

Add/Append data 

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

Output:

After 200 iterations, the program will stop and close the file “student.txt”. The file will contain the entered student records, each on a separate line, formatted as:

You can verify the contents of the “student.txt” file after running the program to see the recorded student information.

 

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

Output:

After the user enters the data, the program writes it to the file “student.txt”.

 

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 

Output:

 

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

 

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

 

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

 

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

 

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

 

Program: Write a program to read a line and store it in a data file and display the contents.

Output:

 

Program: Write a C program to read N students, record, store them in data file and display the content in  appropriate format by using fprintf and fscanf function. 

Output:

 

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

Output:

 

Program: Write a C program to read sentences until the enter key is pressed. Put every word in the data file by  using the fputs( ) fucnction and display the content of the file by using fgets( ) function.

Output:

 

Program: Write a C program to read ages of N students, store them in age.txt file and find out the  average age after reading from the data file.

Output:

 

Program: Write C program to read already created data file student.txt and display its contents if it opens  otherwise print message “The file ……does not exists”.

Output:

 

 

Some IMP Notes 

Fwrite  S.N.  fprintf
Binary format writing  1.  No binary format.
Size of data.  2.  Size of data is not fix
Number of records.  3.  No number of records.
We store the data in block form so not in  format form. 4. Format string used to store the data in the  format form.
Fixed block size.  5. No block size.

 

S.N.  Structure  S.N.  Pointer
1.  Structure is use to store the  difference type of data member like  as char, int, float etc. 1. Where is pointer is use to store the  address of another location (variable).
2.  Structure is use to maintain the  records. 2. Whereas pointer is use to create link list.
3.  Structure can’t be use to access the  hardware. 3.  Pointer can be use to access the hardware.
4.  Structure can’t be use to create  memory run time. 4.  But pointer are use to create the memory  runtime.
5.  Structure can be declared as pointer  variable. 5.  Pointer can be declared inside the  structure.

 

S.N.  Break Keywords (Statement)  S.N.  Continue Keywords (Statement)
1.  The break statement is use to terminate  the loop unconditionally. 1. The continue statement is used return the  pointer at the beginning of the loop.
2.  The break statement can also be use  inside the switch statement. 2. But the continue can be use inside the  switch statement.
3.  The break statement is use to terminate  the loop. 3. The continue statement is use to repeat  set of statements.
4.  Example  

 void main( ) 

 { 

 int i; 

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

 { 

 If (i==5) 

 { 

 break;  

 } 

 printf(“%d”,i);  

 } 

 } 

Output= 1,2,3,4. 

4.  Example 

void main( ) 

 int num; 

 for (num=1; num!=10; num+1) 

 { 

 If(num==7) 

 { 

 continue; 

 } 

 printf(“%d”,num); 

 } 

 } 

Output= 1,2,3,4,5,6,8,9.

 

 

S.N.  Array  S.N.  Pointer
1. Array is create continue memory location with  same type. 1.  Pointer creates only one block of  memory but access all memory of  another variable.
2.  Array takes huge of memory.  2.  Pointer takes less and less memory.
3.  Array is to be fixed at the time of declaration.  3.  Whereas pointer size can be change at  the run time.
4. In array we can free the memory run time.  4.  But using pointer the dynamic  allocated memory can be make free at  run time.
5.  If we allocated huge sized of array and we get  few information then unnecessary memory  will be occupied. 5.  But this problem can resolved by using  the pointer.
6.  Using array technique to accessing the array  elements is more different comparison to  pointer. 6.  It is easier than array.