Study Material for C Programming (Advanced)

Programming in C

1. The C Language: C is a powerful programming language used to create programs to perform what you want your computer to do. C is a programming language developed at AT & T’s Bell Laboratories of the USA in 1972. It was designed and written by a man named Dennis Ritchie. It was designed for programming UNIX operating systems. It is a very easy, simple, and reliable programming language.

a) Creating C Programs: There are four fundamental stages, or processes, in the creation of any C program: 

  • Editing: Editing is the process of creating and applying changes to the source code. C Editor provides an Integrated Development Environment(IDE) to write, manage, develop and test your code. In the editor, you write the code by following the syntaxes of the C programming language.

  • Compiling: The compiler converts the source code into machine code, the language understandable by the computer. The compiler can find any number of errors in the code like systematic errors, random errors. If any error is found in the code, the programmer has to edit those errors. The output from the compiler is known as object code and it is stored in files called object files, which usually have names with the extension .obj in the Microsoft Windows environment, or .o in the Linux/UNIX environment.

  • Linking: The linker combines the object modules generated by the compiler with the standard library supplied as part of C. A failure during the linking phase means that once again you have to go back and edit your source code. Success, on the other hand, will produce an executable file. .exe file is created at this stage.

 

  • Executing: The execution stage is where you run your program, having completed all the previous processes successfully. Unfortunately, this stage can also generate a wide variety of error conditions that can include producing the wrong output, just sitting there and doing nothing, or perhaps crashing your computer for good measure. In all cases, it’s back to the editing process to check your source code.

 

      

b) Structure of basic C Language Program:

  1. Comment line 

  2. Preprocessor directive

  3. Global variable declaration 

  4. main function( ) 

           

               Local variables; 

               Statements;

           } 

  • Comment Line: 

                    Single line comments: starts with //………….

                    Multiline comments: starts with /*..................

                                                                             …………..*/

  • Preprocessor directive: #include<stdio.h> tells the compiler to include information about the standard input/output library. It contains the definition of various system defined functions like scanf(), printf(), pow() etc.

  • Global Variable Declaration: The variables declared outside the main function are called global variables. Its scope remains global as it can be used by any function in the program.

  • main() function: Every C program must have a main() function. The actual implementation of a program starts from this main() function. It encloses the program within curly braces.

  • Example:

            //Write a program to print hello on the screen

            #include<stdio.h>

            int main()

            {

                printf("Hello, World!");

                return 0;

            }

 c) List of all format specifiers in C:

Format specifier Description Supported data types
%c Character

char

unsigned char

%d Signed Integer

short

unsigned short

int

long

%e or %E Scientific notation of float values

float

double

%f Floating point float
%g or %G Similar to %e or %E

float

double

%hi Signed Integer(Short) short
%hu Unsigned Integer(Short) unsigned short
%i Signed Integer

short

unsigned short

int

long

%l or %ld or %li Signed Integer long
%lf Floating point double
%Lf Floating point Long double
%lu Unsigned integer

unsigned int

unsigned long

%lli, %lld Signed Integer long long
%llu Unsigned Integer unsigned long long
%o Octal representation of Integer.

short

unsigned short

int

unsigned int

long

%p Address of a pointer to void void * void *
%s String char *
%u Unsigned Integer

unsigned int

unsigned long

%x or %X Hexadecimal representation of Unsigned Integer

short

unsigned short

int

unsigned int

long

%n Prints nothing  
%% Prints % character  

d) Character Set: A character denotes any alphabet, digit, or special symbol used to represent information. Valid alphabets, numbers, and special symbols allowed in C are:


 

 

The alphabets, numbers, and special symbols when properly combined form constants, variables, and keywords.

  • Identifiers: Identifiers are the user-defined names given to variables, constants, functions, arrays, structures in C. There are some rules to name the identifiers:

  • Identifiers consist of alphabets, digits, and underscores (_).

  • The first character should be an alphabet or underscore.

  • You cannot use keywords as identifiers.

  • As C is a case-sensitive language, the same identifier written in uppercase and lowercase will be considered unique. E.g SUM, sum these are the two different identifiers.

  •  Keywords: These are the reserved words used in the C language. These are the predefined keywords whose definitions are already present in the C library. These keywords are always written in lowercase.

 


 

  • Data types in C: When we declare any variable in C, we must specify its type, i.e., the type of data it holds either character or number, if number, either integer or a decimal value. Data type declaration is also important to allocate memory to that variable.

           C has the following 4 types of data types:

  • Basic built-in data types: int, float, double, char 

  • Enumeration data type: enum 

  • Derived data type: pointer, array, structure, union 

  • Void data type: void

Following are the examples of some very common data types used in C:

  • char: The most basic data type in C. It stores a single character and requires a single byte of memory in almost all compilers.

  • int: As the name suggests, an int variable is used to store an integer.

  • float: It is used to store decimal numbers (numbers with floating-point value) with single precision.

  • double: It is used to store decimal numbers (numbers with floating-point value) with double precision. 

 

Different data types also have different ranges up to which they can store numbers. These ranges may vary from compiler to compiler. Below is a list of ranges along with the memory requirement and format specifiers on the 32-bit GCC compiler.

Type Size(bytes) Range
int or signed int 2 -32,768 to 32767
unsigned int 2 0 to 65535
short int or signed short int 1 -128 to 127
unsigned short int 1 0 to 255
long int or signed long int 4 -2,147,483,648 to 2,147,483,647
unsigned long int 4 0 to 4,294,967,295
Float 4 3.4E-38 to 3.4E+38
double 8 1.7E-308 to 1.7E+308
long double 10 3.4E-4932 to 1.1E+4932
char or signed char 1 -128 to 127
unsigned char 1 0 to 255

Example:

#include <stdio.h>

int main()

{

     int a = 10;

     char b = 'A';

     double c = 3.14;

     printf("Hello! I am a character. My value is %c and ""my size is %lu byte.\n",b, sizeof(char));

     printf("Hello! I am an integer. My value is %d and " "my size is %lu  bytes.\n",a, sizeof(int));

   printf("Hello! I am a double floating point variable." " My value is %lf and my size is %lu bytes.\n",c, sizeof(double));

     return 0;

  }

  • Constants: Constant is any value that cannot be changed during program execution. For example, the number 50 represents a constant integer value. The character string "Programming in C" is an example of a constant character string.

  • Variable: A variable is nothing but a name given to a storage area that our programs can manipulate. The value of the variable can be changed during execution.

                 Example: int A=10;  // A is a constant here, a value is already assigned to it.

                                  int A;  // A is a variable here, you can assign any value to it at runtime

 

  • Expression: An expression is a combination of variables, constants, operators, and function call. It can be arithmetic, logical and relational

              Example:- int z= x+y // arithmetic expression

                                a>b // relational expression

                                a==b // logical expression

  • Escape Sequence in C: An escape sequence in C language is a sequence of characters that doesn't represent itself when used inside a string literal or character. It is composed of two or more characters starting with backslash \. Following are some escape sequences used in C:

Escape Sequence Description
\n Represents a newline character
\r Represents a carriage return
\b Represents a backspace
\f Represents a form-feed character
\t Represents a horizontal tab
\v Represents a vertical tab
\a Inserts a bell (alert) character
\? Inserts a question mark (?)
\" Inserts a double quote (")
\' Inserts a single quote (')
\\ Inserts a backslash (\)


Example:

#include <stdio.h>

int main()

{

     printf("Hello\n");

     printf("Welcome \t to C\n");

     printf("Hello friends");

    printf("\v Welcome to C\n");

     printf("C \r Welcome to\n");

     printf("Welcome\\to C\n");

     printf("\' Welcome to C\n");

     printf("\" Welcome to C\n");

     printf("\?\?!\n");

return 0;

}

Note: Perform it on C editor for better understanding.

 

e) Operators in C: Operators are the special symbols that can perform operations on the operands. Some operators require a minimum of two operands to perform their function and some need one operand only. Following are the operators defined in C:

  • Arithmetic Operators: These operators are used to perform mathematical calculations on data. These operators may be unary or binary. 

                  Unary Operators: Unary means the operator which can operate only on one operand. For example: (++ , –)

                  Binary Operators: Binary means the operator which can operate on two operands.For example: (+ , – , * , /,%)

                       Example:

                            a=b+c; a=b-c;  // Binary operators

                            a=b*c;            a=b/c;

                            a++; a--;      // Unary Operator

  • Assignment operator:  Assignment operators are used to assigning value to a variable. The left side operand of the assignment operator is a variable and the right side operand of the assignment operator is a value. The value on the left side is called lvalue and the value on the right side is called rvalue. “=”: is an assignment operator. This operator is used to assign the value on the right to the variable on the left. 

                       Example: int a=10;

                            char ch= ‘x’; 

The assignment operator is also used in combination with arithmetic operators if we use the same variable both the sides in lvalue and rvalue. E.g a=a+10;

It can be written like a+=10;, Similarly, other arithmetic operators can be used with the assignment operator.

Example: a=a+10; can be written as a+=10;

    a=a-10;  can be written as a-=10;

    a= a*10;can be written as a*=10;

    a=a/10;  can be written as a/=10;

    a=a%10;can be written as a%=10;

  • Relational Operators: These operators are used to compare the values of two operands. It is also used to compare two expressions. Following are the relational operators used in C:

== (Check if two operands are equal)

!=  (Check if two operands are not equal)

>   (Check if the operand on the left is greater than the operand on the right)

<   (Check operand on the left is smaller than right operand)

>= (Check left operand is greater than or equal to right operand)

<= (Check if the operand on left is smaller than or equal to the right operand)

Example: (a==b)

                 (a>b)&&(b>c)  // This is an expression where we have used && logical operator

  • Logical Operators: An expression containing a logical operator returns either 0 or 1 depending upon whether the expression results in true or false. Logical operators are commonly used in decision-making in C. Logical operators in C are: 

                               && (Logical AND)  True only if all operands are true.

                               || (Logical OR)         True only if either one operand is true.

                               ! (Logical NOT)       True only if the operand is 0

                  Example: If c = 4 and d = 2 then, expression ((c==4) && (d>5)) equals to 0.

                            If c = 4 and d = 2 then, expression ((c==4) || (d>5)) equals to 1.

                            If c = 4 then, expression !(c==4) equals to 0.

  • Bitwise Operators: Bitwise operators perform manipulations of data at the bit level. These operators also perform the shifting of bits from right to left or left to right. Bitwise operators are not applied to float or double data. Following are the Bitwise operators in C: 

                  &   (Bitwise AND)

                   |     (Bitwise OR)

                   ^    (Bitwise exclusive OR)

                  <<  (Left Shift)

                   >>  (Right Shift)

Truth Table for Bitwise &, | or ^:

 

a b a&b a | b a ^ b
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0


 

  • Increment and Decrement Operator: C programming has two operators increment ++ and decrement -- to change the value of an operand (constant or variable) by 1. Increment (++) increases the value by 1 whereas decrement (--) decreases the value by 1. 

                Example: 

                    #include <stdio.h>

                        int main()

                           {

                              int a = 10,b=10; 

                              printf("Value of a is = %d \n", a++);  // post increment operator

                              printf("Value of a is = %d \n", ++a);  // pre increment operator

                              printf("Value of b is = %d \n", --b);   // pre decrement operator

                              printf("Value of b is = %d \n", b--);   // post decrement operator

                              return 0;

                          }

                    Output: Value of a is = 10

                                  Value of a is = 12

                                  Value of a is = 9

                                  Value of a is = 9

 

  • Conditional Operator: The conditional operators in the C language are also known as Ternary Operator This is the ternary operator: (? :) It is a condition that we use in C language decision making, but using a conditional operator, we turn the if condition statement into a short and simple operator. 

Syntax: expression1? expression 2 : expression3 

If expression1 is true, it will give expression2 as output, otherwise the expression3.

 

  • Special Operators: Following are some of the special operators used in C: 

Operator Description Example
sizeof Returns the size of a variable sizeof(x) return size of the variable x
, used to link related expressions together int a, b=4,c;
& Returns the address of a variable &x; return address of the variable x
* Pointer to a variable *x; will be a pointer to a variable x

f) Conditional statements in C: Conditional Statements in C programming are used to make decisions based on the conditions. If you put some condition for a block of statements, the execution flow may change based on the result evaluated by the condition. This process is called decision-making in 'C.' Following are the C conditional statements:

  • if statement: The statements written in the if block executes only when the condition is true. If the condition becomes false the compiler does not execute the if block and moves further for the next statements.

              Syntax: 

                   if (test expression) 

                      {

                           // code

                      }

                Example:

                    #include <stdio.h>

                          int main() 

                     {

                           int number;

                           printf("Enter an integer: ");

                           scanf("%d", &number);

                           // true if number is less than 0 and it will print the negative number

                            if (number < 0) 

                               {

                                   printf("You entered %d.\n", number);

                                }

                             return 0;

                        }

  • if-else statement: In this statement, if the if block is true it will execute otherwise the else block will execute.

               Syntax: 

                   if (test expression) 

                      {

                          // run code if the test expression is true

                       }

                   else 

                       {

                           // run code if the test expression is false

                       }

              Example: 

                   #include <stdio.h>

                   int main() 

                    {

                         int number;

                         printf("Enter an integer: ");

                         scanf("%d", &number);

                         //  if executes when number is even or else executes when if is false number is odd.

                   if (number%2==0) 

                    {

                        printf("Number is Even %d.\n", number);

                     }

                  else

                     {

                         printf("Number is Odd %d.\n", number);

                      }

                  return 0;

              }

  • if-else Ladder: The if-else-if ladder statement executes one condition from multiple statements. The execution starts from the top and checks for each if condition. The statement of if block will be executed which evaluates to be true. If none of the if the condition evaluates to be true then the last else block is evaluated.

           Syntax: 

               if (test expression1) 

                 {

                    // statement(s)

                  }

               else if(test expression2) 

                 {

                    // statement(s)

                 }

               else if (test expression3) 

                {

                   // statement(s)

                 }

               else 

                  {

                    // statement(s)

                  }

            Example:

               #include <stdio.h>

                 int main() 

                    {

                        int num1, num2;

                        printf("Enter two integers: ");

                        scanf("%d %d", &num1, &num2);

                        //checks if the two integers are equal.

                        if(num1 == num2)

                    {

                        printf("Both the numbers are equal %d = %d",num1,num2);

                     }

                  else if (num1 > num2) 

                     {

                         printf("First number is greater than Second %d > %d", num1, num2);

                      }

                  else 

                      {

                         printf("First number is less than Second %d < %d",num1, num2);

                      }

                  return 0;

               }

  • Nested if-else: When a series of decisions are required, nested if-else is used. Nesting means using one if-else construct within another one.

           Example: 

               #include<stdio.h>

                int main()

                {

                    int num;

                    printf("Enter Number: ");

                    scanf("%d", &num);

                  if(num<10)

                    {

                         if(num==1)

                     {

                   printf("The value is:%d\n",num);

                   }

                 else

                   {

                       printf("The value is greater than 1");

                   }

                 }

                 else

                  {

                       printf("The value is greater than 10");

                   }

                  return 0;

              }

  • Switch statement: A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case.

Syntax:

switch(expression) {

   case constant-expression  :

      statement(s);

      break; /* optional */

   case constant-expression  :

      statement(s);

      break; /* optional */  

   /* you can have any number of case statements */

   default : /* Optional */

   statement(s);

}

Example:

#include <stdio.h>

int main () 

{

    char grade;

    printf("Enter Grade: ");

    scanf("%c", &grade);

switch(grade) {

       case 'A' :

       printf("Excellent!\n" );

       break;

       case 'B' :

       case 'C' :

      printf("Well done\n" );

       break;

       case 'D' :

      printf("You passed\n" );

         break;

       case 'F' :

          printf("Better try again\n" );

          break;

       default :

          printf("Invalid grade\n" );

    }   

    printf("Your grade is  %c\n", grade );

  return 0;

}

g) Looping Statements: Loop executes the sequence of statements a number of times until the condition defined becomes false. The purpose of using the loop statements is that when you want to repeat the same code a number of times. Loops are classified into two parts:

            Entry Control Loop

            Exit Control Loop

In an entry-controlled loop, a condition is checked before executing the body of a loop. It is also called a pre-checking loop.

In an exit-controlled loop, a condition is checked after executing the body of a loop. It is also called a post-checking loop.

  • While loop: It is an entry-controlled loop. In this case, the condition is first checked then the body of the loop is executed. The loop goes on iterating until the condition becomes false. Once the condition becomes false, the control goes out of the loop. The control will move to the next statement that comes immediately after the while loop. In a while loop, the body will not execute for once also if the condition was false for the first time.

Syntax:

while (condition) 

{

                 Statements;

}

Example: 

#include<stdio.h>

#include<conio.h>

int main()

{

int num=1; //initializing the variable

while(num<=5) //while loop with condition

  {

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

num++;//increment operation

  }

return 0;

}

  • do-while loop: It is an exit-controlled loop. In this case, the body of the loop is executed first then the condition is checked. The do-while body is executed once if the condition is false for the first time. After the body is executed, then it checks the condition. If the condition is true, then it will again execute the body of a loop otherwise control is transferred out of the loop.

Syntax:

      do 

{

                 Statements;

}while(condition);

Example:

#include<stdio.h>

#include<conio.h>

int main()

{

int num=1; //initializing the variable

do //while loop with condition

{

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

     num++; //increment operation

}while(num<=5);

return 0;

}

  • for Loop: for loop is the simplest loop structure in C. It consists of three parts:

               Initialization: The initial value of the for loop is defined here.

               Condition: The expression that fixes the iteration count. The loop goes on iterating until the condition becomes false.

               Incrementation/Decrementation: increases (or decreases) the counter by a set value.

Syntax: 

for (initial value; condition; incrementation or decrementation ) 

{

       Statements;

}

Example:

#include<stdio.h>

#include<conio.h>

int main()

{

int num; //initializing the variable

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

{

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

}

return 0;

}

h) Jump statements: Jump statements cause an unconditional jump to another statement elsewhere in the code. They are used primarily to interrupt switch statements and loops. Following are the jump statements used in C:

  • break: This statement is used to interrupt the iteration at some specified number. Break terminates the loop when encountered. Mostly it is used in switch statements to check the number of cases, when the correct case encounters it terminates the rest of the cases below that.

Example:

#include<stdio.h>

#include<conio.h>

int main()

{

int num; //initializing the variable

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

{

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

{

    if(num==7)

    break;

}

}

return 0;

}

  • continue: The continue statement passes control to the end of the immediately enclosing while, do, or for statement.

Example:

#include<stdio.h>

#include<conio.h>

int main()

{

int num; //initializing the variable

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

{

{

    if(num==7)

    continue;

}

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

}

return 0;

}

  • goto statement: goto jump statement is used to transfer the flow of control to any part of the program desired. This label indicates the location in the program where the control jumps to.

Example:

#include <stdio.h>

int main() {

   int i, j;

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

{

    if (i == 4)

       goto there;

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

  }

   there:

     printf("Four");

  return 0;

}

  1. Arrays: An Array is the collection of data of similar types i.e it is a collection of homogenous data types and all the elements of an array are stored at contiguous memory locations, one after another. An array of characters is a string. Each element has one index value also called subscript, enclosed in square brackets. Index address starts from zero. An array can be single-dimensional or multidimensional and the number of subscripts determines its dimension. One dimensional array is known as a vector and two-dimensional arrays are known as a matrix.

Syntax: 

data_type array_name[array_size];

int arr[10];

int a[5]= { 5,10,15,20,25};

Example: 

#include<stdio.h>

int main()

{

int arr[5],i;

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

{

       printf("enter a value for arr[%d] \n",i);

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

}

printf("the array elements are: \n");

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

{

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

}

return 0;

}

a) Two-dimensional array: Two-dimensional array is also known as a matrix. Two subscripts are used for array declaration in a two-dimensional array.

Syntax: 

data_type array_name[row][column];

int arr[4][4];

int a[3][3]= {

         { 1,2,3},

        {4,5,6,},

         {7,8,9}

       };

Example: 

#include <stdio.h>

  int main()

{

   // array declaration and initialization

   int arr[3][3] = {

     {1, 2, 3},      //row 1

     {4, 5, 6},      //row 2

     {7, 8, 9},     //row 3

   };

   // accessing and printing the elements

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

       // variable i traverses the rows

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

          // variable j traverses the columns

          printf("array [%d][%d] = %d\n", i,j, arr[i][j] );

       }

    }

   return 0;

}

b) String: The array of characters is called a string. It is always terminated by the NULL character. A string is a one-dimensional array of characters. 

Syntax:

char str_name[size];

char str[] = "StudySection";

char str[50] = "StudySection";

char str[] = {'S','t','u','d','y','S','e','c','t','i','o','n','\0'};

char str[13] = {'S','t','u','d','y','S','e','c','t','i','o','n','\0'};

Example: 

#include<stdio.h>  

int main()

{   

     // declare and initialize string

     char str[] = "Study Section";

            // print string

           printf("%s",str);

           return 0;

}

c) String Library Functions: There are some string library functions used to manipulate string and the definitions for these functions are placed in the header file “string.h”. Several string functions are defined below:

  • strlen(): This function returns the length of the string. i.e. the number of characters in the string excluding the terminating NULL character. 

  • strcmp(): This function is used to compare two strings. If the two strings match, strcmp() returns a value 0 otherwise it returns a non-zero value. It compares the strings character by character and the comparison stops when the end of the string is reached or the corresponding characters in the two strings are not the same.

  • strcpy(): This function is used to copying one string to another string. The function strcpy(str1,str2) copies str2 to str1 including the NULL character.

  • strcat(): This function is used to append a copy of a string at the end of the other string. If the first string is “Study” and the second string is “Section” then on applying this function the string becomes “StudySection”.

Example: 

#include <stdio.h>

#include <string.h>

int main()

{

      char str1[20] = "Study";

      char str2[20] = "Section";

      int s1length=strlen(str1);

      int s2length=strlen(str2);

     printf("Length of string str1: %d \n", s1length);

      printf("Length of string str2: %d \n", s2length);

         if (strcmp(str1, str2) ==0)

      {

         printf("string 1 and string 2 are equal \n");

      }

else

       {

          printf("string 1 and 2 are different \n");

      }

      

     strcat(str1,str2);

      printf("String after concatenation: %s \n", str1);

           

      strcpy(str1,str2);

      printf("String str1 is: %s \n", str1);

     

      return 0;

}

  1. Functions in C: A function is a group of statements that collectively perform a task. Every C program has at least one function, a main(), without this function, your program gets executed but does not provide you the output. You can divide up your code into separate functions. Division should be like each function should perform some specific task. A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function. The function call, calls the actual body of the function in the main program for its execution. The C standard library provides numerous built-in functions that your program can call. For example, strcat() to concatenate two strings, memcpy() to copy one memory location to another location, and many more functions. 

a) There are two types of functions: 

  • Library functions are the in-built functions and can be used to fulfill some specific requirement like math(), sqrt(),pow().

  • User-defined functions are defined by the user according to its requirement. The user can name the function according to its requirement.

Syntax: 

Function Declaration: return_type function_name( parameter list );

Defining a Function: 

return_type function_name( parameter list ) 

{

   body of the function

}

Calling a Function:  function_name( parameter list );

Example:

#include <stdio.h>

int sum(int num1, int num2);  //Function Declaration 

  int main () 

{

     int a,b;

    printf("Enter First Number: ");

   scanf("%d", &a);

     printf("Enter First Number: ");

    scanf("%d", &b);

    int ret;

    ret = sum(a, b); // Function Call

  printf( "Sum of two numbers is : %d\n", ret);

  return 0;

int sum(int num1, int num2) // Function Definition

{

         int result; //Local Variable Declaration

          result= num1+num2;

        return result; 

}

b) Types of arguments used in function:

  • Actual Arguments: The arguments used inside the function call are known as actual arguments and these are the original values and copy of these are sent to the called function. For example: in the above example a and b are the actual arguments used in the function call.

           sum(a,b);

  • Formal Arguments: These arguments are mentioned in the function definition. These arguments are also called dummy arguments. For example: in the above example num1 and num2 are the formal arguments used in the function body.

           int sum(int num1, int num2)

           {

             // body of function

           }

c) Categories of Functions based on arguments and return type:

 

  • Function with no argument no return type: In this category, the function has no arguments. It does not receive any data from the calling function. Similarly, it doesn’t return any value. The calling function doesn’t receive any data from the called function. So, there is no communication between calling and called functions.

Example:

#include <stdio.h>

int sum();  //Function Declaration 

  int main () 

{

 sum(); // Function Call

 return 0;

}

  int sum() // Function Definition

{

int a,b,result;

 printf("Enter First Number: ");

    scanf("%d", &a);

     printf("Enter First Number: ");

    scanf("%d", &b);

    result= a+b;

  printf("Sum of two numbers is %d", result);

    }

  • Function with no argument but with return type: In this category, the function has no arguments and it doesn’t receive any data from the calling function, but it returns a value to the calling function. The calling function receives data from the called function. So, it is a one-way data communication between calling and called functions.

Example:

#include <stdio.h>

int sum();  //Function Declaration  

int main () 

{

    int result;

result=sum(); // Function Call

   printf("Sum of two numbers is %d", result);

return 0;

}

  int sum() 

{

      int a,b,result;

    printf("Enter First Number: ");

   scanf("%d", &a);

    printf("Enter First Number: ");

    scanf("%d", &b);

   result= a+b;

   return result; 

}

  • Function with arguments but no return type: In this category, the function has some arguments. it receives data from the calling function, but it doesn’t return a value to the calling function. The calling function doesn’t receive any data from the called function. So, it is one-way data communication between call and calling functions.

Example: 

#include <stdio.h>

int sum(int num1,int num2);  //Function Declaration 

  int main () 

{

     int a,b;

    printf("Enter First Number: ");

    scanf("%d", &a);

    printf("Enter First Number: ");

    scanf("%d", &b);

sum(a,b); // Function Call  

    return 0;

}

  int sum(int num1,int num2)

  {

    int result;

    result= num1+num2;

    printf("Sum of two numbers is %d", result);

}

  • Function with arguments and return type: In this category, functions have some arguments and it receives data from the calling function. Similarly, it returns a value to the calling function. The calling function receives data from the called function. So, it is two-way data communication between calling and called functions.

Example: 

#include <stdio.h>

int sum(int num1, int num2);  //Function Declaration 

  int main () 

{

     int a,b;

    printf("Enter First Number: ");

   scanf("%d", &a);

     printf("Enter First Number: ");

    scanf("%d", &b);

    int ret;

    ret = sum(a, b); // Function Call

  printf( "Sum of two numbers is : %d\n", ret);

  return 0;

int sum(int num1, int num2) // Function Definition

{

         int result; //Local Variable Declaration

          result= num1+num2;

        return result; 

}

 

d) Call by Value and Call by Reference:

Call by Value Call by Reference
In Call by value, values are passed to the calling function. In Call by reference, the address of the variable is passed to the calling function.
In this, a copy of the variable is passed. In this, a variable itself is passed.
Changes made in a copy of a variable never modify the value of the variable outside the function. Change in the variable also affects the value of the variable outside the function.
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.

#include<stdio.h>

void swap(int x, int y);

int main()

{

    int a = 10, b = 20;

     swap(a, b);

    printf("a=%d b=%d\n", a, b);

    return 0;

}

void swap(int x, int y)

{

    int t;

    t = x;

    x = y;

    y = t;

    printf("x=%d y=%d\n", x, y);

}

Output:

x=20 y=10

a=10 b=20

#include<stdio.h>

void swap(int*, int*);

int main()

{

    int a = 10, b = 20;

    swap(&a, &b);

    printf("a=%d b=%d\n", a, b);

    return 0;

}

void swap(int* x, int* y)

{

    int t;

    t = *x;

    *x = *y;

    *y = t;

    printf("x=%d y=%d\n", *x, *y);

}

Output:

x=20 y=10

a=20 b=10

 

4) Structure in C: Structure is a collection of elements of heterogeneous type i.e the data of dissimilar type. To define a structure, you must use the struct statement. The syntax of the struct statement is as follows:

Syntax: 

struct [structure tag] 

{

  member definition;

    member definition;

    ...

    member definition;

} [one or more structure variables];  

Example: 

#include <stdio.h>

#include <string.h>

  struct Book

 {

    char  title[50];

    char  author[50];

    char  subject[100];

    int   book_id;

};

  int main( )

  {

    struct Book Book1;   // Declare Book1 of type Book 

            // Specifications of the book

    strcpy( Book1.title, "C Programming");

   strcpy( Book1.author, "Balagurusamy"); 

    strcpy( Book1.subject, "C for beginners");

    Book1.book_id = 243678;

    // printing the specifications of the book

    printf( "Book 1 title : %s\n", Book1.title);

    printf( "Book 1 author : %s\n", Book1.author);

    printf( "Book 1 subject : %s\n", Book1.subject);

    printf( "Book 1 book_id : %d\n", Book1.book_id);

   return 0;

}

 

a) Pointer to structure: A pointer can be assigned to structure the same way a variable is assigned. 

Syntax: struct Student *struct_pointer;

The address of the structure variable can be stored in the pointer variable by using & operator. 

Syntax: struct_pointer = &stu1;

The members of a structure can be accessed by using the -> operator in the case of pointers.

Syntax: struct_pointer->name;

Example: 

#include <stdio.h>

#include <string.h>

  struct Student 

{

    char name[50];

   char address[100];

    int class; 

    int   roll;

    };

/* function declaration */

void details( struct Student *stu );

int main( ) 

{

    struct Student stu1;        

    struct Student stu2;       

    strcpy( stu1.name, "Sahil Sharma");

    strcpy( stu1.address, "#345, Sector-45, Chandigarh"); 

    stu1.class= 5;

    stu1.roll = 13;

     strcpy( stu2.name, "Ramandeep Singh");

    strcpy( stu2.address, "#350, Sector-40, Chandigarh"); 

    stu2.class= 5;

    stu2.roll = 10;

     printf("First student details \n");

    details( &stu1 );

    printf("Second student details \n");

    details( &stu2 );

return 0;

}

void details( struct Student *stu ) 

{

    printf( "Student name : %s\n", stu->name);

    printf( "Student Address : %s\n", stu->address);

    printf( "Student Class : %d\n", stu->class);

    printf( "Student Roll Number : %d\n", stu->roll);

}

 

b) Array of Structure: When a database of any element is used in a huge amount, we prefer an Array of structures. For example: suppose we want to maintain a database of 200 students, Array of structures is used.

Example:

#include<stdio.h>  

#include <string.h>    

struct student

{    

int rollno;    

char name[10];    

};    

int main()

{    

int i;    

struct student st[5];    

printf("Enter Records of 5 students");    

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

{    

printf("\nEnter Rollno:");    

scanf("%d",&st[i].rollno);    

printf("\nEnter Name:");    

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

}    

printf("\nStudent Information List:");    

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

{    

printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);    

}    

    return 0;    

}

c) Array within a structure: A structure is a heterogeneous collection of data elements, which means it can hold members of various types like int, char, float, etc. Similarly, it can hold an array as its data member. A structure can access an array the same way it accesses other members. 

Example: 

#include<stdio.h>  

#include <string.h>    

struct student

{    

int rollno;    

char name[10];    

};    

int main()

{    

int i;    

struct student st[5];    

printf("Enter Records of 5 students");    

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

{    

printf("\nEnter Rollno:");    

scanf("%d",&st[i].rollno);    

printf("\nEnter Name:");    

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

}    

printf("\nStudent Information List:");    

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

{    

printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);    

}    

    return 0;    

}

5) Pointer in C:  A pointer is a variable that holds the address of another variable. Like other variables, we have to first declare the pointer before using it. Dynamic memory allocation is not possible without the use of pointers. The address of the variable can be accessed by using the ampersand sign (&). 

Syntax:

         type *var-name;

         int *p;

         double *p;

         float *p;

         char *p;

Steps to using a pointer: 

  • Define a variable.

  • Assign the address of a variable to a pointer.

  • finally, access the value at the address available in the pointer variable.

Example: 

#include <stdio.h>

int main () 

{

    int  var = 20;   /* actual variable declaration */

    int  *p;        /* pointer variable declaration */

p = &var;  /* store address of var in pointer variable*/

    printf("Address of var variable: %x\n", &var  );

/* address stored in pointer variable */

    printf("Address stored in p variable: %x\n", p );

/* access the value using the pointer */

    printf("Value of *p variable: %d\n", *p );

   return 0;

}

6) File I/O in C: A file can be used to store a large volume of data. Like other language following are the operations to be performed on files in C:

  • Creating a File

  • Opening a File

  • Reading a File

  • Writing a File

  • Closing a File

There are some file management functions are available in C:

Function Description
open () Creating a file or opening an existing file
fclose () Closing a file
fprintf () Writing a block of data to a file
fscanf () Reading a block of data from a file
getc () Reads a single character from a file
putc () Writes a single character to a file
getw () Reads an integer from a file
putw () Writing an integer to a file
fseek () Sets the position of a file pointer to a specified location
ftell () Returns the current position of a file pointer
rewind () Sets the file pointer at the beginning of a file

 

  • Creating a File: When you start working with files, the first step is to create a file. It is just a memory allocation nothing else than that.    

            Syntax: 

                 FILE *fp;

                 fp = fopen ("file_name", "mode");

It is a standard function that creates a file if it does not exist and also opens an existing file. Whenever you open or create a file, you have to specify what you are going to do with the file. Following are the different modes to be used to specify what you want to do with this file:

File mode Description
r Opens a file in read-only mode.  No deletion is allowed in this mode.
w Open a file for writing. If a file doesn’t exist it creates a file and allows writing in it. If the file already exists user can make changes to it.
a Open a file in append mode. If a file is in append mode, then the file is opened. The content within the file doesn't change.
r+ open for reading and writing from the beginning.
w+ open for reading, writing, and overwriting a file.
a+ open for reading and writing, appending to file.

 

  • Closing a File: When you open a file, you should have to close that file when all its operations are completed. This prevents the file from accidental damage.

Syntax:

fclose (file_pointer);

Example: 

FILE *p;

p  = fopen ("data.txt", "r");

fclose (p);

Example: Opening and Closing a file:

#include <stdio.h>

#include <stdlib.h>

int main()

{

    int roll,n,i;

    char name[20];

    FILE *fptr;

    fptr = fopen("C:\\program.txt","w");

    if(fptr == NULL)

    {

       printf("Error!");   

       exit(1);             

    }

     printf("Details of how many students you want to Enter: \n");

    scanf("%d",&n);

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

    {

    printf("Enter name: ");

   scanf("%s",name);

    printf("Enter roll number: ");

    scanf("%d",&roll);

    fprintf(fptr," Name: %s \n Roll Number: %d \n",name,roll);

    }

        fclose(fptr);

    return 0;

}

Example: Writing in an existing File: 

#include <stdio.h>

#include <stdlib.h>

int main()

{

    int roll,n,i;

    char name[20];

    char str[] = "Study Section\n";

    FILE *fptr;

    fptr = fopen("C:\\program.txt","w");

   if(fptr == NULL)

    {

       printf("Error!");   

       exit(1);             

   }

   printf("Details of how many students you want to Enter: \n");

    scanf("%d",&n);

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

    {

    printf("Enter name: ");

    scanf("%s",name);

    printf("Enter roll number: ");

    scanf("%d",&roll);

    fprintf(fptr," Name: %s \n Roll Number: %d \n",name,roll);

    }

    for (i = 0; str[i] != '\n'; i++) 

{

             /* write to file using fputc() function */

            fputc(str[i], fptr);

         }

       fclose(fptr);

       return 0;

}

This website uses cookies to improve user experience. By using our website you consent to all cookies in accordance with our Cookie Policy. More info. I Agree