C Language Notes
C Language Notes
Introduction to C Language
C is a general-purpose high level language that was originally developed by Dennis Ritchie for the Unix
operating system. C has now become a widely used professional language for various reasons.
Easy to learn
Structured language
Key words in C
"Keywords" are words that have special meaning to the C compiler. A ivariable cannot have the same
spelling and case as a C keyword. Some basic keyword are int, float, char, double.
Keyword
char
unsigned char
int
Format Specifier
%c
<-- -- >
%d
Size
1 Byte
8 Bytes
2 Bytes
Data Range
-128 to +127
0 to 255
-32768 to +32767
long int
unsigned int
float
double
long double
%ld
%u
%f
%lf
%Lf
-231 to +231
0 to 65535
-3.4e38 to +3.4e38
-1.7e38 to +1.7e38
-3.4e38 to +3.4e38
4 Bytes
2 Bytes
4 Bytes
8 Bytes
12-16 Bytes
Derived Data types: Array, Function, Structure, Union and pointers are considered as derived data
type.
Operators in C Language
What is Operator? Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and 5 are
called operands and + is called operator. C language supports following type of operators.
Arithmetic Operators
Bitwise Operators
Assignment Operators
Misc Operators
Arithmetic Operators:
There are following arithmetic operators supported by C language: Assume variable A holds 10 and
variable B holds 20 then:
Operator
Description
Example
A + B will give 30
B / A will give 2
B % A will give 0
++
--
Logical Operators
&
&
Called Logical AND operator. If both the operands are non zero then then condition becomes
true.
||
Called Logical OR Operator. If any of the two operands is non zero then then condition
becomes true.
Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is
true then Logical NOT operator will make false.
Relational Operators
=
=
Checks if the value of two operands is equal or not, if yes then condition becomes
true.
!= Checks if the value of two operands is equal or not, if values are not equal then
condition becomes true.
>
Checks if the value of left operand is greater than the value of right operand, if
yes then condition becomes true.
<
Checks if the value of left operand is less than the value of right operand, if yes
then condition becomes true.
>
=
Checks if the value of left operand is greater than or equal to the value of right
operand, if yes then condition becomes true.
<
=
Checks if the value of left operand is less than or equal to the value of right
operand, if yes then condition becomes true.
(A >= B) is
not true.
}
if ( b >= a )
{
printf("Line 5 - b is either greater than or equal to b\n" );
}
if ( a && b )
{
printf("Line 6 - Condition is true\n" );
}
if ( a || b )
{
printf("Line 7 - Condition is true\n" );
}
/* Again lets change the value of a and b */
a = 0;
b = 10;
if ( a && b )
{
printf("Line 8 - Condition is true\n" );
}
else
{
printf("Line 8 - Condition is not true\n" );
}
if ( !(a && b) )
{
printf("Line 9 - Condition is true\n" );
}
}
Assignment Operators:
There are following assignment operators supported by C language:
Operator
Description
Example
+=
-=
C += A is equivalent to C = C + A
*=
/=
Misc Operators
Operato
r
Description
Example
sizeof()
&
Pointer to a variable.
?:
Conditional Expression
Precedence of C Operators
Operator precedence determines the grouping of terms in an expression. This affects how
an expression is evaluated. Certain operators have higher precedence than others; for
example, the multiplication operator has higher precedence than the addition operator:
For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher
precedenace than + so it first get multiplied with 3*2 and then adds into 7.
If Statement
If-Else Statement
Nested If-Else Statement
Switch Case
If Statement:
This is a conditional statement used in C to check condition or to control the flow of
execution of statements. This is also called as 'decision making statement or control
statement.' The execution of a whole program is done in one direction only.
Syntax:
if(condition)
{
statements;
}
In above syntax, the condition is checked first. If it is true, then the program control flow
goes inside the braces and executes the block of statements associated with it. If it returns
false, then program skips the braces. If there are more than 1 (one) statements in if
statement then use { } braces else it is not necessary to use.
Program :
#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();
}
If-Else Statement:
This is also one of the most useful conditional statement used in C to check conditions.
Syntax:
if(condition)
{
true statements;
}
else
{
false statements;
}
In above syntax, the condition is checked first. If it is true, then the program control flow
goes inside the braces and executes the block of statements associated with it. If it returns
false, then it executes the else part of a program.
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();
}
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;
}
In above syntax, the condition is checked first. If it is true, then the program control flow
goes inside the braces and again checks the next condition. If it is true then it executes the
block of statements associated with it else executes else part.
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();
}
There are two statement built in C, break; and continue; to interrupt the normal flow of control of a program.
Loops performs a set of operation repeately until certain condition becomes false but, it is sometimes desirable
to skip some statements inside loop and terminate the loop immediately without checking the test expression.
In such cases, break and continue statements are used.
break Statement
In C programming, break is used in terminating the loop immediately after it is encountered. The break
statement is used with conditional if statement.
The figure below explains the working of break statement in all three type of loops.
# include <stdio.h>
int main(){
float num,average,sum;
int i,n;
printf("Maximum no. of inputs\n");
scanf("%d",&n);
for(i=1;i<=n;++i){
printf("Enter n%d: ",i);
scanf("%f",&num);
if(num<0.0)
break;
//for loop breaks if num<0.0
sum=sum+num;
}
average=sum/(i-1);
printf("Average=%.2f",average);
return 0;
}
Output
continue Statement
It is sometimes desirable to skip some statements inside the loop. In such cases, continue statements are
used.
For better understanding of how continue statements works in C programming. Analyze the figure below which
bypasses some code/s inside loops using continue statement.
Enter num1:3
Enter num2:0
Enter num3:-5
Enter num4:2
product=-30
- See more at: http://www.programiz.com/c-programming/c-break-continue-statement#sthash.qwGf4dr9.dpuf
printf("c is largest");}
else
if(b>c)
printf("b is largest");
else
printf("c is largest");
getch();
}
Program to Make Calculator using Switch case statements
#include<stdio.h>
#include<stdlib.h>
void main()
{
int a,b,res,ch;
printf("\t *********************");
printf("\n\tMENU\n");
printf("\t********************");
printf("\n\t(1)ADDITION");
printf("\n\t(2)SUBTRACTION");
printf("\n\t(3)MULTIPLICATION");
printf("\n\t(4)DIVISION");
printf("\n\t(5)REMAINDER");
printf("\n\t(0)EXIT");
printf("\n\t********************");
printf("\n\n\tEnter your choice:");
scanf("%d",&ch);
if(ch<=5 & ch>0)
{
printf("Enter two numbers:\n");
scanf("%d%d",&a,&b);
}
switch(ch)
{
case 1:
res=a+b;
printf("\n Addition:%d",res);
break;
case 2:
res=a-b;
printf("\n Subtraction:%d",res);
break;
case 3:
res=a*b;
printf("\n Multiplication:%d",res);
break;
case 4:
res=a/b;
printf("\n Division:%d",res);
break;
case 5:
res=a%b;
printf("\n Remainder:%d",res);
break;
case 0:
printf("\n Choice Terminated");
exit(1);
break;
default:
printf("\n Invalid Choice");
}
}
LOOPS in C Language
For Loop
2)
While Loop
3)
Do while Loop
For Loop:In for looping statement allows a number of lines represent until the condition is satisfied
Syntax:
for(initialize counter variable ; condition ; increment/decrement the counter variable)
{
Statement1;
...
Statement n;
}
WHILE LOOP
In While looping statement allows a number of lines represent until the condition is
satisfied
Syntax:
while( condition)
{
Statement1;
...
Statement n;
}
DO WHILE LOOP:
In DO WHILE LOOP first execute the statements then it checks the condition.
Syntax:
do
{
Statement1;
...
Statement n;
}while(condition);
}
do while loop :
Do
{
Statements;
}while(condition);
rev=(rev*10)+mod;
num=num/10;
}
printf("Reverse of the given number: %d", rev);
getchar();
}
Solution Ex-2:
#include<stdio.h>
void main()
{
int i,j,n;
for(i=0 ; i<4 ; i++)
{
for(j=0 ; j <= i ; j++)
{
Printf("*");
}
Printf(\n);
}
}
Solution Ex-3:
#include<stdio.h>
int main(){
int input,i,result=1;
printf("please input a Integer: ");
scanf("%d",&input);
for(i=input;i>0;i--)
{
result=result*i;
}
printf("the factorial of %d is %d\n",input,result);
}
ARRAY
Array by definition is a variable that holds multiple elements which have the same data
type.
Declaring Arrays
In order to declare an array, you need to specify:
Data type of the array's elements. It could be int, float, double, char...etc.
Fixed number of elements that array contains. The number of elements is put inside
square brackets followed the array name.
The following illustrates the typical syntax of declaring an array:
1
data_type array_name[size];
For example, to declare an array of integers with size of 10, you can do as follows:
1
int a[100];
In the memory, you have 10 consecutive objects like following:
For example, to declare an array of integers with size of 10, you can do as follows:
You must follow the rules below when you declare an array in C:
Bounds Checking
In C there is no check to see if the subscript used for an array exceeds the size of the
array. Data entered with a subscript exceeding the array size will simply be placed in
memory outside the array; probably on top of other data, or on the program itself. This
will lead to unpredictable results, to say the least, and there will be no error message to
warn you that you are going beyond the array size. In some cases the computer may just
hang. Thus, the following program may turn out to be suicidal.
main( )
{
int num[40], i ;
for ( i = 0 ; i <= 100 ; i++ )
num[i] = i ;
}
Thus, to see to it that we do not reach beyond the array size is entirely the programmers
botheration and not the compilers.
Accessing Array's Elements using Pointers
#include<stdio.h>
Void main()
{
int a[5]={1,2,3,4,5};
int *ptr,i;
ptr=&a[0];
for (i=0;i<=4;i++)
{
Printf(%d,*(ptr+i));
}
getch();
}
Program of Linear search :
#include<stdio.h>
int main(){
int a[5]={10,11,12,13,14,15},i,n,m,count=0;
printf("Enter the number to be search: ");
scanf("%d",&m);
for(i=0;i<=n-1;i++){
if(a[i]==m){
count=1;
break;
}
}
if(c==0)
printf("The number is not in the list");
else
printf("The number is found");
}
return 0;
What is 2D ARRAY?
It is also possible for arrays to have two or more dimensions. The two-dimensional array
is also called a matrix.
Memory Map of 2D array
In memory whether it is a one-dimensional or a two-dimensional array the array elements
are stored in one continuous chain. The arrangement of array elements of a twodimensional array in memory is shown below.
*x1=*y1;
*y1=z1;
printf(*x=%d *y=%d,x1,y1);
}
main()
{
int x=100, y=200;
swap(&x,&y);
printf(x=%d y=%d,x,y);
Storage Classes
Moreover, a variables storage class tells us:
(a) Where the variable would be stored.
(b) What will be the initial value of the variable, if initial value is not specifically
assigned.(i.e. the default initial value).
(c) What is the scope of the variable; i.e. in which functions the value of the variable
would be available.
(d) What is the life of the variable; i.e. how long would the variable exist.
The features of a variable defined to have an automatic storage class are as under:
Storage Memory.
Default initial value An unpredictable value, which is often called a garbage value.
Scope Local to the block in which the variable is defined.
Life Till the control remains within the block in which the variable is defined.
Following program shows how an automatic storage class variable is declared, and the
fact that if the variable is not initialized it contains a garbage value.
Register Storage Class
The features of a variable defined to be of register storage class are as under:
Storage
- CPU registers.
Default initial value - Garbage value.
Scope - Local to the block in which the variable is defined.
Life - Till the control remains within the block in which the variable is defined.
Static Storage Class
The features of a variable defined to have a static storage class are as under:
Storage Memory.
Default initial value Zero.
Scope Local to the block in which the variable is defined.
Life Value of the variable persists between different function calls.
External Storage Class
The features of a variable whose storage class has been defined as external are as follows:
Storage Memory.
Default initial value Zero.
Scope Global.
Life As long as the programs execution doesnt come to an end.
STRUCTURE: Structure can be a collection of heterogeneous data type.
Structure Declaration:
struct struct-name{
type field-name;
type field-name;
... };
types can handle a great variety of situations. But quite often we deal with entities that
are collection of dissimilar data types. In some types of situation when we have to store
dissimilar data structure can be used.
How structure members are stored in memory
Whatever be the elements of a structure, they are always stored in contiguous memory
locations. The following program would illustrate this:
/* Memory map of structure elements */
main( )
{
struct book
{
char name ;
float price ;
int pages ;
};
struct book b1 = { 'B', 130.00, 550 } ;
printf ( "\nAddress of name = %u", &b1.name ) ;
Chapter 10: Structures 371
printf ( "\nAddress of price = %u", &b1.price ) ;
printf ( "\nAddress of pages = %u", &b1.pages ) ;
}
Here is the output of the program...
Address of name = 65518
Address of price = 65519
Address of pages = 65523
Actually the structure elements are stored in memory as shown in the Figure below.
Preprocessor Directives:
We would learn the following preprocessor directives here:
(a) Macro expansion
(b) File inclusion
(c) Conditional Compilation
Macro Expansion
Have a look at the following program.
#define UPPER 25
main( )
{
int i ;
for ( i = 1 ; i <= UPPER ; i++ )
printf ( "\n%d", i ) ;
}
In this program instead of writing 25 in the for loop we are writing it in the form of
UPPER, which has already been defined before main( ) through the statement,
#define UPPER 25
This statement is called macro definition or more commonly, just a macro. What
purpose does it serve? During preprocessing, the preprocessor replaces every occurrence
of UPPER in the program with 25.
File Inclusion (#include)
A preprocessor include directive causes the preprocessor to replace the directive with
the contents of the specified file.
Conditional Compilation
We can, if we want, have the compiler skip over part of a source code by inserting the
preprocessing commands #ifdef and #endif, which have the general form:
#ifdef macroname
statement 1 ;
statement 2 ;
statement 3 ;
#endif
STRING
strlen( )
This function counts the number of characters present in a string. Its usage is illustrated in
the following program.
main( )
{
char arr[ ] = "Bamboozled" ;
int len1, len2 ;
len1 = strlen ( arr ) ;
len2 = strlen ( "Humpty Dumpty" ) ;
printf ( "\nstring = %s length = %d", arr, len1 ) ;
printf ( "\nstring = %s length = %d", "Humpty Dumpty", len2 ) ;
}
The output would be...
string = Bamboozled length = 10
string = Humpty Dumpty length = 13
strcpy( )
This function copies the contents of one string into another. The base addresses of the
source and target strings should be supplied to this function. Here is an example of
strcpy( ) in action...
main( )
{
char source[ ] = "Sayonara" ;
char target[20] ;
strcpy ( target, source ) ;
printf ( "\nsource string = %s", source ) ;
printf ( "\ntarget string = %s", target ) ;
}
And here is the output...
source string = Sayonara
target string = Sayonara
strcat( )
This function concatenates the source string at the end of the target string. For example,
Bombay and Nagpur on concatenation would result into a string BombayNagpur.
Here is an example of strcat( ) at work.
main( )
{
char source[ ] = "Folks!" ;
char target[30] = "Hello" ;
strcat ( target, source ) ;
printf ( "\nsource string = %s", source ) ;
printf ( "\ntarget string = %s", target ) ;
}
And here is the output...
source string = Folks!
target string = HelloFolks!
strcmp( )
This is a function which compares two strings to find out whether they are same or
different. The two strings are compared character by character until there is a mismatch
or end of one of the strings is reached, whichever occurs first. If the two strings are
identical, strcmp( ) returns a value zero. If theyre not, it returns non zero values.
main( )
{
char string1[ ] = "Jerry" ;
char string2[ ] = "Ferry" ;
int i, j, k ;
i = strcmp ( string1, "Jerry" ) ;
j = strcmp ( string1, string2 ) ;
k = strcmp ( string1, "Jerry boy" ) ;
printf ( "\n%d %d %d", i, j, k ) ;
}
And here is the output...
0 4 -32
In the first call to strcmp( ), the two strings are identicalJerry and Jerryand the
value returned by strcmp( ) is zero. In the second call, the first character of Jerry
doesn't match with the first character of Ferry and the result is 4, which is the numeric.
xstrlen ( char *s )
{
int length = 0 ;
while ( *s != '\0' )
{
length++ ;
s++ ;
}
return ( length ) ;
}
The output would be...
string = Bamboozled length = 10
string = Humpty Dumpty length = 13
main
{
char source[ ] = "Sayonara" ;
char target[20] ;
xstrcpy ( target, source ) ;
printf ( "\nsource string = %s", source ) ;
printf ( "\ntarget string = %s", target ) ;
}
This will extract the data from the character array according to the conversion specifier
and store into the respective variables.
Let us understand this using an example.
char *str = "Learn C Online";
char *first, *second, *third;
sscanf(str, "%s %s %s",first,second,third);
In the above example,
"Learn" will get stored in variable first
"C" will get stored in variable second
"Online" will get stored in variable third
Sprintf()
sprintf() function is exactly opposite to sscanf() function. Sprint() function writes the
formatted text to a character array.
Syntax:
sprintf (CharacterArray,"Conversion Specifier", variables);
Let us understand this using an example.
char *str;
char *first = "Learn", *second = "C", *third = "Online";
sprintf(str, "%s %s %s",first,second,third);
In the above example, Learn C Online will get stored in the character array str.
FILE HANDLING
What is file handling?
File is a place where information or data is stored.
we make use of some of the file-handling functions in c like:
fopen()-for opening a file.
fclose()-to close a file. Every file being opened for any operations like:
while((ch=getc(p))!=EOF)
putc(ch,q);
printf("\nCOMPLETED");
fclose(p);
fclose(q);
return 0;
}
POINTER
What is pointer? Explain with examples
A pointer is a variable that holds a memory address.
The general form of declaring a pointer variable is:
type *name;
type is the data type of the pointer.
name is the name of pointer variable.
The data type of the pointer defines what type of variables the pointer can point to.
Two special pointer operators are: * and &.
The & is operator that gives the memory address.
The * is complement of &. It returns the value located at the address that follows.
int i, *p;
i = 5;
p = &i;
Modular programming
Modular programming is the process of subdividing a computer program into separate sub-programs.
A module is a separate software component. It can often be used in a variety of applications and functions
with other components of the system. Similar functions are grouped in the same unit of programming code
and separate functions are developed as separate units of code so that the code can be reused by other
applications.
Object-oriented programming (OOP) is compatible with the modular programming concept to a large extent.
Modular programming enables multiple programmers to divide up the work and debug pieces of the program
independently.
The benefits of using modular programming includ:
A single procedure can be developed for reuse, eliminating the need to retype the code many times.
Programs can be designed more easily because a small team deals with only a small part of the
entire code.
Types of software
Component of computer system or architecture of computer system
Number systems.