C Programming



C Programming Language

C language is a general purpose and structured programming language developed by 'Dennis Ritchie' at AT &T's Bell Laboratories in the 1972s in USA.
It is also called as 'Procedure oriented programming language.'
C is not specially designed for specific applications areas like COBOL (Common Business-Oriented Language) or FORTRAN (Formula Translation). It is well suited for business and scientific applications. It has some various features like control structures, looping statements, arrays, macros required for these applications.
The C language has following numerous features as:
  • Portability
  • Flexibility
  • Effectiveness and efficiency
  • Reliability
  • Interactivity
Execution of C Program :
C program executes in following 4 (four steps).
  1. Creating a program :
An editor like notepad or wordpad C Editor is used to create a C program. This file contains a source code which consists of executable code. The file should be saved as '*.c' extension only.
  1. Compiling the program :
The next step is to compile the program. The code is compiled by using compiler. Compiler converts executable code to binary code i.e. object code.
  1. Linking a program to library :
The object code of a program is linked with libraries that are needed for execution of a program. The linker is used to link the program with libraries. It creates a file with '*.exe' extension.
  1. Execution of program :
The final executable file is then run by dos command prompt or by any other software.

 

History of C :


Year of Establishment
Language Name
Developed By
1960
ALGOL-60
Cambridge University
1963
CPL (Combined Programming Language)
Cambridge University
1967
BCPL (Basic Combined Programming Language)
Martin Richard at Cambridge University
1970
B
Ken Thompson at AT & T's Bell Laboratories.
1972
C
Dennis Ritchie at AT & T' Bell Laboratory.

The development of C was a cause of evolution of programming languages like Algol 60, CPL (Combined Programming Langauge), BCPL (Basic Combined Programming Language) and B.

  • Algol-60 : (1963) :
ALGOL is an acronym for Algorithmic Language. It was the first structured procedural programming language, developed in the late 1950s and once widely used in Europe. But it was too abstract and too general structured langauage.
  • CPL : (1963) :
CPL is an acronym for Combined Programming Language. It was developed at Cambridge University.
  • BCPL : (1967) :
BCPL is an acronym for Basic Combined Programming Language. It was developed by Martin Richards at Cambridge University in 1967. BCPL was not so powerful. So, it was failed.
  • B : (1970) :
B language was developed by Ken Thompson at AT & T Bell Laboratories in 1970. It was machine dependent. So, it leads to specific problems.
  • C : (1972) :
'C' Programming Langauage was developed by Dennis Ritchie at AT & T Bell Laboratories in 1972. This is general purpose, compiled, structured programming langauage. Dennis Ritchie studied the BCPL, then improved and named it as 'C' which is the second letter of BCPL

Structure of C Program

The basic structure of C program is as follow:
Document Section
Links Section (File)
Definition Section
Global variable declaration Section
void main()
{
    Variable declaration section
    Function declaration section
    executable statements;
}
Function definition 1
---------------------
---------------------
Function definition n where,
Document Section : It consists of set of comment lines which include name of a program, author name, creation date and other information.
Links Section (File) : It is used to link the required system libraries or header files to excute a program.
Definition Section : It is used to define or set values to variables.
Global variable declaration Section : It is used to declare global or public variable.
void main() : Used to start of actual C program. It includes two parts as declaration part and executable part.
Variable declaration section : Used to declare private variable.
Function declaration section : Used to declare functions of program from which we get required output.
Then, executable statements are placed for execution.
Function definition section : Used to define functions which are to be called from main().

Character Set :

A character refers to the digit, alphabet or special symbol used to data represetation.
  1. Alphabets :                 A-Z, a-z
  2. Digits :                       0-9
  3. Special Characters :    ~ ! @ # $ % ^ & * ( ) _ + { } [ ] - < > , . / ? \ | : ; " '
  4. White Spaces :            Horizontal tab, Carriage return, New line, form feed

Identifier :

Identifier is the name of a variable that is made up from combination of alphabets, digits and underscore.

Variable :

It is a data name which is used to store data and may change during program execution. It is opposite to constant. Variable name is a name given to memory cells location of a computer where data is stored.
* Rules for varibales:
  • First character should be letter or alphabet.
  • Keywords are not allowed to use as a variable name.
  • White space is not allowed.
  • C is case sensitive i.e. UPPER and lower case are significant.
  • Only underscore, special symbol is allowed between two characters.
  • The length of indentifier may be upto 31 characters but only only the first 8 characters are significant by compiler.
  • (Note: Some compilers allow variable names whose length may be upto 247 characters. But, it is recommended to use maximum 31 characters in variable name. Large variable name leads to occur errors.)

Keywords :

Keywords are the system defined identifiers.
All keywords have fixed meanings that do not change.
White spaces are not allowed in keywords.
Keyword may not be used as an indentifier.
It is strongly recommended that keywords should be in lower case letters.
There are totally 32(Thirty Two) keywords used in a C programming.
int
float
double
long
short
signed
unsigned
const
if
else
switch
break
default
do
while
for
register
extern
static
struct
typedef
enum
return
sizeof
goto
union
auto
case
void
char
continue
volatile

Escape Sequence Characters (Backslash Character Constants) in C:

C supports some special escape sequence characters that are used to do special tasks.
These are also called as 'Backslash characters'.
Some of the escape sequence characters are as follow:
Character Constant
Meaning
\n
New line (Line break)
\b
Backspace
\t
Horizontal Tab
\f
Form feed
\a
Alert (alerts a bell)
\r
Carriage Return
\v
Vertical Tab
\?
Question Mark
\'
Single Quote
\''
Double Quote
\\
Backslash
\0
Null

Constants in C :

A constant is an entity that doesn't change during the execution of a program.
Followings are the different types of constants :

1. Real Constant :

  • It must have at least one digit.
  • It must have a decimal point which may be positive or negative.
  • Use of blank space and comma is not allowed between real constants.
  • Example:

+194.143, -416.41

2. Integer Constant :

  • It must have at least one digit.
  • It should not contain a decimal place.
  • It can be positive or negative.
  • Use of blank space and comma is not allowed between real constants.
  • Example:

1990, 194, -394

3. Character Constant :

  • It is a single alphabet or a digit or a special symbol enclosed in a single quote.
  • Maximum length of a character constant is 1.
  • Example:

'T', '9', '$'

4. String Constant :

  • It is collection of characters enclosed in double quotes.
  • It may contain letters, digits, special characters and blank space.
  • Example:

"Depot School"

Data Types in C :

"Data type can be defined as the type of data of variable or constant store."
When we use a variable in a program then we have to mention the type of data. This can be handled using data type in C.
Followings are the most commonly used data types in C.

Keyword
Format Specifier
Size
Data Range
char
%c
1 Byte
-128 to +127
unsigned char

8 Bytes
0 to 255
int
%d
2 Bytes
-32768 to +32767
long int
%ld
4 Bytes
-231 to +231
unsigned int
%u
2 Bytes
0 to 65535
float
%f
4 Bytes
-3.4e38 to +3.4e38
double
%lf
8 Bytes
-1.7e38 to +1.7e38
long double
%Lf
12-16 Bytes
-3.4e38 to +3.4e38

* Qualifier :

When qualifier is applied to the data type then it changes its size.
Size qualifiers : short, long
Sign qualifiers : signed, unsigned

* Enum Data Type :

This is an user defined data type having finite set of enumeration constants. The keyword 'enum' is used to create enumerated data type.
Syntax:
enum [data_type] {const1, const2, ...., const n};

Example:
#include <stdio.h>
int main()
{
enum Days{Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday};
Days TheDay;
int j = 0;
printf("Please enter the day of the week (0 to 6)\n");
scanf("%d",&j);
TheDay = Days(j);
if(TheDay == Sunday || TheDay == Saturday)
printf("Hurray it is the weekend\n");
else
printf("Curses still at work\n");
return 0;
}

* Typedef :

It is used to create new data type. But it is commonly used to change existing data type with another name.
Syntax:
typedef [data_type] synonym;
OR typedef [data_type] new_data_type;
Example:
#include <stdio.h>
void main ()
{
  typedef int my_type;
  my_type var1, var2, var3;
  var1 = 10;
  var2 = 20;
  var3 = 30;
}

Operators in C :

"Operator is a symbol that is used to perform mathematical operations."
When we use a variable in a program then we have to mention the type of data. This can be handled using data type in C.
Followings are the most commonly used data types in C.

Operator Name
Operators
Example
Assignment
=
#include <stdio.h>
#include <conio.h>
void main()
{
        int a,b;
        clrscr();
        a = 53;
        printf("\n\t Value of A : %d",a);       // 53
        b = a;  // Interchange of value using assignment
        printf("\n\n\t Value of B : %d",b);    // 53
        getch();
}


Arithmetic
+, -, *, /, %
#include <stdio.h>
#include <conio.h>
void main()
{
        int a,b,c,d,e,f,g;
        clrscr();
        printf("\n\t Enter First Number :");    // 5
        scanf("%d",&a);
        printf("\n\t Enter Second Number :");   // 2
        scanf("%d",&b);
        c = a + b;
        printf("\n\n\t Addition is : %d",c);   // 7
        d = a - b;
        printf("\n\n\t Subtraction is : %d",d);  // 3
        e = a * b;
        printf("\n\n\t Multiplication is : %d",e);  // 10
        f = a / b;
        printf("\n\n\t Division is : %d",f); // 2
        g = a % b;
        printf("\n\n\t Modulus is : %d",g); // 1
        getch();
} 

Logical
&&, ||, !
#include <stdio.h>
#include <conio.h>
 
void main()
{
        int no1=2, no2=5;
        clrscr();
        printf("\n\n %d",(no1 && no2));   // returns 1
        printf("\n\n %d",(no1 || no2));   // returns 1
        getch();
}

Relational
<, >, <=, >=, ==, !=
#include <stdio.h>
#include <conio.h>
 
void main()
{
        int a=6, b=2;
        clrscr();
        printf("\n\n A<=B : %d",(a<=b)); // 0 - False
        printf("\n\n A>B : %d",(a>b)); // 1 - True
        printf("\n\n A!=B : %d",(a!=b)); // 1 - True
        getch();
}

Shorthand
+=, -=, *=, /=, %=
#include <stdio.h>
#include <conio.h>
void main()
{
        int a,b;
        clrscr();
        a = 18;
        b = 4;
        printf("\n\t Value of A : %d",a);  // 18
        printf("\n\t Using of B : %d",b);  // 4
        b += a ;  // b = b + a
        printf("\n\n\t Using += (i.e b=b+a): %d",b); // 22
        // Change the operator as -=, *=, /=, %=
        getch();
}

Unary
++, --
#include <stdio.h>
#include <conio.h>
 
void main()
{
        int a=4, b;
        clrscr();
        printf("\n\n Value of A : %d",a); // 4
        a++; // Post
        printf("\n\n Value of A : %d",a); // 5
        ++a; // Pre
        printf("\n\n Value of A : %d",a); // 6
        b=--a;
        printf("\n\n Value of A : %d",a); // 5
        printf("\n\n Value of B : %d",b); // 5
        b=a++;
        printf("\n\n Value of A : %d",a); // 6
        printf("\n\n Value of B : %d",b); // 5
        b++;
        printf("\n\n Value of B : %d",b); // 6
        getch();
}

Conditional
()?:;
#include <stdio.h>
#include <conio.h>
void main()
{
        int a, b=3;
        clrscr();
        a = 5;
        printf("\n\n A is less than B ? ");
        
   
   // No
        getch();
}

Bitwise
&, |, ^, <<, >>, ~
#include <stdio.h>
#include <conio.h>
void main()
{
        int a=2, b=3,c;
        clrscr();
        c =a|b;
        printf("\n%d\n",c);
        getch();
}

Operators Precedence and Associativity :

In C, each and every operator has a spcial precedence which is associated with it. There are various levels of precedence. This precedence is especially used to determine to evaluation of expression which has more than one operator in it. The operators which has higher precedence are executed first and vice-versa. Operators which has same precedence level are evaluated from left to right. It is dependant on it's level. This feature is well known as 'Associativity of an operator.'
Category 
Operator 
Associativity 
Postfix 
() [] -> . ++ - -  
Left to right 
Unary 
+ - ! ~ ++ - - (type) * & sizeof  
Right to left 
Multiplicative  
* / % 
Left to right 
Additive  
+ - 
Left to right 
Shift  
<< >> 
Left to right 
Relational  
< <= > >= 
Left to right 
Equality  
== != 
Left to right 
Bitwise AND 
Left to right 
Bitwise XOR 
Left to right 
Bitwise OR 
Left to right 
Logical AND 
&& 
Left to right 
Logical OR 
|| 
Left to right 
Conditional 
?: 
Right to left 
Assignment 
= += -= *= /= %= >>= <<= &= ^= |= 
Right to left 
Comma 
Left to right 
Fig.: Precedence and Associativity of operators

Decision Making Statements / Conditional Statements :

C program executes program sequentially. Sometimes, a program requires checking of certain conditions in program execution. C provides various key condition statements to check condition and execute statements according conditional criteria.
These statements are called as 'Decision Making Statements' or 'Conditional Statements.'
Followings are the different conditional statements used in C.
  1. If Statement

Syntax:
 
if(condition)
{
       statements;
}

Example:
#include <stdio.h>
#include <conio.h>
void main()
{
       int a;
       a=5;
       clrscr();
       if(a>4)
              printf("\nValue of A is greater than 4 !");
       if(a==4)
              printf("\n\n Value of A is 4 !");
       getch();
}


  1. If-Else Statement

Syntax:
 
if(condition)
{
       true statements;
}
else
{
       false statements;
}
Example:
#include <stdio.h>
#include <conio.h>
void main()
{
       int no;
       clrscr();
       printf("\n Enter Number :");
       scanf("%d",&no);
       if(no%2==0)
              printf("\n\n Number is even !");
       else
              printf("\n\n Number is odd !");
       getch();
}


  1. Nested If-Else Statement

It is a conditional statement which is used when we want to check more than 1 conditions at a time in a same program. The conditions are executed from top to bottom checking each condition whether it meets the conditional criteria or not. If it found the condition is true then it executes the block of associated statements of true part else it goes to next condition to execute.
Syntax:
 
if(condition)
{
       if(condition)
       {
              statements;
       }
       else
       {
              statements;
       }
}
else
{
       statements;
}

Example:
#include <stdio.h>
#include <conio.h>
void main()
{
       int no;
       clrscr();
       printf("\n Enter Number :");
       scanf("%d",&no);
       if(no>0)
       {
              printf("\n\n Number is greater than 0 !");
       }
       else
       {
              if(no==0)
              {
                    printf("\n\n It is 0 !");
              }
              else
              {
                    printf("Number is less than 0 !");
              }
       }
       getch();
}


  1. Switch Case

This is a multiple or multiway brancing decision making statement.
When we use nested if-else statement to check more than 1 conditions then the complexity of a program increases in case of a lot of conditions. Thus, the program is difficult to read and maintain. So to overcome this problem, C provides 'switch case'.
Switch case checks the value of a expression against a case values, if condition matches the case values then the control is transferred to that point.

Syntax:
 
switch(expression)
{
       case expr1:
              statements;
              break;
       case expr2:
              statements;
              break;



       case exprn:
              statements;
              break;                                   
       default:
              statements;
}
In above syntax, switch, case, break are keywords.
expr1, expr2 are known as 'case labels.'
Statements inside case expression need not to be closed in braces.
Break statement causes an exit from switch statement.
Default case is optional case. When neither any match found, it executes.

Program :

#include <stdio.h>
#include <conio.h>
void main()
{
       int no;
       clrscr();
       printf("\n Enter any number from 1 to 3 :");
       scanf("%d",&no);
       switch(no)
       {
              case 1:
                    printf("\n\n It is 1 !");
                    break;
              case 2:
                    printf("\n\n It is 2 !");
                    break;
              case 3:
                    printf("\n\n It is 3 !");
                    break;
              default:
                    printf("\n\n Invalid number !");
       }
       getch();
}

* Rules for declaring switch case :

  • The case label should be integer or character constant.
  • Each compound statement of a switch case should contain break statement to exit from case.
  • Case labels must end with (:) colon.

* Advantages of switch case :

  • Easy to use.
  • Easy to find out errors.
  • Debugging is made easy in switch case.
  • Complexity of a program is minimized.

Looping Statements / Iterative Statements :

'A loop' is a part of code of a program which is executed repeatedly.
A loop is used using condition. The repetition is done until condition becomes condition true.
A loop declaration and execution can be done in following ways.
  • Check condition to start a loop
  • Initialize loop with declaring a variable.
  • Executing statements inside loop.
  • Increment or decrement of value of a variable.

* Types of looping statements :

Basically, the types of looping statements depends on the condition checking mode. Condition checking can be made in two ways as : Before loop and after loop. So, there are 2(two) types of looping statements.
  • Entry controlled loop
  • Exit controlled loop
1. Entry controlled loop :
In such type of loop, the test condition is checked first before the loop is executed.
Some common examples of this looping statements are :


This is an entry controlled looping statement.
In this loop structure, more than one variable can be initilized. One of the most important feature of this loop is that the three actions can be taken at a time like variable initilisation, condition checking and increment/decrement. The for loop can be more concise and flexible than that of while and do-while loops.
Syntax:
 
for(initialisation; test-condition; incre/decre)
{
       statements;
}
 
In above syntax, the given three expressions are seperated by ';' (Semicolon)
Features :
  • More concise
  • Easy to use
  • Highly flexible
  • More than one variable can be initilized.
  • More than one increments can be applied.
  • More than two conditions can be used.

Program :

#include <stdio.h>
#include <conio.h>
void main()
{
       int a;
       clrscr();
       for(i=0; i<5; i++)
       {
              printf("\n\t FundamentalOfComputing");  // 5 times
       }
       getch();
}

Nested for loop

Program :

#include <stdio.h>
#include <conio.h>
void main()
{
       int a,i;
       clrscr();
       for(i=0; i<3; i++)
       {
              printf("i=”%d\n”,i);
              for(a=1;a<=3;a++)
              {
              Printf(("a=%d\n”,a);
              }
       }
       getch();
}


This is an entry controlled looping statement. It is used to repeat a block of statements until condition becomes true.
Syntax:
 
while(condition)
{
       statements;
       increment/decrement;
}
In above syntax, the condition is checked first. If it is true, then the program control flow goes inside the loop and executes the block of statements associated with it. At the end of loop increment or decrement is done to change in variable value. This process continues until test condition satisfies.

Program :

#include <stdio.h>
#include <conio.h>
void main()
{
       int a;
       clrscr();
       a=1;
       while(a<=5)
       {
              printf("\n Depot School Dharan");
              a+=1      // i.e. a = a + 1
       }
       getch();
}

Do-While loop :

This is an exit controlled looping statement.
Sometimes, there is need to execute a block of statements first then to check condition. At that time such type of a loop is used. In this, block of statements are executed first and then condition is checked.
Syntax:
do
{
       statements;
       (increment/decrement);
}while(condition);
 
In above syntax, the first the block of statements are executed. At the end of loop, while statement is executed. If the resultant condition is true then program control goes to evaluate the body of a loop once again. This process continues till condition becomes true. When it becomes false, then the loop terminates.
Note: The while statement should be terminated with ; (semicolon).

Program :

#include <stdio.h>
#include <conio.h>
void main()
{
       int a;
       clrscr();
       a=1;
       do
       {
              printf("\n\t FundamentalOfComputing");  // 5 times
              a+=1;      // i.e. a = a + 1
       }while(a<=5);
       a=6;
       do
       {
              printf("\n\n\t Technowell");  // 1 time
              a+=1;      // i.e. a = a + 1
       }while(a<=5);
       getch();
}

Break Statement :

Sometimes, it is necessary to exit immediately from a loop as soon as the condition is satisfied.
When break statement is used inside a loop, then it can cause to terminate from a loop. The statements after break statement are skipped.
Syntax :
 
       break;
 
Figure : 
 

 
 

Program :

#include <stdio.h>
#include <conio.h>
void main()
{
       int i;
       clrscr();
       for(i=1;  ; i++)
       {
              if(i>5)
              break;
              printf("%d",i);  // 5 times only
       }
       getch();
}

Output :

12345


Continue Statement :

Sometimes, it is required to skip a part of a body of loop under specific conditions. So, C supports 'continue' statement to overcome this anomaly.
The working structure of 'continue' is similar as that of that break statement but difference is that it cannot terminate the loop. It causes the loop to be continued with next iteration after skipping statements in between. Continue statement simply skips statements and continues next iteration.
Syntax :
 
       continue;
 
Figure :

 
 

Program :

#include <stdio.h>
#include <conio.h>
void main()
{
       int i;
       clrscr();
       for(i=1; i<=10; i++)
       {
              if(i==6)
              continue;
              printf("\n\t %d",i);  // 6 is omitted
       }
       getch();
}

Output :

        1
        2
        3
        4
        5
        7
        8
        9
        10

Goto Statement :

It is a well known as 'jumping statement.' It is primarily used to transfer the control of execution to any place in a program. It is useful to provide branching within a loop.
When the loops are deeply nested at that if an error occurs then it is difficult to get exited from such loops. Simple break statement cannot work here properly. In this situations, goto statement is used.
Syntax :
 
       goto [expr];
 
Figure :
 

 
 

Program :

#include <stdio.h>
#include <conio.h>
void main()
{
       int i=1, j;
       clrscr();
       while(i<=3)
       {
              for(j=1; j<=3; j++)
              {
                    printf(" * ");
                    if(j==2)
                    goto stop;
              }
              i = i + 1;
       }
       stop:
              printf("\n\n Exited !");
       getch();
}

Output :

 *  *
 Exited

Contents :

1.      Functions

2.      Types of Functions :

3.      Built In Functions

4.      User Defined Functions

5.      Function Call By Passing Value

6.      Function Call By Returning Value

7.      Function Call By Passing and Returning Value

8.      Advantages

9.      Recursion (Recursive Function)

Functions in C :

The function is a self contained block of statements which performs a coherent task of a same kind.
C program does not execute the functions directly. It is required to invoke or call that functions. When a function is called in a program then program control goes to the function body. Then, it executes the statements which are involved in a function body. Therefore, it is possible to call fuction whenever we want to process that functions statements.

Types of functions :

There are 2(two) types of functions as:
1. Built in Functions
2. User Defined Functions


1. Built in Functions :
These functions are also called as 'library functions'. These functions are provided by system. These functions are stored in library files. e.g.
  • scanf()
  • printf()
  • strcpy
  • strlwr
  • strcmp
  • strlen
  • strcat
1. User Defined Functions :
The functions which are created by user for program are known as 'User defined functions'.
Syntax:
 
void main()
{
       // Function prototype
       <return_type><function_name>([<argu_list>]);
       
       // Function Call
       <function_name>([<arguments>]);
}
// Function definition
<return_type><function_name>([<argu_list>]);
{
       <function_body>;
}
 

Program :

#include <stdio.h>
#include <conio.h>
 
void add()
{
       int a, b, c;
       clrscr();
       printf("\n Enter Any 2 Numbers : ");
       scanf("%d %d",&a,&b);
       c = a + b;
       printf("\n Addition is : %d",c);
}
void main()
{
       void add();
       add();
       getch();
}

Output :

 Enter Any 2 Numbers : 23 6
 Addition is : 29




Function Call by Passing Value :

When a function is called by passing value of variables then that function is known as 'function call by passing values.'
Syntax:
 
// Declaration
void <function_name>(<data_type><var_nm>);
 
// Calls
<function_name>(<var_nm>);
 
// Definition
void <function_name>(<data_type><var_nm>);
{
       <function_body>;
       - - - - - - - -;
}

Program :

#include <stdio.h>
#include <conio.h>
 
void printno(int a)
{
       printf("\n Number is : %d", a);
}
void main()
{
       int no;
       void printno(int);
       clrscr();
       printf("\n Enter Number : ");
       scanf("%d", &no);
       printno(no);
       getch();
}

Output :

 Enter Number : 21
 Number is : 21_




Function Call by Returning Value :

When a function returns value of variables then that function is known as 'function call by returning values.'
Syntax:
 
// Declaration
<data_type><function_name>();
 
// Calls
<variable_of_function>=<function_nm>();
 
// Definition
<data_type><function_name>()
{
       <function_body>;
       - - - - - - - -;
       return <variable_of_function>;
}

Program :

#include <stdio.h>
#include <conio.h>
 
int number()
{
       int no;
       printf("\n Enter Number : ");
       scanf("%d",&no);
       return no;
}
void main()
{
       int no;
       int number();
       clrscr();
       no = number();
       printf("\n Number is : %d",no);
       getch();
}

Output :

 Enter Number : 5
 Number is : 5_

Function Call by Passing and Returning Value :

When a function passes and returns value of variables then that function is known as 'function call by passing and returning values.'

Program :


/* Program to demonstrate function call by passing 



#include <stdio.h>
#include <conio.h>
 
int number(int n)
{
       return n;
}
void main()
{
       int number(int);
       int a = number(4);
       clrscr();
       printf("\n Number is : %d",a);
       getch();
}

Output :


 Number is : 4_



Recursion (Recursive Function) :

When a function of body calls the same function then it is called as 'recursive function.'
Example:
 
Recursion()
{
       printf("Recursion !");
       Recursion();
}

Program :

#include <stdio.h>
#include <conio.h>
 
Recursion()
{
       int no;
       printf("\nRecursion... ");
       printf("\n\n Enter Number : ");
       scanf("%d",&no);
       if (no==3)
              exit(0);
       else
              Recursion();
}
void main()
{
       clrscr();
       Recursion();
}

Output :

Recursion...
 Enter Number : 2
Recursion...
 Enter Number : 1
Recursion...
 Enter Number : 3_





Function Advantages :
  • It is easy to use.
  • Debugging is more suitable for programs.
  • It reduces the size of a program.
  • It is easy to understand the actual logic of a program.
  • Highly suited in case of large programs.
  • By using functions in a program, it is possible to construct modular and structured programs.

Storage Class :

'Storage' refers to the scope of a variable and memory allocated by compiler to store that variable. Scope of a variable is the boundary within which a varible can be used. Storage class defines the the scope and lifetime of a variable.
From the point view of C compiler, a variable name identifies physical location from a computer where varaible is stored. There are two memory locations in a computer system where variables are stored as : Memory and CPU Registers.
Functions of storage class :
To detemine the location of a variable where it is stored ?
Set initial value of a variable or if not specified then setting it to default value.
Defining scope of a variable.
To determine the life of a variable.

Types of Storage Classes :

Storage classes are categorized in 4 (four) types as,

Automatic Storage Class :

  • Keyword : auto
  • Storage Location : Main memory
  • Initial Value : Garbage Value
  • Life : Control remains in a block where it is defined.
  • Scope : Local to the block in which variable is declared.
Syntax :
 
       auto [data_type] [variable_name];
       
Example :
 
       auto int a;
       

Program :

#include <stdio.h>
#include <conio.h>
void main()
{
       auto int i=10;
       clrscr();
       {
              auto int i=20;
              printf("\n\t %d",i);
       }
       printf("\n\n\t %d",i);
       getch();
}

Output :

        20
        10

Register Storage Class :

  • Keyword : register
  • Storage Location : CPU Register
  • Initial Value : Garbage
  • Life : Local to the block in which variable is declared.
  • Scope : Local to the block.
Syntax :
 
       register [data_type] [variable_name];
       
Example :
 
       register int a;
       
When the calculations are done in CPU, then the value of variables are transferred from main memory to CPU. Calculations are done and the final result is sent back to main memory. This leads to slowing down of processes.
Register variables occur in CPU and value of that register variable is stored in a register within that CPU. Thus, it increases the resultant speed of operations. There is no waste of time, getting variables from memory and sending it to back again.
It is not applicable for arrays, structures or pointers.
It cannot not used with static or external storage class.
Unary and address of (&) cannot be used with these variables as explicitly or implicitly.

Program :

#include <stdio.h>
#include <conio.h>
 
void main()
{
       register int i=10;
       clrscr();
       {
              register int i=20;
              printf("\n\t %d",i);
       }
       printf("\n\n\t %d",i);
       getch();
}

Output :

        20
        10


Static Storage Class :

  • Keyword : static
  • Storage Location : Main memory
  • Initial Value : Zero and can be initialize once only.
  • Life : depends on function calls and the whole application or program.
  • Scope : Local to the block.
Syntax :
 
       static [data_type] [variable_name];
       
Example :
 
       static int a;
       
There are two types of static variables as :

a) Local Static Variable
b) Global Static Variable
Static storage class can be used only if we want the value of a variable to persist between different function calls.

Program :

#include <stdio.h>
#include <conio.h>
 
void main()
{
       int i;
       void incre(void);
       clrscr();
       for (i=0; i<3; i++)
       incre();
       getch();
}
 
void incre(void)
{
       int avar=1;
       static int svar=1;
       avar++;
       svar++;
       printf("\n\n Automatic variable value : %d",avar);
       printf("\t Static variable value : %d",svar);
}

Output :

Automatic variable value : 2   Static variable value : 2
Automatic variable value : 2   Static variable value : 3
Automatic variable value : 2   Static variable value : 4_


External Storage Class :

  • Keyword : extern
  • Storage Location : Main memory
  • Initial Value : Zero
  • Life : Until the program ends.
  • Scope : Global to the program.
Syntax :
 
       extern [data_type] [variable_name];
       
Example :
 
       extern int a;
       
The variable access time is very fast as compared to other storage classes. But few registers are available for user programs.
The variables of this class can be referred to as 'global or external variables.' They are declared outside the functions and can be invoked at anywhere in a program.

Program :

#include <stdio.h>
#include <conio.h>
 
extern int i=10;
void main()
{
       int i=20;
       void show(void);
       clrscr();
       printf("\n\t %d",i);
       show();
       getch();
}
void show(void)
{
       printf("\n\n\t %d",i);
}

Output :

        20
        10_


Array :

Array is a collection of homogenous data stored under unique name. The values in an array is called as 'elements of an array.' These elements are accessed by numbers called as 'subscripts or index numbers.' Arrays may be of any variable type.
Array is also called as 'subscripted variable.'

Types of an Array :

1.      One / Single Dimensional Array

2.      Two Dimensional Array

Single / One Dimensional Array :

The array which is used to represent and store data in a linear form is called as 'single or one dimensional array.'
Syntax:
 
       <data-type> <array_name> [size];
 
Example:
 
       int a[3] = {2, 3, 5};
       char ch[20] = "FundamentalOfComputing" ;
       float stax[3] = {5003.23, 1940.32, 123.20} ;
       
Total Size (in Bytes):
 
       total size = length of array * size of data type
       
In above example, a is an array of type integer which has storage size of 3 elements. The total size would be 3 * 2 = 6 bytes.

* Memory Allocation :

           
 
    Fig : Memory allocation for one dimensional array

Program :

#include <stdio.h>
#include <conio.h>
void main()
{
       int a[3], i;;
       clrscr();
       printf("\n\t Enter three numbers : ");
       for(i=0; i<3; i++)
       {
              scanf("%d", &a[i]);  // read array
       }
       printf("\n\n\t Numbers are : ");
       for(i=0; i<3; i++)
       {
              printf("\t %d", a[i]);  // print array
       }
       getch();
}

Output :


 
        Enter three numbers : 9 4 6
        
        Numbers are :  9       4       6_




Features :
  • Array size should be positive number only.
  • String array always terminates with null character ('\0').
  • Array elements are countered from 0 to n-1.
  • Useful for multiple reading of elements (numbers).

Disadvantages :
  • There is no easy method to initialize large number of array elements.
  • It is difficult to initialize selected elements.


Two Dimensional Array :

The array which is used to represent and store data in a tabular form is called as 'two dimensional array.' Such type of array specially used to represent data in a matrix form.
The following syntax is used to represent two dimensional array.
Syntax:
 
<data-type> <array_nm> [row_subscript][column-subscript];
 
Example:
 
       int a[3][3];
       
In above example, a is an array of type integer which has storage size of 3 * 3 matrix. The total size would be 3 * 3 * 2 = 18 bytes.
It is also called as 'multidimensional array.'

* Memory Allocation :

           
 
    Fig : Memory allocation for two dimensional array

Program :

#include <stdio.h>
#include <conio.h>
void main()
{
       int a[3][3], i, j;
       clrscr();
       printf("\n\t Enter matrix of 3*3 : ");
       for(i=0; i<3; i++)
       {
              for(j=0; j<3; j++)
              {
              scanf("%d",&a[i][j]);  //read 3*3 array
              }
       }
       printf("\n\t Matrix is : \n");
       for(i=0; i<3; i++)
       {
              for(j=0; j<3; j++)
              {
              printf("\t %d",a[i][j]);  //print 3*3 array
              }
          printf("\n");
       }
       getch();
}

Output :


 
        Enter matrix of 3*3 : 3 4 5 6 7 2 1 2 3
        
        Matrix is :
        3       4       5
        6       7       2
        1       2       3_




Limitations of two dimensional array :
  • We cannot delete any element from an array.
  • If we don’t know that how many elements have to be stored in a memory in advance, then there will be memory wastage if large array size is specified.



Structure :

Structure is user defined data type which is used to store heterogeneous data under unique name. Keyword 'struct' is used to declare structure.
The variables which are declared inside the structure are called as 'members of structure'.
Syntax:
struct structure_nm
{
       <data-type> element 1;
       <data-type> element 2;
       - - - - - - - - - - -
       - - - - - - - - - - -
       <data-type> element n;
}struct_var;




Example :
 
struct emp_info
{
       char emp_id[10];
       char nm[100];
       float sal;
}emp;

Note :
1. Structure is always terminated with semicolon (;).
2. Structure name as emp_info can be later used to declare structure variables of its type in a program.

* Instances of Structure :

Instances of structure can be created in two ways as,
Instance 1:
 
struct emp_info
{
       char emp_id[10];
       char nm[100];
       float sal;
}emp;




Instance 2:
 
struct emp_info
{
       char emp_id[10];
       char nm[100];
       float sal;
};
struct emp_info emp;
In above example, emp_info is a simple structure which consists of stucture members as Employee ID(emp_id), Employee Name(nm), Employee Salary(sal).

* Aceessing Structure Members :

Structure members can be accessed using member operator '.' . It is also called as 'dot operator' or 'period operator'.
structure_var.member;

 

Program :

#include <stdio.h>
#include <conio.h>
 
struct comp_info
{
       char nm[100];
       char addr[100];
}info;
 
void main()
{
       clrscr();
       printf("\n Enter Company Name : ");
       gets(info.nm);
       printf("\n Enter Address : ");
       gets(info.addr);
       printf("\n\n Company Name : %s",info.nm);
       printf("\n\n Address : %s",info.addr);
       getch();
}

Output :

 Enter Company Name : CODES
 Enter Address : Dharan-9
 
 Company Name : CODES
 Address : Dharan-9





Pointer :

Pointer is a variable which holds the memory address of another variable. Pointers are represented by '*'. It is a derive data type in C. Pointer returns the value of stored address.
Syntax:
 
       <data_type> *pointer_name;
       
In above syntax,
* = variable pointer_name is a pointer variable.
pointer_name requires memory location
pointer_name points to a variable of type data type.
How to Use ?
       
       int *tot;
 
Illustration :
 
       int tot = 95;
       
Figure :
              
 
In above example, the statement instructs the system to find out a location for integer variable quantity and puts the values 95 in that memory location.
* Features of Pointer :

* Pointer variable should have prefix '*'.
* Combination of data types is not allowed.
* Pointers are more effective and useful in handling arrays.
* It can also be used to return multiple values from a funtion using function arguments.
* It supports dynamic memory management.
* It reduces complexity and length of a program.
* It helps to improve execution speed that results in reducing program execution time.

Program :

#include <stdio.h>
#include <conio.h>
 
void main()
{
       int a=10;
       int *ptr;
       clrscr();
       ptr = &a;
       printf("\n\t Value of a : %d", a);
       scanf("\n\n\t Value of pointer ptr : %d", *ptr);
       printf("\n\n\t Address of pointer ptr : %d", ptr);
       getch();
}

Output :


        Value of a : 10
        
        Value of pointer ptr : 10
        
        Address of pointer ptr : -12_



Union :

Union is user defined data type used to stored data under unique variable name at single memory location.
Union is similar to that of structure. Syntax of union is similar to structure. But the major difference between structure and union is 'storage.' In structures, each member has its own storage location, whereas all the members of union use the same location. Union contains many members of different types, it can handle only one member at a time.
To declare union data type, 'union' keyword is used.
Union holds value for one data type which requires larger storage among their members.
Syntax:
 
       union union_name
       {
              <data-type> element 1;
              <data-type> element 2;
              <data-type> element 3;
       }union_variable;
 
Example:
 
       union techno
       {
              int comp_id;
              char nm;
              float sal;
       }tch;
       
In above example, it declares tch variable of type union. The union contains three members as data type of int, char, float. We can use only one of them at a time.

* Memory Allocation :

           
 
        Fig : Memory allocation for union

To access union members, we can use the following syntax.
       tch.comp_id
       tch.nm
       tch.sal

Program :


#include <stdio.h>
#include <conio.h>
 
union techno
{
       int id;
       char nm[50];
}tch;
 
 
void main()
{
       clrscr();
       printf("\n\t Enter developer id : ");
       scanf("%d", &tch.id);
       printf("\n\n\t Enter developer name : ");
       scanf("%s", tch.nm);
       printf("\n\n Developer ID : %d", tch.id);//Garbage 
       printf("\n\n Developed By : %s", tch.nm);
       getch();
}

Output :

        Enter developer id : 101
        
        Enter developer name : technowell
        
Developer ID : 25972
 
Developed By : technowell_




String Handling in C :

String :
A string is a collection of characters. Strings are always enlosed in double quotes as "string_constant".
Strings are used in string handling operations such as,
  • Counting the length of a string.
  • Comparing two strings.
  • Copying one string to another.
  • Converting lower case string to upper case.
  • Converting upper case string to lower case.
  • Joining two strings.
  • Reversing string.

Declaration :

The string can be declared as follow :
Syntax:
 
       char string_nm[size];
 
Example:
 
       char name[50];
       

String Structure :

When compiler assigns string to character array then it automatically supplies null character ('\0') at the end of string. Thus, size of string = original length of string + 1.
 
       char name[7];
       name = "TECHNO"
       

 
 

Read Strings :

To read a string, we can use scanf() function with format specifier %s.
 
       char name[50];
       scanf("%s",name);
       
The above format allows to accept only string which does not have any blank space, tab, new line, form feed, carriage return.

Write Strings :

To write a string, we can use printf() function with format specifier %s.
 
       char name[50];
       scanf("%s",name);
       printf("%s",name);
       

string.h header file


'string.h' is a header file which includes the declarations, functions, constants of string handling utilities. These string functions are widely used today by many programmers to deal with string operations.
Some of the standard member functions of string.h header files are,
Function Name
Description
strlen -
Returns the length of a string.
strlwr -
Returns upper case letter to lower case.
strupr -
Returns lower case letter to upper case.
strcat -
Concatenates two string.
strcmp -
Compares two strings.
strrev -
Returns length of a string.
strcpy -
Copies a string from source to destination.

Program :

#include <stdio.h>
#include <conio.h>
#include <string.h>
void main()
{
       char str[50];
       clrscr();
       printf("\n\t Enter your name : ");
       gets(str);
       printf("\nLower case of string: %s",strlwr(str));
       printf("\nUpper case of string: %s",strupr(str));
       printf("\nReverse of string: %s",strrev(str));
       printf("\nLength of String: %d",strlen(str));
       getch();
}

Output :

Enter your name : FundamentalOfComputing
Lower case of string: fundamentalofcomputing
Upper case of string: FUNDAMENTALOFCOMPUTING
Reverse of string: GNITUPMOCFOLATNEMADNUF  
Length of String: 22_








File Handling in C

To work with files, the library routines must be included into your programs. This is done by the statement,
 
        #include <stdio.h>
as the first statement of your program.
File operation functions in C:

Function Name
Operation
fopen()
Creates a new file. Opens an existing file.
fclose
Closes a file which has been opened for use
getc()
Reads a character from a file
putc()
Writes a character to a file
fprintf()
Writes a set of data values to a file
fscanf()
Reads a set of data values from a file
getw()
Reads a integer from a file
putw()
Writes an integer to the file
fseek()
Sets the position to a desired point in the file
ftell()
Gives the current position in the file
rewind()
Sets the position to the beginning of the file
Simple Example:
#include
void main(void)
{
FILE *myfile;
char c;
myfile = fopen("firstfile.txt", "r");
if (myfile == NULL) printf("File doesn't exist\n");
else {
do {
c = getc(myfile);

putchar(c);

} while (c != EOF);

}
fclose(myfile);

}
USING FILES
  • Declare a variable of type FILE
    To use files in C programs, you must declare a file variable to use. This variable must be of type FILE, and be declared as a pointer type.
FILE is a predefined type. You declare a variable of this type as

         FILE  *in_file;
This declares infile to be a pointer to a file.
  • Associate the variable with a file using fopen()
    Before using the variable, it is associated with a specific file by using the fopen() function, which accepts the pathname for the file and the access mode (like reading or writing).
·          
·                  in_file = fopen( "myfile.dat", "r" );
In this example, the file myfile.dat in the current directory is opened for read access.
  • Process the data in the file
    Use the appropriate file routines to process the data
  • When finished processing the file, close it
    Use the fclose() function to close the file.
·          
·                  fclose( in_file );

The following illustrates the fopen function, and adds testing to see if the file was opened successfully.

        #include <stdio.h>
        /* declares pointers to an input file, and the fopen function */
        FILE   *input_file, *fopen ();

        /* the pointer of the input file is assigned the value returned from the fopen call. */
        /* fopen tries to open a file called datain for read only. Note that */
        /* "w" = write, and "a" = append.  */
        input_file = fopen("datain", "r");

        /* The pointer is now checked. If the file was opened, it will point to the first */
        /* character of the file. If not, it will contain a NULL or 0. */
        if( input_file == NULL ) {
               printf("*** datain could not be opened.\n");
               printf("returning to dos.\n");
               exit(1);
        }


NOTE: Consider the following statement, which combines the opening of the file and its test to see if it was successfully opened into a single statement.

        if(( input_file = fopen ("datain", "r" )) == NULL ) {
               printf("*** datain could not be opened.\n");
               printf("returning to dos.\n");
               exit(1);
        }

INPUTTING/OUTPUTTING SINGLE CHARACTERS
Single characters may be read/written with files by use of the two functions, getc(), and putc().
 
        int ch;
 
        ch = getc( input_file );   /*  assigns character to ch  */
 
The getc() also returns the value EOF (end of file), so
 
        while( (ch = getc( input_file )) != EOF )
               ......................
 
NOTE that the putc/getc are similar to getchar/putchar except that arguments are supplied specifying the I/O device.
 
        putc('\n', output_file ); /* writes a newline to output file */
 

CLOSING FILES
When the operations on a file are completed, it is closed before the program terminates. This allows the operating system to cleanup any resources or buffers associated with the file. The fclose() function is used to close the file and flush any buffers associated with the file.

        fclose( input_file );
        fclose( output_file );

COPYING A FILE
The following demonstrates copying one file to another using the functions we have just covered.

        #include <stdio.h>

        main()   /* FCOPY.C    */
        {
               char in_name[25], out_name[25];
               FILE *in_file, *out_file, *fopen ();
               int c;

               printf("File to be copied:\n");
               scanf("%24s", in_name);
               printf("Output filename:\n");
               scanf("%24s", out_name);

               in_file = fopen ( in_name, "r");

               if( in_file == NULL )
                       printf("Cannot open %s for reading.\n", in_name);
               else {
                       out_file = fopen (out_name, "w");
                       if( out_file == NULL )
                               printf("Can't open %s for writing.\n",out_name);
                       else {
                               while( (c = getc( in_file)) != EOF )
                                      putc (c, out_file);
                               putc (c, out_file);   /* copy EOF */
                               printf("File has been copied.\n");
                               fclose (out_file);
                       }
                       fclose (in_file);
               }
        }

TESTING FOR THE End Of File TERMINATOR (feof)
This is a built in function incorporated with the stdio.h routines. It returns 1 if the file pointer is at the end of the file.
 
        if( feof ( input_file ))
               printf("Ran out of data.\n");

THE fprintf AND fscanf STATEMENTS
These perform the same function as printf and scanf, but work on files. Consider,
 
        fprintf(output_file, "Now is the time for all..\n");
        fscanf(input_file, "%f", &float_value);
 
THE fgets AND fputs STATEMENTS
These are useful for reading and writing entire lines of data to/from a file. If buffer is a pointer to a character array and n is the maximum number of characters to be stored, then

        fgets (buffer, n, input_file);
will read an entire line of text (max chars = n) into buffer until the newline character or n=max, whichever occurs first. The function places a NULL character after the last character in the buffer. The function will be equal to a NULL if no more data exists.

        fputs (buffer, output_file);
writes the characters in buffer until a NULL is found. The NULL character is not written to the output_file.
NOTE: fgets does not store the newline into the buffer, fputs will append a newline to the line written to the output file.


Header File in C :

Header file contains different predefined functions, which are required to run the program. All header files should be included explicitly before main ( ) function.
It allows programmers to seperate functions of a program into reusable code or file. It contains declarations of variables, subroutines. If we want to declare identifiers in more than one source code file then we can declare such identifiers in header file. Header file has extension like '*.h'. The prototypes of library functions are gathered together into various categories and stored in header files.
E.g. All prototypes of standard input/output functions are stored in header file 'stdio.h' while console input/output functions are stored in 'conio.h'.
The header files can be defined or declared in two ways as
Method 1 : #include "header_file-name"
Method 2 : #include <header_file-name>
Method 1 is used to link header files in current directory as well as specified directories using specific path. The path must be upto 127 characters. This is limit of path declaration. Method 2 is used to link header files in specified directories only.

Standard Header Files :

Followings are the some commonly used header files which plays a vital role in C programming :

Assert.h

Ctype.h

Math.h

Process.h

Stdio.h

Stdlib.h

String.h

Time.h

Graphics.h

assert.h header file :

An assertion is a 'conditional check' placed in a program to indicate that the developer thinks that the condtion has to be always true, at that place, for the program to work properly after that point. If the condition happens to be false, the program execution would be abruptly aborted.

For example:
    assert (y!=0); /* The developer thinks that y shouldn't be equal to 0. If not, the code would get abhorted */
    z=x/y;
Whenever the program gets aborted because of an assertion, a corefile would be dumped.
Example1
#include <stdio.h>
#include <assert.h >
int main()
{
    int x,y,z;
    printf("Enter the 2 numbers to divide\n");
    scanf("%d %d",&x,&y);
    assert(y!=0);
    z=x/y;
    printf("x/y=%d\n",z);
    return;
}

Output:
Enter the 2 numbers to divide
3 0
Sample1: assert_test.c:8: main: Assertion `y!=0' failed.
Aborted

Example2
#include <conio.h>
#include <assert.h>
void main()
{
       clrscr();
       assert(12 == 2);
       getch();
}

Output :


Assertion failed: 12==2, file ..\ASSERT.C, line 5
Abnormal program termination


ctype.h (Character Functions header file):

It contains the declarations for character functions i.e. it contains information used by the character classification and character converstion macros.
Some of the standard member functions of ctype.h header files are,
Function Name
Description

isalnum -
checks for alphanumeric character.
isalpha -
checks for alphabetic character.
isxdigit -
checks for hexadecimal digit.
isupper -
checks for upper case character.
isspace -
checks for any whitespace character.
ispunct -
checks for punctuation character.
isdigit -
checks for digits.
islower -
checks for lower case characters.
isprint -
checks for printable character with space character.
isgraph -
checks for graphic character without space character.

Example :

#include <stdio.h>
#include <conio.h>
#include <ctype.h>
#include <string.h>
void main()
{
       int len, i;
       char *str = "FundamentalOfComputing";
       clrscr();
       len = strlen(str);
       for(i=1;i<=len;i++)
       {
              str[i] = tolower(str[i]); //tolower()
       }
       printf("\n\t Using tolower() : %s",str);
       for(i=1;i<=len;i++)
       {
              str[i] = toupper(str[i]); //toupper()
       }
       printf("\n\n\t Using toupper() : %s",str);
       getch();
}

Output :

        Using tolower() : FundamentalOfComputing

        Using toupper() : FUNDAMENTALOFCOMPUTING




math.h header file

math.h is a header file which is commonly used for mathematical operations. Some functions of this header file uses floating point numbers. The functions which accepts angle are accepted in terms of radians.
Some of the standard member functions of math.h header files are,
Function Name

Description
acos -
Arccosine - Returns inverse cosine.
cos -
Returns cosine.
log -
Returns log of a number.
pow(x,y) -
Returns power of x raise to y. i.e. xy
sqrt -
Returns square root of a number.
tan -
Returns tangent.
ceil -
Ceiling - Small int not less than that of parameter.
exp -
Uses as an Exponential function.
floor -
Floor - Largest int not greater than parameter.

Program :

#include <stdio.h>
#include <conio.h>
#include <math.h>
void main()
{
       clrscr();
       printf("\n\t Log of 10 : %f",log(10));
       printf("\n\n\t Square Root of 16 : %f",sqrt(16));
       printf("\n\n\t Square of 4 : %f",pow(4,2));
       printf("\n\n\t Sine of 10 : %f",sin(10));
       getch();
}

Output :

        Log of 10 : 2.302585

        Square Root of 16 : 4.000000

        Square of 4 : 16.000000

        Sine of 10 : -0.544021_



process.h header file

'process.h' is a header file which includes macros and declarations. These are especially used during work with thread and processes. There is no standard for process.h functions. They depend on compiler which we use.
Some of the standard member functions of process.h header files are,
Function Name

Description
execle -        
It loads & executes new child process by placing it in memory previously    occupied by the parent process.
spawnv -
process.
Parameters are passed as an array of pointers. It loads & executes new child

getpid -
It returns the process identifier.
execlp -        
It loads & executes a new child process by placing it in memory previously occupied by the parent process.

Program :

#include <stdio.h>
#include <conio.h>
#include <process.h>
void main()
{
       clrscr();
       // under DOS PSP segment
       printf("\n\t Program's process identification");
       printf(" number  is : %X",getpid());
       getch();
}

Output :

Program's process identification number (PID) number is : 8E01


stdio.h (Standard Input/Output Header File):

stdio.h refers to standard input/output header file. it is header file in C's standard library which contains constants, macros definitions and declarations of functions. It includes types used for various standard input and output operations.
The functions which are declared in stdio.h are very popular.
Member Functions :
Some of the standard member functions of stdio.h header files are,
Function Name

Description
scanf -
used to take input from the standard input stream
gets -
read characters from stdin while a new line is inserted
printf -
prints to the standard output stream
putc -
writes and returns a character to a stream
putchar -
It works as same of putc(stdout)
puts -
outputs a character string to stdout
fopen -
Opens a file to read or write
fwrite -
writes data to a file
fputs -
writes a string to a file
fread -
reads data from a file
fseek -
seeks file
fclose -
Closes a file
remove -
deletes or removes a file
rename -
renames a file
rewind -       
adjusts the specified file so that the next I/O operation will take place at the beginning of the file. "rewind" is equivalent to fseek(f,0L,SEEK_SET);

Program :

#include <stdio.h>
#include <conio.h>
void main()
{
       int no;
       clrscr();
       printf("\n\t Enter any number : ");
       scanf("%d",&no); // scanf()
       printf("\n\n\t Number is : %d",no); // printf()
       getch();
}

Output :

        Enter any number : 122

        Number is : 122_




stdlib.h (Standard Library header file):

'stdlib' is an acronym for Standard Library. It is header file of standard library in C which contains the functions like allocation of memory, conversions, process controls and other utilities.
Some of the standard member functions of stdlib.h header files are,
Function Name

Description
abs -
It returns the absolute value of a number.
atof -
It converts string into double value.
atoi -
It converts string into integer value.
atol -
It converts string into long integer value.
abort -
It terminates execution as abnormally.
exit -
It terminates execution of a program.
malloc -
It allocates memory from heap.
realloc -
It reallocates the memory.
calloc -
It allocates specific memory to array of object of sizes.
free -
Releases the momory.
rand -
It creates the series of pseudo numbers.
qsort -
It sorts an array.

Program :

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
void main()
{
      char no[10];
      clrscr();
      printf("\n\t Using abs(-194): %d",abs(-194)); // 1
      printf("\n\n\t Enter any number : ");
      scanf("%s",no);
      printf("\n\t Using atof() : %lf",atof(no)); // 2
      printf("\n\n\t Using atoi() : %d",atoi(no)); // 3
      getch();
}

Output :

        Using abs(-194) : 194



        Enter any number : 12



        Using atof() : 12.000000



        Using atoi() : 12_


string.h header file

'string.h' is a header file which includes the declarations, functions, constants of string handling utilities. These string functions are widely used today by many programmers to deal with string operations.
Some of the standard member functions of string.h header files are,
Function Name

Description
strlen -
Returns the length of a string.
strlwr -
Returns upper case letter to lower case.
strupr -
Returns lower case letter to upper case.
strcat -
Concatenates two string.
strcmp -
Compares two strings.
strrev -
Returns length of a string.
strcpy -
Copies a string from source to destination.

Program :

#include <stdio.h>
#include <conio.h>
#include <string.h>
void main()
{
      char str[50];
      clrscr();
      printf("\n\t Enter your name : ");
      gets(str);
      printf("\nLower case of string: %s",strlwr(str));
      printf("\nUpper case of string: %s",strupr(str));
      printf("\nReverse of string: %s",strrev(str));
      printf("\nLength of String: %d",strlen(str));
      getch();
}

Output :

Enter your name : FundamentalOfComputing
Lower case of string: fundamentalofcomputing
Upper case of string: FUNDAMENTALOFCOMPUTING
Reverse of string: MAXEONHCET  
Length of String: 10_


time.h header file

The header file as 'time.h' is used to declare date and time functions which are primarily used to access date/time for manipulations.
Some of the standard member functions of time.h header files are,
Function Name

Description
asctime -
Returns string : day month date hours:min:sec year
clock -
Returns time if exists otherwise -1.
ctime -
Returns current time.
difftime -
Returns the difference in seconds between two times.
gmtime -
Returns the Greenwitch Mean Time (GMT) / UTC.
localtime -
It returns local time.

Program :

#include <stdio.h>
#include <conio.h>
#include <time.h>
void main()
{
      struct tm, *lcl;
      time_t t1;
      clrscr();
      t1 = time(NULL);
      lcl = localtime(&t1);
      printf("\n\tLocal Date and Time: %s",asctime(lcl));
      lcl = gmtime(&t1);
      printf("\n\n\tUTC Date and Time: %s",asctime(lcl));
      getch();
}

Output :

        Local Date and Time : Sat Nov 06 14:36:27 2010



        UTC Date and Time : Sat Nov 06 19:36:27 2010_


graphics.h header file

The 'graphics.h' header file is used to declare graphics functions. It declares prototypes for the graphics functins.
Some of the standard member functions of graphics.h header files are,
Function Name

Description
initgraph -
Used to initilize graphics and load graphics driver.
line -
Used to draw a line as line(x1,y1,x2,y2).
bar -
Used to draw rectangle with diagonal, bar(x1,y1,x2,y2).
circle -
Used to draw circle, circle(x1,y1,radius).
cleardevice -
It clears the graphics screen.
closegraph -
Closes or shut downs graphics system.
rectangle -
Used to draw a rectangle.
setcolor -
It sets the current drawing color.
getcolor -
It returns the current drawing color.
floodfill -
Used to flood-fill bounded region.
settextstyle -
It sets current text features.
ellipse -
It draws ellipse, as ellipse(x,y,start,end,xrad,yrad).

Program :

/*  Program to demonstrate graphics.h header file working.



#include <stdio.h>
#include <conio.h>
#include <graphics.h>
void main()
{
      int gdriver=DETECT, gmode;
      clrscr();
      initgraph(&gdriver,&gmode,"c:\\tc\\bgi");
      circle(70,70,20);
      getch();
      closegraph();
}

Output :

 
        
 




SOME EXAMPLES OF C

Program to print pyramid in C : Pattern 1 :


Program :

#include <stdio.h>
#include <conio.h>
void main()
{
      int i,j;
      clrscr();
      for(i=0; i<5; i++)
      {
            for(j=0; j<5; j++)
            {
                  printf(" * ");
            }
            printf("\n");
      }
      getch();
}

Output :


 * * * * *
 * * * * *
 * * * * *
 * * * * *
 * * * * *_


Program :

#include <stdio.h>
#include <conio.h>
void main()
{
       int i,j;
       clrscr();
       for(i=0; i<5; i++)
       {
              for(j=0; j<=i; j++)
              {
                    printf(" * ");
              }
              printf("\n");
       }
       getch();
}

Output :


 * 
 * * 
 * * * 
 * * * *
 * * * * *_

Program :

#include <stdio.h>
#include <conio.h>
void main()
{
      int i,j,k;
      clrscr();
      for(i=1; i<=5; i++)
      {
            for(j=5; j>=i; j--)
            {
                  printf(" ");
            }
            for(k=1; k<=i; k++)
            {
                  printf("*");
            }
            printf("\n");
      }
      getch();
}

Output :


         *
       * *
     * * *
   * * * *
 * * * * *_

Program :

#include <stdio.h>
#include <conio.h>
void main()
{
      int i,j,k,samp=1;
      clrscr();
      for(i=5; i>=1; i--)
      {
            for(k=samp; k>=0; k--)
            {
                  printf(" "); // only 1 space
            }
            for(j=i; j>=1; j--)
            {
                  printf("*");
            }
            samp = samp + 1;
            printf("\n");
      }
      getch();
}

Output :


 * * * * *
   * * * *
     * * *
       * *
         *_

Program :

#include <stdio.h>
#include <conio.h>
void main()
{
      int i,j;
      clrscr();
      for(i=5; i>=1; i--)
      {
            for(j=1; j<=i; j++)
            {
                  printf(" * ");
            }
            printf("\n");
      }
      getch();
}

Output :


 * * * * *
 * * * *
 * * *
 * *
 *_

Program :

#include <stdio.h>
#include <conio.h>
void main()
{
       int i,j,k,t=0;
       clrscr();
       for(i=1; i<=5; i++)
       {
              for(k=t; k<5; k++)
              {
                    printf(" ");
              }
              for(j=0; j< i; j++)
              {
                    printf(" * ");
                    t = t + 1;
              }
              printf("\n");
       }
       getch();
}

Output :


     *
    * *
   * * *
  * * * *
 * * * * *_

Program :

#include <stdio.h>
#include <conio.h>
void main()
{
      int i,j,k,samp=1;
      clrscr();
      for(i=1; i<=5; i++)
      {
            for(k=samp; k<=5; k++)
            {
                  printf(" ");
            }
            for(j=0; j< i; j++)
            {
                  printf("*");
            }
            samp = samp + 1;
            printf("\n");
      }
      samp = 1;
      for(i=4; i>=1; i--)
      {
            for(k=samp; k>=0; k--)
            {
                  printf(" ");
            }
            for(j=i; j>=1; j--)
            {
                        printf("*");
            }
            samp = samp + 1;
            printf("\n");
      }
      getch();
}

Output :


         *
       * *
     * * *
   * * * *
 * * * * *
   * * * *
     * * *
       * *
         *_

Program :

#include <stdio.h>
#include <conio.h>
void main()
{
      int rw, c, no=1 ,len;
      clrscr();
      printf("Enter number of rows: ");
      scanf("%d," &len);
      for(rw=1; rw<=len; rw++)
      {
            printf("\n");
            for(c=1; c<=rw; c++)
            {
                  printf(" %2d ", no);
                  no++;
            }
      }
      getch();
}

Output :


Enter number of rows: 5
 
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15_

Program :

#include <stdio.h>
#include <conio.h>
void main()
{
      int no,i,y,x=35;
      clrscr();
      printf("Enter number of rows: ");
      scanf("%d," &no);
      for(y=0;y<=no;y++)
      {
            goto(x,y+1);
            for(i=0-y; i<=y; i++)
            {
                  printf(" %3d ", abs(i));
                  x=x-3;
            }
      }
      getch();
}

Output :


Enter number of rows: 5
 
          0          
        1 0 1        
      2 1 0 1 2      
    3 2 1 0 1 2 3    
  4 3 2 1 0 1 2 3 4  
5 4 3 2 1 0 1 2 3 4 5_

Program :

#include <stdio.h>
#include <conio.h>
void main()
{
      int i, j=5, k, x;
      clrscr();
      for(i=1;i<=5;i++)
      {
            for(k=1;k<=j;k++)
            {
                  printf(" ");
            }
            for(x=1;x<=i;x++)
            {
                  printf("%d",i);
                  printf(" ");
            }
            printf("\n");
            j=j-1;
      }
      getch();
}

Output :


    1    
   2 2   
  3 3 3  
 4 4 4 4 
5 5 5 5 5_

Program :

#include <stdio.h>
#include <conio.h>
void main()
{
      int i,j,k;
      clrscr();
      for(i=1; i<=5; i++)
      {
            for(j=1; j<=5-i; j++)
            {
                  printf("   ");
            }
            for(k=1; k<=2*i-1; k++)
            {
                  printf(" %d ",k);
            }
            printf("\n");
      }
      getch();
}

Output :


        1    
      1 2 3
    1 2 3 4 5
  1 2 3 4 5 6 7
1 2 3 4 5 6 7 8 9_


GRAPHICS Programming

Turbo C has a good collection of graphics libraries. If you know the basics of C, you can easily learn graphics programming. To start programming, let us write a small program that displays a circle on the screen.
/*  simple.c
    example 1.0
*/
#include<graphics.h>
#include<conio.h>

void main()
{
    int gd=DETECT, gm;

    initgraph(&gd, &gm, "c:\\turboc3\\bgi " );
    circle(200,100,150);

    getch();
    closegraph();
}

 
    To run this program, you need graphics.h header file, graphics.lib library file and Graphics driver (BGI file) in the program folder. These files are part of Turbo C package. In all our programs we used 640x480 VGA monitor. So all the programs are according to that specification. You need to make necessary changes to your programs according to your screen resolution. For VGA monitor, graphics driver used is EGAVGA.BGI.
    Here, initgraph() function initializes the graphics mode and clears the screen. We will study the difference between text mode and graphics mode in detail latter.
InitGraph:
Initializes the graphics system.

Declaration:
void far initgraph(int far *graphdriver, int far *graphmode, char far *pathtodriver);

Remarks: To start the graphics system, you must first call initgraph.

initgraph initializes the graphics system by loading a graphics driver from disk (or validating a registered driver) then putting the system into graphics mode.

initgraph also resets all graphics settings (color, palette, current position, viewport, etc.) to their defaults, then resets graphresult to 0.
Arguments:
*graphdriver: Integer that specifies the graphics driver to be used. You can give graphdriver a value using a constant of the graphics drivers enumeration type.
*graphmode : Integer that specifies the initial graphics mode (unless *graphdriver = DETECT). If *graphdriver = DETECT, initgraph sets *graphmode to the highest resolution available for the detected driver. You can give *graphmode a value using a constant of the graphics_modes enumeration type.
pathtodriver : Specifies the directory path where initgraph looks for graphics drivers (*.BGI) first.  If they're not there, initgraph looks in the current directory.  If pathtodriver is null, the driver files must be in the current directory.  This is also the path settextstyle searches for the stroked character font files (*.CHR).
    closegraph() function switches back the screen from graphcs mode to text mode. It clears the screen also. A graphics program should have a closegraph function at the end of graphics. Otherwise DOS screen will not go to text mode after running the program. Here, closegraph() is called after getch() since screen should not clear until user hits a key.
    If you have the BGI file in the same folder of your program, you can just leave it as "" only. you need not mention *graphmode if you give *graphdriver as DETECT.
   
    In graphics mode, all the screen co-ordinates are mentioned in terms of pixels. Number of pixels in the screen decides resolution of the screen. In the example 1.0,  circle is drawn with x-coordinate of the center 200, y-coordinate 100 and radius 150 pixels. All the coordinates are mentioned with respect to top-left corner of the screen.
Basic Shapes and Colors:
    Now let us write a program to draw some basic shapes.
/*
shapes.c
example 1.1
*/

#include<graphics.h>
#include<conio.h>

void main()
{
    int gd=DETECT, gm;
    int poly[12]={350,450, 350,410, 430,400, 350,350, 300,430, 350,450 };
    initgraph(&gd, &gm, "");

    circle(100,100,50);
    outtextxy(75,170, "Circle");
    rectangle(200,50,350,150);
    outtextxy(240, 170, "Rectangle");
    ellipse(500, 100,0,360, 100,50);
    outtextxy(480, 170, "Ellipse");
    line(100,250,540,250);
    outtextxy(300,260,"Line");

    sector(150, 400, 30, 300, 100,50);
    outtextxy(120, 460, "Sector");
    drawpoly(6, poly);
    outtextxy(340, 460, "Polygon");
    getch();
    closegraph();
}
Here is the screenshot of output:
    Here, circle() function takes x, y coordinates of the circle with respect to left top of the screen and radius of the circle in terms of pixels as arguments. Not that, in graphics, almost all the screen parameters are measured in terms of pixels.
    Function outtextxy() displays a string in graphical mode. You can use different fonts, text sizes, alignments, colors and directions of the text that we will study later. Parameters passed are x and y coordinates of the position on the screen where text is to be displayed. There is another function outtext() that displayes a text in the current position. Current position is the place where last drawing is ended. These functions are declared as follows:
void far outtextxy(int x, int y, char *text);
void far outtext(char *text);
Circle, arc, pieslice are declared as follows:
Declaration:
  •  void far arc(int x, int y, int stangle, int endangle, int radius);
  •  void far circle(int x, int y, int radius);
  •  void far pieslice(int x, int y, int stangle, int endangle, int radius);
Remarks:
  • arc draws a circular arc in the current drawing color.
  • circle draws a circle in the current drawing color.
  • pieslice draws a pie slice in the current drawing color, then fills it using
    the current fill pattern and fill color.
Arguments:
  • (x,y): Center point of arc, circlew, or pie slice
  • stangle: Start angle in degrees
  • endangle: End angle in degrees
  • radius: Radius of arc, circle, and pieslice
    Here, stangle and endangle are in degrees starting from the +ve x-axis in the polar coordinate system in the anti-clockwise direction. if stangle is 0, endangle is 360, it will draw a full circle. Refer this figure for clear idea: For the details of current color, fill color and fill patterns, refer the sections Lines and Colors. 
    Another basic shape that we come across is a rectangle. To draw a border, use rectangle with the coordinates of outline, to draw a square use rectangle with same height and width. drawpoly() and fillpoly() are two functions useful to draw any polygons. To use these functions, store coordinates of the shape in an array and pass the address of array as an argument to the function. By looking at the output of the previous program, you can understand what drawpoly is. fillpoly is similar except that it fills in the shape with current fill color.
Declaration:
  • void far rectangle(int left, int top, int right, int bottom);
  • void far drawpoly(int numpoints, int far *polypoints);
  • void far fillpoly(int numpoints, int far *polypoints);
Remarks:
  • rectangle draws a rectangle in the current line style, thickness, and drawing color.
  • drawpoly draws a polygon using the current line style and color.
  • fillpoly draws the outline of a polygon using the current line style and color, then fills the polygon using the current fill pattern and fill color.
Arguments: 
  • (left,top) is the upper left corner of the rectangle, and (right,bottom) is its lower right corner.
  •  numpoints:  Specifies number of points
  • *polypoints: Points to a sequence of (numpoints x 2) integers. Each pair of integers gives the x and y coordinates of a point on the polygon.
        To draw a closed polygon with N points, numpoints should be N+1 and the array polypoints[] should contain 2(N+1) integers with first 2 integers equal to last 2 integers.
        Let us study more about shapes latter. Here is some idea about colors. There are 16 colors declared in graphics.h as listed bellow.
BLACK:                  0
BLUE:                     1
GREEN:                  2
CYAN:                    3
RED:                       4
MAGENTA:            5
BROWN:                 6
LIGHTGRAY:         7
DARKGRAY:          8
LIGHTBLUE:           9
LIGHTGREEN:       10
LIGHTCYAN:         11
LIGHTRED:            12
LIGHTMAGENTA: 13
YELLOW:               14
WHITE:                   15
        To use these colors, use functions setcolor(), setbkcolor() and setfillstyle(). setcolor() function sets the current drawing color. If we use setcolor(RED); and draw any shape, line or text after that, the drawing will be in red color. You can either use color as defined above or number like setcolor(4);. setbkcolor() sets background color for drawing. Setfillstyle sets fill pattern and fill colors. After calling setfillstyle, if we use functions like floodfill, fillpoly, bar etc, shpes will be filled with fill color and pattern set using setfillstyle. These function declarations are as follows.
Declaration:
  •  void far setfillstyle(int pattern, int color);
  • void far setcolor(int color);
  • void far setbkcolor(int color);
Remarks:
  • setfillstyle sets the current fill pattern and fill color.
  • setcolor sets the current drawing color to color, which can range from 0 to getmaxcolor.
  • setbkcolor sets the background to the color specified by color.
        The parameter pattern in setfillstyle is as follows:
 Names
Value
Means  Fill With...
EMPTY_FILL
0
Background color
SOLID_FILL
1
Solid fill
LINE_FILL
2
---
LTSLASH_FILL
3
///
SLASH_FILL
4
///, thick lines
BKSLASH_FILL
5
\\\, thick lines
LTBKSLASH_FILL
6
 \\\
HATCH_FILL
7
Light hatch
XHATCH_FILL
8
Heavy crosshatch
INTERLEAVE_FILL
9
Interleaving lines
WIDE_DOT_FILL
10
Widely spaced dots
CLOSE_DOT_FILL
11
Closely spaced dots
USER_FILL
12
User-defined fill pattern
        Here is an example program with colors, pixels, bar, cleardevice etc. stdlib.h is used for random number generation. We have a function random(no), it returns a random number between 0 an no. The effect is by drawing random radius, random color circles with same center and random pixels. kbhit() function(defined in conio.h) returns a nonzero value when a key is pressed in the keyboard. So, the loop will continue until a key is pressed.
/*
random.c
some graphics effects using random numbers.
example 1.2
by HarshaPerla, http://eharsha.tk
*/

#include "graphics.h"
#include "conio.h"
#include "stdlib.h"

void main()
{
    int gd,gm;
    gd=DETECT;

    initgraph(&gd, &gm, "");
    setcolor(3);
    setfillstyle(SOLID_FILL,RED);
    bar(50, 50, 590, 430);
   
    setfillstyle(1, 14);
    bar(100, 100, 540, 380);

    while(!kbhit())
    {
        putpixel(random(439)+101,  random(279)+101,random(16));
        setcolor(random(16));
        circle(320,240,random(100));
    }
    getch();
    closegraph();
}

 Thank You for reading.

Computer science, Number Systems, Boolean Algebra,QBASIC, C tutorial, SQL Tutorial, HTML 5 tutorial

Follow by Email