C-Programming-Notes (1)
C-Programming-Notes (1)
Characteristics / Features
1. It is a structured (modular) programming language. So any large programs can be erased easily.
2. It is small size and requires less memory than other languages programs.
3. It is platform independent language.
4. It is procedural programming language because the program is divided into number of functions.
5. It is general purpose structured programming language.
6. It is internationally standardized programming language.
7. It inherits or invisible functionality (memory management, CPU-register manipulation, etc.)
Advantages
1. It is easy for debugging, testing and maintaining.
2. It is portable programming language.
3. It is fast for executing.
4. It is compact programming language. The statement in C language are generally short but very
powerful.
5. It is simple / easy. It supports both HLL and LLL.
6. It has only 32 keywords so that easy to remember.
7. Its compiler is easily available.
8. It has ability to extend itself. Users can add their own functions to the C Library.
9. It can use to design middle type of software.
Disadvantages
1. There is no runtime checking.
2. There is no strict type checking. (Example: We can pass an integer value for the floating data type)
[Note: Floating point: a) Single precision (!) = Number with decimal value up to 7 digits.
b) Double precision (#) = Number with decimal value up to 15 digits.
3. As the program extends it is very difficult to fix the bugs.
4. It may be compile time overhead due to the misplacing and excessive use of pointers.
5. It does not use to develop complex type of software now-a-day.
C program layout
C program consists of two sections.
1. Pre-processor directives
2. Main function
Example:
#include<stdio.h> Pre-processor directives
int main()
{
printf("Hello World");
Main function
return 0;
Structure of C program
1. Header files 4. Declaration part 7. Comments
2. Global declaration 5. Executable part 8. Function header
3. Main() 6. User defined functions
Comment line: It indicates the purpose of the program. It is represented as:
For single line comment: // comment
For multi-line comment: /* comments */
Comment line is used for increasing the readability of the program. It is enclosed within the
decimeters. Comment line can be single or multiple line but should not be nested.
Pre-processor Directives: #include<stdio.h> tells the compiler to include information about the
standard input/output library. It is also used in symbolic constant such as #define PI 3.14 (value).
The stdio.h (Standard Input Output header file) contains definition and declaration of system
defined function such as printf(), scanf(), pow(), etc. Generally, printf() function is used to display
and scanf() function is used to read value.
Global Declaration: This is the section where variable are declared globally so that it can be access
by all the functions used in the program. And it is generally declared outside the function:
main() : It is the user defined function and every function has one main() function from
where actually program is started and it is encloses within the pair of curly braces. The
main() function can be anywhere in the program but in general practice it is placed in the
first position. The main() function return value when it declared by data type as:
int main()
{
return 0
}
The main() function does not return any value when void (means null / empty) as void
main(void) or
void main()
{ Output: C Language
printf("C Language");
}
The program execution start with opening brace and end with closing brace.
Declaration Part and Executable Part: These both parts lies in between the two braces. And at the
end of each line, the semi-colon is given which indicates statement termination.
[Note: 1) Syntactic Error: The error that arises in an expression due to unbalanced parenthesis are
called syntactic error.
2) Semantic Error: The error that arises due to the use of undefined variable are called semantic
error.
3) Building: The process of compiling and linking a program is often called building.]
Header Files: Header files are standard files that are compulsory in C program and contains the
function definition of library functions.
(i) #include<stdio.h>: It is standard input output header file. It contains the function definition
of input output functions such as scanf(), printf(), etc.
(ii) #include<conio.h>: conio stands for CONsole Input Output header file. It is a header file
which is included in the program this is used to use, clrscr(), getch(), etc. We do not need
to include this file in C program. It is necessary for C++ programs.
(iii) #include<math.h>: This header file is used for mathematical functions such as pow(), sqrt(),
sin(), tan(), cos(), etc.
(iv) #include<graphics.h>: It is graphic header file. It contains the function definition of graphic
processing functions such as line(), circle(), rectangle(), etc.
(v) #include<string.h>: It is string header file. It contains the function definition of string
processing functions such as strlen(), strcat(), strcpy(), etc.
Elements of C Program
1. #include<stdio.h>: At the first line of the program you can see the #include<stdio.h>. It is called
the pre-processor directive or pre-processor instruction. This instruction must include at the
starting of the every C program. It instructs the C compiler to include information from the
standard input/output (stdio.h) library header file.
2. int main(): Below the pre-processor instruction, there is int main(). It is a function or sub-program.
There may use number of functions in a C program but there must be included at least one main()
function. Execution of any C program starts from the main() function. It is not possible to execute
any C program without main() function.
The int before main() specifies the function declaration is integer data type and its return type is
integer value. That means it can return an integer value.
The ( ) parenthesis that follow the function name may contain list of values to be used by that
function is called parameters or arguments. If main(void) is given as a parameter which refers that
it does not take any arguments.
{
…………………….
…………………….
}
The curly braces { } contains the program statements to be executed whenever the function is
called. Each statement must be terminated by a semi-colon (;). The '{' open curly brace represents
the beginning of the function body and the '}' close curly brace represents its termination.
3. printf() : It is C library function that instructs the computer to display characters or a string
enclosed by the quotation marks on the monitor screen. Items enclosed by the parenthesis are
called arguments.
4. return 0 : At the end of function main(), we have to include 'return 0' statement because function
main is defined to return a value of integer type. The return 0; statement returns a value from main
to the operating system.
C Preprocessor
Preprocessor is a program that processes the code before it passes through the compiler. It operates under
the control of preprocessor command lines and directives. Preprocessor directives are placed in the source
program before the main line before the source code passes through the compiler it is examined by the
preprocessor for any preprocessor directives.
Preprocessor directives follow the special syntax rules and begin with the symbol # and do not require
any semicolon (;) at the end. A set of commonly used preprocessor directives are listed below:
Directives Function
#define Defines a macro substitution
#undef Undefines a macro
#include Specifies a file to be included
#ifdef Tests for macro definition
#else Specifies alternatives when # if tests fails
Fundamentals of C
Character Set : Character sets are the letters, digits and special characters and white spaces that
form words, numbers and expressions.
Character-set
a) Letters : A – Z, a – z
b) Digits: 0 – 9
c) Special characters: , . ; : ? ' " ! / \ $ %, etc
d) White spaces: Blank space, Horizontal space, Carriage Return, New Line, Form feed
Comments: It is not compulsory in C program but it makes easy to study the programs. Comments
can be written in two forms:
(i) // single line comments
(ii) /*multi-line comments*/
Tokens: Tokens are fundamental parts of C program from which other parts are formed. C programs
are written using tokens. There are six types of C tokens that are given below:
(i) Operators
(ii) Keywords
(iii) Identifiers
(iv) Constants
(v) Strings
(vi) Special symbols
Keywords / Reserved Words: Keywords are those special words that are pre-defined in C
programming language. These keywords cannot be used as identifiers (variables) in the program.
Here is the list of keywords used in Standard C.
Identifiers : Identifiers are the names given to program unit such as variable, structure, function,
etc. They are not defined in programming language but are used to define by the programmer.
Some basic rules to define identifiers are given below:
(i) First character must be an alphabet underscore then digits or alphabets.
(ii) It must consist of only letters, digits and underscore.
(iii) Any standard C language keyword cannot be used as identifier name.
(iv) It should not contain a space.
(v) It allows both uppercase and lowercase characters.
User defined type declaration: C language supports a feature where user can define an identifier
that characterizes an existing data type.
Syntax: typedef <type> <identifier>
Example: typedef int number;
Type Format Specifier: The format specifiers are used in C for input and output purposes. Using
this concept, the compiler can understand that what type of data is in a variable during taking
input using the scanf() function and printing using printf() function. Here is a list of format
specifiers.
Format specifier Type
%c Character
%d Signed integer
%f Float values
%s String
%l or %ld or %li Long integer
%lf Double integer
%Lf Long double integer
Variables: It is a name of the memory location used to store a data value. It is a value that can
change any time.
Example: int a,b,c;
int a=3, b=4, c=5;
char d, e;
Here, a, b, c are integer variable and d, e are character type variable.
Rules for using variables:
a) They must always begin with a letter, alphabet or character.
b) The length of a variable must not be more than 8 characters.
c) White space is not allowed.
d) A variable should not be a keyword.
e) It should not contain any special characters.
Constant: Those data values which does not change during program execution.
Example: radius = 3.14 is a constant
#define pi 3.1415
#define length 5.5
There are several types of constants:
a) Integer constant: It consists of a set of digits 0 to 9 preceded by an optional + or – sign.
Examples: 123, -21, 0, 5632, +78, etc.
b) Floating point constant: It is a number that can be written either in decimal form or an
exponent form or both. It must have at least one digit before decimal point and at least
one digit after the decimal. Examples: 7.0, 17.6, -14.5, 0.8, etc.
c) Single Character constant: It stores only single character. It is enclosed by single
quotation mark. Examples: 'A', 'B', 'h', '2', '5', etc.
d) String constant: It is a set of characters enclosed in double quotation marks which may
include alphabet, number, special character and blank space. Examples: "bibek", "123",
"Good Bye", "!......?", etc.
Escape sequences: The non-printing characters started with slash (\) are called escape sequences.
They are special characters used in output functions.
3) Control Statement: They are used to create special program feature such as logical tests, loops
and branches.
Example: for (c=1; c<=10; c++)
a) Arithmetic operators (Binary operator): Those operators that performs simple arithmetic
calculations such as addition, subtraction, multiplication, division, modulus, etc. It uses two
operands so that it is called binary operator.
Operator Meaning Example
+ Addition a+b
- Subtraction a-b
* Multiplication a*b
/ Division a/b
% Modulus a%b
b) Relational operators: Those operators that compares the relationship between operands and bring
out a decision and program accordingly.
Operator Meaning Example
< is less than a<b
<= is less than or equal to a<=b
> is greater than a>b
>= is greater than or equal to a>=b
== is equal to a= =b
!= is not equal to a!=b
c) Logical operators: Those operators that are used to give logical value either true or false.
Operator Meaning Example
&& Logical AND (a>b)&&(a>c)
|| Logical OR (a>b) || (a>c)
! Logical NOT !(a= = b)
d) Assignment operators: Those operators that are used to assign the value of expression into variable.
The most commonly used assignment operator is '='. It is written in the form of:
variable = expression
Example: x = a+b
where, x is a variable and a+b is an expression. Here the value of a+b is evaluated and substituted to
the variable x .
Shorthand Assignment
e) Unary (monadic) operators: A class of operators that act upon a single operand to produce a new
value, which is called unary operator. It is mostly used in loops.
There are two types of unary operators:
(i) Increment operator:
++variable name (prefix):
Example: m = 5;
y = ++m;
In this case, the value of y and m would be 6 because a prefix operator first adds 1 to the
operand and then the result is assigned to the variable on the left.
f) Conditional (Ternary) operators: An expression that makes use of the conditional operator (?) and
(:) is called conditional operator. It can be written in the form:
expression1 ? expression 2 : expression 3
Example: a = 10;
b = 15;
c = (a>b) ? a:b
Here, expression 1 (a>b) is evaluated first. If expression 1 gets true then the value of c will be the
value of a, otherwise the value of c will be the value of b. In this example, the value of b is assigned
to c.
g) Bitwise operators: Those operators which supports special operators for manipulation of data at bit
level is called bitwise operators. It operates on each bit of data. It may not be applied to a float or
double.
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise Exclusive
<< Shift left
>> Shift right
h) Special Operators: C supports some special operators of interest such as comma, size of operator,
pointer operator (& and *) and member selection operators (. and ->).
i) Size of operator: The operator 'size of ' gives the size of the data type or variable in terms of bytes
occupied in the memory.
Example: m = size of (sum);
n = size of (long int);
Output: 1.000000
b and c are integer, and division is also integer, but final value is converted to float because a
is float.
b) Explicit type conversion: If we want to convert any type of single variable or mixed variable
into another type then it is known as explicit type conversion.
Example: float x;
int num1, num2;
num1=10, num2=3;
x= (float)num1/(float)num2; /* num1 and num2 are converted into float */
printf ("%f",x); /* The result is 3.333333 */
Library Functions
The functions that are pre-defined in programming language are called library functions. Some library
functions are used for input/output operations, some are for string processing operations, and some are
for mathematical operation and so on. Each library function can perform specific task and return specific
value. Some library functions are printf( ), scanf( ), strlen( ), clrscr( ), getch( ), sqrt( ), etc.
b) puts( ): It is a library function that can use to display data from standard output device.
Syntax: puts(string expression);
#include<stdio.h>
#include<conio.h>
void main()
{
char a[10];
printf("Enter a string: ");
gets(a);
printf("The string entered is: ");
puts(a);
getch();
}
Control Structures
Control statements are those statements that help to jump from one part of the program to another. These
statements are mainly used to select statements, to repeat the statements number of times and to jump
from one part to other parts inside a program.
There are three types of control statements:
Control Statement
(ii) if….else statement: In this statement, if the condition is satisfied(true), then the true
statements are executed otherwise the else statement(false) are executed.
Syntax: if(condition)
{
Block of statement 1;
}
else
{
Block of statement 2;
}
(iv) Nested if statement: In nested if statement if the first, if condition is true the control
will enter inner if. If this is true the statement will execute otherwise control will come
out of the inner if and the else statement will be executed.
Syntax: if(condition)
{
if(condition 1)
{
Block of statement 1;
}
else
{
Block of statement 2;
}
else
{
block of statement n;
}
b) Switch case statement: It is alternative of nested if else. It is executed when there are many
choices and only one is to be executed.
Syntax: switch(expression)
{
case 1:
block of statement 1;
break;
case 2:
block of statement 2;
break;
…………
…………
case n:
block of statement n;
break;
default:
default-block of statement;
break;
}
2. Looping (Iteration): The process of repetition of the statement until the condition is satisfied.
Types of looping:
a) For loop
b) While loop
c) Do while loop
For loop: For loops are used when the number of iterations is known before entering the loop. It is also
known as counter-controlled loop.
a. setting a loop counter to an initial values
b. testing the loop counter to determine whether its value has reached the number of repetition
desired.
c. increasing, decreasing the values of loop counter each time the program statement within the
loop has been executed.
Syntax: for(initial value; final value; increment/decrement)
{
Block of statement;
}
a) While loop: It executes one or more statements while the given condition remains true. It is
useful when number of iterations is unknown. The while loop is an entry control (pre-test)
loop.
Syntax: while(expression)
{
Block of statement;
}
b) Do while loop: do…..while loops are useful where loop is to be executed at least once. In do
while loop condition comes after the body of loop. This loop executes one or more statements
while the given condition is true. It is an exit control (post-test) loop.
Syntax: do
{
Block of statement;
}
while(expression);
Nested for loop: A loop within a loop is called nested loop. In this the outer loop is used for counting rows
and the internal loop is used for counting columns. Any loop can be used as inner loop of another loop.
Syntax: for (initialization; condition; increment/decrement)
{
for (initialization; condition; increment/decrement)
{
statement (s);
}
}
Examples:
1) #include<stdio.h> Output
#include<conio.h> 123
void main( ) 123
{
123
int i,j;
for(i=1; i<=3; i++)
{
for(j=1; j<=3; j++)
{
printf(“%d”,j);
}
printf(“\n”);
}
getch( );
}
2) #include<stdio.h> Output
#include<conio.h>
void main( ) 111
{ 222
int i,j; 333
for(i=1; i<=3; i++)
{
for(j=1; j<=3; j++)
{
printf(“%d”,i);
}
printf(“\n”);
}
getch( );
}
3) #include<stdio.h> Output
#include<conio.h>
void main( ) 1
{ 12
int i,j; 123
for(i=1; i<=3; i++)
{
for(j=1; j<=i; j++)
{
printf(“%d”,j);
}
printf(“\n”);
}
getch( );
}
4) #include<stdio.h> Output
#include<conio.h>
void main( ) 1
{ 22
int i,j; 333
for(i=1; i<=3; i++)
{
for(j=1; j<=i; j++)
{
printf(“%d”,i);
}
printf(“\n”);
}
getch( );
}
5) #include<stdio.h> Output
#include<conio.h>
void main( ) 54321
{ 5432
int i,j; 543
for(i=1; i<=5; i++) 54
{ 5
for(j=5; j>=i; j--)
{
printf(“%d”,j);
}
printf(“\n”);
}
getch( );
}
6) #include<stdio.h> Output
#include<conio.h>
void main( ) 11111
{ 2222
int i,j; 333
for(i=1; i<=5; i++) 44
{ 5
for(j=5; j>=i; j--)
{
printf(“%d”,i);
}
printf(“\n”);
}
getch( );
}
7) #include<stdio.h> Output
#include<conio.h>
void main( ) 55555
{ 5555
int i,j,a=5; 555
for(i=5; i<=1; i--) 55
{ 5
for(j=1; j<=i; j++)
{
printf(“%d”,a);
}
printf(“\n”);
}
getch( );
}
8) #include<stdio.h> Output
#include<conio.h>
void main( ) 5
{ 55
int i,j,a=5; 555
for(i=1; i<=5; i++) 5555
{ 55555
for(j=1; j<=i; j++)
{
printf(“%d”,a);
}
printf(“\n”);
}
getch( );
}
Infinite Loop: A loop is said to be infinite if it never terminates. To come out from loop we have to press
reset.
Loop Interruption:
1. break statement
Syntax: break;
statement;
Example:
#include<stdio.h>
#include<conio.h> Output
void main( )
0 1
int a;
for(a=0; a<5; a++)
{
if(a==2)
break;
printf(“%d”,a);
}
getch( );
}
2. continue statement
Syntax: continue;
statement;
Example:
#include<stdio.h> Output
#include<conio.h> 0 1 3 4
void main( )
int a;
for(a=0; a<5; a++)
{
if(a==2)
continue;
printf(“%d”,a);
}
getch( );
}
String Function
String is a collection of character or group of character which is enclosed within double quotation
symbol (“ ”). Strings are always enclosed within double quotes whereas character is enclosed
within single quotes (‘ ’) in C.
1. String length i.e. strlen( ): It returns the length of given string (including spaces).
Syntax: strlen(string);
3. String copy i.e. strcpy( ): It is used to copy content of a string to another string. It takes two
arguments.
Syntax: strcpy(string1, string2);
4. String reverse i.e. strrev( ): It is used to reverse a string. It takes only one string and returns in
reverse order.
Syntax: strrev(string);
5. String uppercase i.e. strupr( ): It is used to convert the lowercase into uppercase. It takes only
one string.
Syntax: strupr(string);
6. String lowercase i.e. strlwr( ): It is used to convert the uppercase into lowercase. It takes only
one string.
Syntax: strlwr(string);
7. String compare i.e. strcmp( ): It is used to compare two string character by character. It accepts
two string as parameters and returns an integer whose value is:
< 0 if the first string is smaller than second string.
> 0 if the first string is greater than second string.
= = 0 < if the first string equal to second string.
Array
An array is a collection of similar data type that can hold value of a particular data type for which it has
been declared.
Types of array:
a) Single dimensional array: It has only one subscript / suffix. A subscript is a number in a bracket
that follows an arrays name.
Example: int n[1000];
Here, it means n[0], n[1], n[2], …….., n[999]
b) Multi-dimensional array: It is an array that can use to store similar types of data in a common
name. It consists of two subscript / suffix in which first gives number of row size and second
gives number of column size.
Example: int n[3][3];
Here, it means: n[0][0] n[0][1] n[0][2]
n[1][0] n[1][1] n[1][2]
n[2][0] n[2][1] n[2][2]
Examples:
1) WAP to input any 10 numbers and display.
Using single dimensional array
#include<stdio.h>
#include<conio.h>
void main( )
{
int n[10],i;
printf(“Enter 10 numbers: ”);
for(i=0; i<10; i++)
{
scanf(“%d”,&n[i]);
}
printf(“You entered\n”);
for(i=0; i<10; i++)
{
printf(“%d\n”,n[i]);
}
getch( );
}