Download - C & DS Notes
-
8/6/2019 C & DS Notes
1/83
UNIT IAlgorithm:- Step by step representation to performing any task is called algorithm.
Algorithm & flowchart for making a tea:
BeginBoil water.Put tea power in the kettle.Pour boiled water in the kettle.Wait for three minutes.Boil milk.
Put boiled milk in a cup.Add sugar to the cup.Empty the kettle in the cup.Stir the cup with a spoon.
End
1
Put tea power in the kettle
Pour boiled water in the kettle
Wait for 3 minutes
Boil milk
Put boiled milk in a cup
Add sugar to the cup
Empty the kettle
Stir the cup with a spoon
End
Boil Water
Begin
-
8/6/2019 C & DS Notes
2/83
Steps to write an algorithm:It is the step by step method of performing any task. When we breakup a big task
into smaller steps what we actually do is to create an algorithm. The steps in an algorithmcan be divided in three basic categories. They are
1. Sequence2. Selection
3. Iteration
Sequence:A Sequence is a series of steps that we can follow in any algorithm without any
break i.e.,Unconditionally.
Selection:
Selection involves makes a choice from multiple, available options. A selectionstatement generally takes the form of
1. If2. Then3. End-if
Eg:
1. Ifthe guest wants tea.2. Then give him tea.3. Offer biscuits.4. End-if
Begin Begin
1. Ifthe guest wants tea 1. Ifthe guest wants tea2. Then make tea. 2. Then make tea;3. End-if 3. offer biscuits4. Offer biscuits 4. End-if
End. End
Offer biscuits to all guests Offer biscuits only to guests who want tea
2
Begin
Take a utensil.Take the utensil to the water tap.
Open the tap.Fill the utensil with water.Close the tap.Put the utensil on the gas or in the oven.Start the gas or the oven.Wait until the water boils.Switch off the gas or the oven.
End
-
8/6/2019 C & DS Notes
3/83
I. Compound conditions:We combine two or more conditions in to a single compound condition (using the
words like andand/oror to join sentences.
1. Compound conditions with and:
1. Ifit is a weekday2. and it is 7 am or more3. and you are feeling ok4. Then
5. Take breakfast6. Go to work7. End-if
2. Compound conditions with or:
1. Ifit is a weekday2. or work is pending3. or boss is angry4. Then
5. Take breakfast6. Go to work
7. End-if
II. Nested condition:- Putting a if with in another if forms a nested condition.
Eg 1.1. Ifyou are feeling ok2. Then go to work3. Else
4. Ifyou have fever5. Then go to the doctor6. Else
7. Just relax8. End-if9. End-if
Eg 2.
1. Ifa>b2. Then Ifa>c3. Then choose a4. Else choose c5. End-if6. Else ifb>c7. Then choose b8. Else choose a9. End-if
10. End-ifSelecting the largest of three numbers using nested conditions
3
-
8/6/2019 C & DS Notes
4/83
III Testing and debugging:We are checking to see if our algorithm gives the desired result, Hence we testing
the algorithm. A set of values of a, b and c that we use for testing (e.g. a=18, b=24,c=49) is
called as a test case as we test our algorithm for a possibility (or case) at a given time. Agroup of test cases makes up the test data.
If for any one of such conditions, our algorithm gives an incorrect result, we say thatis a bug in the algorithm- it is another name for an error. The process of removing a bugfrom an algorithm is called as debugging.
IV Indentation and Algorithm maintenance:For every if statement there is a end-if statement, for every Begin statement there is
an end statement, writing end-if is exactly below if, end is exactly below begin & start
some sentences at beginning and some after leaving some spaces is called indentation.Writing algorithms in indentation is very easy to understand & make changes very easily.Writing the algorithms in indented form is called good maintenance of algorithms.
Iteration: A sequence of steps which are used repeatedly is called iteration.
(a) 1. Repeat (b) 1. Do (c) 1. While I do not arrive2. Wait for two minutes. 2. Wait for two minutes. 2. Wait for two
minutes.
3. Until I arrive 3. While I do not arrive 3. End-while4. Go to Movie 4. Go to Movie 4. Go to Movie
Repeat-Until & Do-While (cases a & b) are essentially, first it do the steps thencheck for the condition, While- End while(case) is differ from above, Because first checksthe condition then do the steps.
4
-
8/6/2019 C & DS Notes
5/83
Flowchart:- Representation of algorithm in graphical form is called Flowchart.
Flowchart Symbols & its uses
S. NO Symbols Name Purpose Usage of symbol in flowchart
1. Rounded Rectangle Terminal It is used to start and stop
2. Parallelogram Data It is used for input or
output data
3. Rectangle Process It is used to process the
data
4. Rhombus Decision It is used to give condition
5. Arrows Flow of control It is used to give flow of
given data
6. Hexagon Preparation It is used for loops like
For, While, Do While
7. Circle Connector It is used for connecting
lines
8. Crossed Circle Summing Junction It is used for junctions
9. - - - - - - Dotted Lines Flow of data It is used to give Flow of
data in loops
10. Double Sided Rectangle Predefined Process It is used for Predefined
process like Macros
5
-
8/6/2019 C & DS Notes
6/83
System Ready
Enter ProgramProgram Code
EditSource Program
CompileSource Program
CCompiler
SyntaxErrors?
Link withSystem Library
SystemLibrary
ExecuteObject Code
InputData
Logic andData
Errors
?
CORRECT OUTPUT
Stop
Flowchart for Process of Compiling & Running a C Program
Source Program
Yes
No Object Code
Executable Object Code
Data Error Logic Error
No Errors
6
-
8/6/2019 C & DS Notes
7/83
C Tokens
Tokens
Keywords Identifiers Constants Strings Operators Special
Symbols(Reserved words)
int, if fact, avg abc, A +,^ {, #
Numeric Character
Integer Real Single Multi
Character Character
1.05, 2.4e2 A, 1 ABC, $123
Decimal Binary Octal Hexa Decimal
(0-9) (0,1) (0-7) (0-9, A-F)89, 187 01, 110 05, 017 1A, FF
Data Types
Data Types
User defined Derived Primary(fundamental) Empty
typedef, enum Structure, union nullIntegers Real Numbers Characters
int long short float double long double char
Data Type Size(bytes) Size(bits) Range Range (in 2 pow)
int 2 16 -32,768 to 32,767 -215 to 215-1
signed int 2 16 -32,768 to 32,767 -215 to 215-1
unsigned int 2 16 0 to 65,535 0 to 216-1
long 4 32 -2,147,483,648 to 2,147,483,647 -231 to 231-1
signed long 4 32 -2,147,483,648 to 2,147,483,647 -231 to 231-1
unsigned long 4 32 0 to 4,294,967,295 0 to 232-1
short 1 8 -128 to 127 -27
to 27
-1signed long 1 8 -128 to 127 -27 to 27-1
unsigned long 1 8 0 to 255 0 to 28-1
float 4 32 3.4E-38 to 3.4E+38
double 8 64 1.7E-308 to 1.7E+308
long double 10 80 3.4E-4932 to 1.1E+4932
char 1 8 -128 to 127 -27 to 27-1
signed char 1 8 -128 to 127 -27 to 27-1
unsigned char 1 8 0 to 255 0 to 28-1
7
-
8/6/2019 C & DS Notes
8/83
First Program
Let's be polite and start by saluting the world! Type the following program into your favorite editor:
#include < stdio.h>void main()
{printf("\nHello World\n");
}
Save the code in the file hello.c, then compile it by typing:gcc hello.c
This creates an executable file a.out, which is then executed simply by typing its
name. The result is that the characters `` Hello World'' are printed out, preceded by an
empty line.
A C program containsfunctions and variables. The functions specify the tasks to beperformed by the program. The ``main'' function establishes the overall logic of the code. Itis normally kept short and calls different functions to perform the necessary sub-tasks. AllC codes must have a ``main'' function.
Our hello.c code calls printf, an output function from the I/O (input/output)
library (defined in the file stdio.h). The original C language did not have any built-in I/O
statements whatsoever. Nor did it have much arithmetic functionality. The originallanguage was really not intended for ''scientific'' or ''technical'' computation.. Thesefunctions are now performed by standard libraries, which are now part of ANSI C. The K& R textbook lists the content of these and other standard libraries in an appendix.
The printf line prints the message ``Hello World' ' on ``stdout'' (the output
stream corresponding to the X-terminal window in which you run the code); ``\n'' prints a
``new line'' character, which brings the cursor onto the next line. By construction, printfnever inserts this character on its own: the following program would produce the sameresult:
#include < stdio.h>void main(){
printf("\n");printf("Hello World");printf("\n");
}
Try leaving out the ``\n'' lines and see what happens.
The first statement ``#include < stdio.h>'' includes a specification of the C I/O
library. All variables in C must be explicitly defined before use: the ``.h'' files are by
convention ``header files'' which contain definitions of variables and functions necessaryfor the functioning of a program, whether it be in a user-written section of code, or as part
of the standard C libaries. The directive ``#include'' tells the C compiler to insert thecontents of the specified file at that point in the code. The ``< ...>'' notation instructs the
compiler to look for the file in certain ``standard'' system directories.
8
http://www.physics.drexel.edu/courses/Comp_Phys/General/UNIX/editors.htmlhttp://www.physics.drexel.edu/courses/Comp_Phys/General/C_basics/compile.htmlhttp://www.physics.drexel.edu/courses/Comp_Phys/General/UNIX/editors.htmlhttp://www.physics.drexel.edu/courses/Comp_Phys/General/C_basics/compile.html -
8/6/2019 C & DS Notes
9/83
The void preceeding ``main'' indicates that main is of ``void'' type--that is, it has
no type associated with it, meaning that it cannot return a result on execution.
The ``;'' denotes the end of a statement. Blocks of statements are put in braces {...},as in the definition of functions. All C statements are defined in free format, i.e., with nospecified layout or column assignment. Whitespace (tabs or spaces) is never significant,
except inside quotes as part of a character string. The following program would produceexactly the same result as our earlier example:
#include < stdio.h>void main(){
printf("\nHello World\n");}
The reasons for arranging your programs in lines and indenting to show structure should beobvious!
The following program, sine.c, computes a table of the sine function for angles between
0 and 360 degrees.
/************************//* Table of *//* Sine Function *//************************/
#include < stdio.h>#include < math.h>
void main(){
int angle_degree;double angle_radian, pi, value;printf ("\nCompute a table of the sine function\n\n");pi = 4.0*atan(1.0);printf ( " Value of PI = %f \n\n", pi );printf ( " angle Sine \n" );angle_degree=0; /* initial angle value */while ( angle_degree 360 */{
angle_radian = pi * angle_degree/180.0 ;value = sin(angle_radian);printf ( " %3d %f \n ", angle_degree, value );
angle_degree = angle_degree + 10; /* increment the loop index */}
}
The code starts with a series of comments indicating its the purpose, as well as itsauthor. It is considered good programming style to identify and document your work
(although, sadly, most people only do this as an afterthought). Comments can be writtenanywhere in the code: any characters between /* and */ are ignored by the compiler andcan be used to make the code easier to understand. The use of variable names that aremeaningful within the context of the problem is also a good idea.
9
-
8/6/2019 C & DS Notes
10/83
The #include statements now also include the header file for the standard
mathematics library math.h. This statement is needed to define the calls to the
trigonometric functions atan and sin. Note also that the compilation must include the
mathematics library explicitly by typing
gcc sine.c -lm
Variable names are arbitrary (with some compiler-defined maximum length,typically 32 characters). C uses the following standard variable types:
int -> integer variableshort -> short integerlong -> long integerfloat -> single precision real (floating point) variabledouble -> double precision real (floating point) variablechar -> character variable (single byte)
The compilers checks for consistency in the types of all variables used in any code.This feature is intended to prevent mistakes, in particular in mistyping variable names.Calculations done in the math library routines are usually done in double precisionarithmetic (64 bits on most workstations). The actual number of bytes used in the internalstorage of these data types depends on the machine being used.
The printf function can be instructed to print integers, floats and strings properly.The general syntax is
printf( "format", variables );
where "format" specifies the converstion specification and variables is a list ofquantities to print. Some useful formats are
%.nd integer (optional n = number of columns; if 0, pad with zeroes)%m.nf float or double (optional m = number of columns,
n = number of decimal places)%ns string (optional n = number of columns)%c character\n \t to introduce new line or tab\gring the bell (``beep'') on the terminal
Operators
1. Arithmetic operators (+, -, *, /, %)2. Relational Operators (=, ==, !=)3. Logical Operators (&&, ||, !)4. Assignment Operator (=) (a=a+b => a+=b Shorthand notation)5. Increment/Decrement Operators (++, --) (a++, a-- => Post & ++a, a++ Pre)6. Bitwise Operators (&, |, , >>, b ? a+b : a-b)8. Special Operators (,(comma), sizeof())
10
http://www.physics.drexel.edu/courses/Comp_Phys/General/C_basics/compile.htmlhttp://www.physics.drexel.edu/courses/Comp_Phys/General/C_basics/compile.html -
8/6/2019 C & DS Notes
11/83
Truth Tables
Logical Operators
Logical AND Logical OR
A B A&&B
0 0 0
0 nonzero
0
nonzero
0 0
nonzero
nonzero
1
Logical NOT
Bitwise Operators
Bitwise AND Bitwise OR
Bitwise Ex-OR Bitwise NOT
A^B=AB+AB Ones Complement
A B A||B
0 0 0
0 nonzero
1
nonzero
0 1
nonzero
nonzero
1
A !A
0 1
nonzero
0
A B A&B
0 0 0
0 1 0
1 0 0
1 1 1
A B A|B
0 0 0
0 1 1
1 0 1
1 1 1
A B A^B
0 0 0
0 1 1
1 0 11 1 0
A ~A
0 1
1 0
11
-
8/6/2019 C & DS Notes
12/83
Operator Precedence & Associativity
Operator Description Associativity Rank
( )[ ]
Function CallArray element reference
Left to right 1
+-++--!~*&Sizeof(type)
Unary PlusUnary minusIncrementDecrementLogical negation (Logical not)Ones compliment (Bitwise not)Pointer reference (indirection)AddressSize of an objectType cast (conversion)
Right to left 2
*/%
MultiplicationDivisionModulus
Left to right 3
+-
AdditionSubtraction
Left to right 4
>
Left shiftRight shift
Left to right 5
=
Less thanLess than or equal toGreater thanGreater than or equal to
Left to right 6
==!=
Equality (Relational equal to)Inequality (Relational not equal to)
Left to right 7
& Bitwise AND Left to right 8
^ Bitwise EX-OR Left to right 9| Bitwise OR Left to right 10
&& Logical AND Left to right 11
|| Logical OR Left to right 12
? : Conditional Operator (Conditional expression) Right to left 13
=*= /= %=+= -= &=^= |==
Assignment operators Right to left 14
, Comma operator Left to right 15
12
-
8/6/2019 C & DS Notes
13/83
Input FormatsInteger Numbers:
int a,b,c,x,y,p,q,r;printf(Enter three integer numbers);scanf(%d %*d %d,&a,&b,&c); 1 2 3
printf(%d %d %d,a,b,c); 1 3 -3577printf(Enter 2 4-digit numbers);scanf(%2d %4d,&x,&y); 6789 4321
printf(%d %d,x,y); 67 89
printf(Enter 2 2-digit numbers);scanf(%d %d,&a,&x); 44 66
printf(%d %d,a,x); 4321 44printf(Enter 9-digit number);scanf(%3d %4d %3d&p,&q,&r); 123456789
printf(%d %d %d,p,q,r); 66 1234 567printf(Enter 2 3-digit numbers);scanf(%d %d,&x,&y); 123 456
printf(%d %d,x,y); 89 123
Real Numbers:
float x,y;double p,q;
printf(Enter two values);scanf(%f %e,&x,&y); 12.3456 17.5e-2
printf(%f %f,x,y); 12.345600 0.175000scanf(%lf %lf,&p,&q); 4.142857142857 18.5678901234567890
printf(%lf %e,&p,&q); 4.142857142857 1.856789012346e+001
Strings:
char name1[15],name2[15],name3[15],char address[80];
printf(Enter a name);scanf(%15c,name1); 123456789012345printf(%15s,name1); 123456789012345r printf(Enter a name);scanf(%s,name2); New York
printf(%15s,name2); Newprintf(Enter a name);scanf(%15s,name1); London
printf(%s,name1); York printf(Enter a name);scanf(%15c,name1); 123456789012
printf(%15s,name1); 123456789012 r printf(Enter a name);scanf(%s,name2); New-York
13
-
8/6/2019 C & DS Notes
14/83
-
8/6/2019 C & DS Notes
15/83
-
8/6/2019 C & DS Notes
16/83
{ True
Statement 1;Statement 2; false
}else
{ Statement 3;
Statement 4;
}
Syntax of nested if statement:
16
Statement 3Statement 4
iscondition1
-
8/6/2019 C & DS Notes
17/83
iscondition2
if (Condition 1) True{
if (Condition 1){
Statement 1; TrueStatement 2;
}
else { False Statement 3;
Statement 1Statement 2
17
Statement 3Statement 4
-
8/6/2019 C & DS Notes
18/83
iscondition1
Statement 1is
condition2
Statement 2is
condition3
Statement 3
Statement 4
Statement 4;}
}
Syntax of if-else ladder statement: Syntax of switch statement:
if (Condition 1) switch(expression){ {Statement 1; case 1: statement 1;
} break; elseif (Condition 2) case 2: statement 2;
{ break;Statement 2; case 3: statement 3;
} break; elseif (Condition 3) case 4: statement 4;
{ break;Statement 3; default: statement 5;
}else }
{Statement 4;
}
False
True False
True False
True
Syntax of goto statement:
main(){
double x, y;read:scanf(%lf,&x);if(X
-
8/6/2019 C & DS Notes
19/83
TestCondition
?
Body ofthe loop
TestCondition
?
Body ofthe loop
If(x
-
8/6/2019 C & DS Notes
20/83
} }while(condition 1); }} }while(condition 2); }
Nested while loop Nested do-while loop Nested for loop
Most real programs contain some construct that loops within the program,
performing repetitive actions on a stream of data or a region of memory. There areseveral ways to loop in C. Two of the most common are the while loop:
while (expression){
...block of statements to execute...}
and the for loop:for (expression_1; expression_2; expression_3){
...block of statements to execute...}
The while loop continues to loop until the conditional expression becomesfalse. The condition is tested upon entering the loop. Any logical construction (see belowfor a list) can be used in this context.The for loop is a special case, and is equivalent to the following while loop:
expression_1;while (expression_2){
...block of statements...
expression_3;}For instance, the following structure is often encountered:
i = initial_i;while (i
-
8/6/2019 C & DS Notes
21/83
if (angle_degree == 360) break;}
The conditional if simply asks whetherangle_degree is equal to 360 or not; if yes, the loop is
stopped.QUIZ QUESTIONS
1. ________ is a method of representing step by step procedure for solving a problem?a)Algorithm b)Flowchart c)both d)none [ ]
2. _________ is a diagrammatic representation of an algorithm.?a)Flowchart b)Pipeline c)Program d)none [ ]
3.__________ symbol is used to represent decision ?a)Rhombus b)Rectangle c)Circle d)none [ ]
4. _________ symbol is used to represent connector?a)Rhombus b)Rectangle c)Circle d)none [ ]
5. C follows ____________approach?a)Top-Down b)Bottom-Up c)both d)none [ ]
6. _________ is used to convert the code of high level language to m/c level language?a)Compiler b)Interpreter c)Assembler d)both a&b
7. _________ preprocessor directive is used for including header files and other files?a)#include b)#define c)both d)none [ ]
8. What are the steps involved in execution of a C program?
9. What is the expression of an algorithm in a programming language?
10.Give the programming development steps?
11.What is a process of collecting ,organizing and maintaining a complete information aboutthe program?
12. What are the C Tokens?
13. Which one we used to refer the names of variables, functions and arrays?
14. Difference between variable and constant?
15. Types of data types in C?
16. What is the range of values for int data type?
17. Values can be assigned to variables by using which operator?
18. Giving values to variables through keyboard can be done by using which function?
19. What is an Operator?
20. Types of operators?
21
-
8/6/2019 C & DS Notes
22/83
21. Which operator gives the net result true if the condition have the value true, otherwisegives the result false?
22. What is the another name for conditional operator?
23. What is an expression?
24.What are control statement?
25. What is a bi directional conditional control statement?
26. What is an unidirectional control statement ?
27. If the label : is placed after the go to label ; some statement will be skipped?
28. Which operator is used to increment the value of the variable by1 ?
29. Which operator is used to performs operations only at bit level?
30. What is the need of switch Switch Statement?
31. Which statement is used to end the particular case and exit from the switchstatement?
32. What are the loop statements?
33. Difference between while loop and do-while loop?
34. Which symbol is used to give the process in flowcharts?
35. sizeof (long int) is __________
36. a=15 , b=10 , c= - - a b , d=b--+++a printf(%d,(c>d)? 1:0); ________________
37. printf(%06d,9876) = ____________
38. name[20] = NEWDELHI 110001printf(%7s,name)_____________________
39. a=5, printf(%d%d%d,a++,a,++a); _____________________
40. 14 % -3 =________________________
41. \b used for _______________
42. Each case statement in switch() is separated by which statement?
43.#define N 5 m 10 is this a valid statement?
44.How many times statements are executed in dowhile loop(minimum) ?
22
-
8/6/2019 C & DS Notes
23/83
Review Questions
1. What is the purpose of if statement? Describe the different forms of if statement. ?
2. What is the purpose of while and do-while statement? What is the minimum number of times
while and do-while statement will be executed?
3. In what respect for statement is different from while and do-while statement?
4. What is the role of control variable in for statements.
5. Describe switch statement. What is the difference between if and switch statement?
6. How break and continue statements work in repetitive statement?
7. What is the difference between a while and do- while loop?
8. How a for loop can be different with do while loop.
9. Write a program to find the sum of the following series:
1. S=l+3+5+. n2. 5=1+2+4+.n3. S=l+x2+x4+x6+xn.4. s=x+x2/2!+x4!+x6/6!.......xn/n25.
10. Write a program to generate the following pattern
i) 12 3
4 5 67 8 9 10
ii) A B C D E E D C B AA B C D D C B AA B C C B AA B B AA A
11 In a company an employ is paid as follows:
Salary DA HRA
(i) Less then 2000 10% 5%
(ii) Greater then equal to 2000 but less then 4000 25% 15%
(iii) Greater then equal to 4000 but less then 30% 25%
(iv) Greater then 8000 40% 30%
Find the net salary of an employee.
12 The rate of interest offered by a bank on fixed deposite is
i. Period < 6 Months 5%ii. Period < 12 Months 6%
iii. Between 1 year to 3 years 8%iv. Between 3 year to 5 years 9%
v. Above 5 years or more 10%13.What is the difference between conditional and unconditional goto statements?
14.What are breaking control statements?
23
-
8/6/2019 C & DS Notes
24/83
15.What are conditional statement ? Explian in detail in C
UNIT IIArrays:
Arrays of any type can be formed in C. The syntax is simple:
type name[dim];
In C, arrays starts at position 0. The elements of the array occupy adjacent locations inmemory. C treats the name of the array as if it were a pointer to the first element--this isimportant in understanding how to do arithmetic with arrays. Thus, ifv is an array, *v is
the same thing as v[0], *(v+1) is the same thing as v[1], and so on:
Pointer use for an array
Consider the following code, which illustrates the use of pointers:
#define SIZE 3
void main(){
float x[SIZE];
float *fp;int i;for (i = 0; i < SIZE; i++)
x[i] = 0.5*(float)i;for (i = 0; i < SIZE; i++)
printf(" %d %f \n", i, x[i]);fp = x;for (i = 0; i < SIZE; i++)
printf(" %d %f \n", i, *(fp+i));}
24
-
8/6/2019 C & DS Notes
25/83
(The expression ``i++'' is C shorthand for ``i = i + 1''.) Since x[i] means the
i-th element of the array x, and fp = x points to the start of the x array, then *(fp+i) is
the content of the memory address i locations beyond fp, that is, x[i].
STRINGS :
Astring constant, such as
"I am a string"
is an array of characters. It is represented internally in C by the ASCII charactersin the string, i.e., ``I'', blank, ``a'', ``m'',... for the above string, and terminated by the
special null character ``\0'' so programs can find the end of the string.
String constants are often used in making the output of code intelligible using printf ;
printf("Hello, world\n");printf("The value of a is: %f\n", a);
String constants can be associated with variables. C provides the char type
variable, which can contain one character--1 byte--at a time. A character string is storedin an array of character type, one ASCII character per location. Never forget that, sincestrings are conventionally terminated by the null character ``\0'', we require one extra
storage location in the array!
C does not provide any operator which manipulate entire strings at once. Stringsare manipulated either via pointers or via special routines available from the standard
stringlibrary string.h. Using character pointers is relatively easy since the name of an
array is a just a pointer to its first element. Consider the following code:
void main(){
char text_1[100], text_2[100], text_3[100];
char *ta, *tb;int i;char message[] = "Hello, I am a string; what are you?";
printf("Original message: %s\n", message);i=0;while ( (text_1[i] = message[i]) != '\0' )
i++;printf("Text_1: %s\n", text_1);ta=message;tb=text_2;while ( ( *tb++ = *ta++ ) != '\0' )
;printf("Text_2: %s\n", text_2);
}
25
-
8/6/2019 C & DS Notes
26/83
The standard ``string'' library contains many useful functions to manipulatestrings; a description of this library can be found in an appendix of the K & R textbook.Some of the most useful functions are:
char *strcpy(s,ct) -> copy ct into s, including ``\0''; return s
char *strncpy(s,ct,n) -> copy n charcater of ct into s, return s
char *strncat(s,ct) -> concatenate ct to end of s; return s
char *strncat(s,ct,n) -> concatenate n character of ct to end ofs, terminate
with ``\0''; return s
int strcmp(cs,ct) -> compare cs and ct; return 0 if cs=ct,
ct
char *strchr(cs,c) -> return pointer to first occurence of c in cs or
NULL if not encountered
size_t strlen(cs) -> return length of cs
(s and t are char*, cs and ct are const char*, c is an char converted to type int, and n is an int.)
Consider the following code which uses some of these functions:
#include < string.h>void main(){
char line[100], *sub_text;
strcpy(line,"hello, I am a string;");printf("Line: %s\n", line);strcat(line," what are you?");printf("Line: %s\n", line);printf("Length of line: %d\n", (int)strlen(line));if ( (sub_text = strchr ( line, 'W' ) )!= NULL )
printf("String starting with \"W\" ->%s\n", sub_text);if ( ( sub_text = strchr ( line, 'w' ) )!= NULL )
printf("String starting with \"w\" ->%s\n", sub_text);if ( ( sub_text = strchr ( sub_text, 'u' ) )!= NULL )
printf("String starting with \"w\" ->%s\n", sub_text);
}
26
-
8/6/2019 C & DS Notes
27/83
-
8/6/2019 C & DS Notes
28/83
6. itoa(i): integer valueis converted in to string &Returns a stringchar str[20]str=itoa(123)
Storage Classes:
Storage classes gives the information about the
1. Scope of the variable.2. Life time of the variable.3. Where the variable will get the storage.4. The default initial value of the variable.
There are 4 types of storage classes.
1. Automatic2. Register3. Static4. External.
1. Automatic:
Keyword for this storage class is auto. The scope of the variable is local.Thatmeans life time of the variable is within the block or function. It will get the storage inRAM. The default initial value is garbage value.
2. Register:
Keyword is register. The scope of the register variable is local that means lifetimeis within the block or function. It will get the storage in register. The default initial valueis garbage value. Register access time is less when compared to the memory access time.
3. Static:
Keyword is static. The scope of the static variable is local & gloabal. That meanslifetime is within the block or function (if it is local) & throughout the program (if it isglobal). It will get the storage in RAM. The default initial value is Zero.
4. External:
Keyword is extern. The scope of the extern variable is gloabal. That meanslifetime is throughout the program. It will get the storage in RAM. The default initialvalue is Zero.
Storage Class Scope Default Value Storage PlaceAuto Local Garbage RAM
Static Global Zero RAM
Extern Global Zero RAMRegister Local Garbage Register
28
-
8/6/2019 C & DS Notes
29/83
Functions:
Functions are easy to use; they allow complicated programs to be parcelled upinto small blocks, each of which is easier to write, read, and maintain. We have alreadyencountered the function main and made use of I/O and mathematical routines from the
standard libraries. Now let's look at some other library functions, and how to write anduse our own.
Calling a Function:
The call to a function in C simply entails referencing its name with theappropriate arguments. The C compiler checks for compatibility between the arguments
in the calling sequence and the definition of the function.
Library functions are generally not available to us in source form. Argument typechecking is accomplished through the use of header files (like stdio.h) which contain all
the necessary information. For example, as we saw earlier, in order to use the standardmathematical library you must include math.h via the statement
at the top of the file containing your code. The most commonly used header files are
#include < math.h>
< stdio.h> -> defining I/O routines
< ctype.h> -> defining character manipulation routines
< string.h> -> defining string manipulation routines
< math.h> -> defining mathematical routines
< stdlib.h> -> defining number conversion, storage allocation and similar tasks
< stdarg.h> -> defining libraries to handle routines with variable numbers of arguments
< time.h> -> defining time-manipulation routines In addition, the following header files exist
< assert.h> -> defining diagnostic routines< setjmp.h> -> defining non-local function calls
< signal.h> -> defining signal handlers
< limits.h> -> defining constants of the int type
< float.h> -> defining constants of the float type
29
-
8/6/2019 C & DS Notes
30/83
EXAMPLE OF FUNCTION:
A function has the following layout:
return-type function-name ( argument-list-if-necessary ){...local-declarations......statements...return return-value;
}
Ifreturn-type is omitted, C defaults to int. The return-value must be of the declared type. A
function may simply perform a task without returning any value, in which case it has the followinglayout:
void function-name ( argument-list-if-necessary )
{ ...local-declarations......statements...
}
As an example of function calls, consider the following code:
#include < stdio.h>#include < string.h>void main(){
int n;char string[50];strcpy(string, "Hello World");n = n_char(string);printf("Length of string = %d\n", n);
}
int n_char(char string[]){
int n;n = strlen(string);
if (n > 50)printf("String is longer than 50 characters\n");
return n;
Function Meaning Function Meaning
acos(x) Arc cosine of x ceil(x) x rounded up to the nearest integer
asin(x) Arc sine of x exp(x) e to the power of x
atan(x) Arc tangent of x fabs(x) Absolute value of x
atan2(x, y) Arc tangent of x/y floor(x) x rounded down to the nearest integer
cos(x) Cosine of x fmod(x, y) Reminder of x/ysin(x) Sine of x log(x) Natural log of x, x>0
tan(x) Tangent of x log10(x) Base 10 log of x, x>0
cosh(x) Hyperbolic cosine of x pow(x, y) x to the power y(xy)
sinh(x) Hyperbolic sine of x sqrt(x) Square root of x, x>0
tanh(x)Hyperbolic tangent ofx
30
-
8/6/2019 C & DS Notes
31/83
}
Arguments are always passed by value in C function calls. This means that local``copies'' of the values of the arguments are passed to the routines. Any change made tothe arguments internally in the function is made only to the local copies of the arguments.In order to change (or define) an argument in the argument list, this argument must be
passed as an address, thereby forcing C to change the ``real'' argument in the callingroutine.
As an example, consider exchanging two numbers between variables. First let'sillustrate what happen if the variables are passed by value:
#include < stdio.h>void exchange(int a, int b);void main(){
int a, b;
a = 5;b = 7;printf("From main: a = %d, b = %d\n", a, b);exchange(a, b);printf("Back in main: ");printf("a = %d, b = %d\n", a, b);
}
void exchange(int a, int b){
int temp;
temp = a;a = b;b = temp;printf(" From function exchange: ");printf("a = %d, b = %d\n", a, b);
}
Run this code and observe that a and b are NOT exchanged! Only the copies of the arguments are
exchanged. The RIGHT way to do this is of course to use pointers:
#include < stdio.h>
void exchange ( int *a, int *b );void main()
{int a, b;a = 5;b = 7;printf("From main: a = %d, b = %d\n", a, b);exchange(&a, &b);printf("Back in main: ");printf("a = %d, b = %d\n", a, b);
}
void exchange ( int *a, int *b ){
31
-
8/6/2019 C & DS Notes
32/83
int temp;temp = *a;*a = *b;*b = temp;printf(" From function exchange: ");printf("a = %d, b = %d\n", *a, *b);
}
The rule of thumb here is that
You use regular variables if the function does not change the values of those arguments You MUST use pointers if the function changes the values of those arguments
QUIZ QUESTIONS
1. Array is collection of____________
2. Array elements are stored in _________________
3. A character array always ends with ________________
4. If you declare array without static , the elements it will be set to ___________
5. Declaring the name and the type of the array and setting the no of elements in the array is
known as ____________________the array.
6. All array subscripts begin with __________________
7. Array is a data structure which can hold multiple variable of _______________
8. A number with in square brackets that differentiates one element of an arraqy from another
is called ________________________
9. An array having more than one subscript is called _________________
10. the string will always terminate with _______________________
11. We can initialize an array using___________________________
12. The second subscript in 2Dimentional array designate_______________________
13. sizeof( ) indicates ________________
14. Total no of characters in the array is always _______________more than the string length.
15. s1 = welcome to, s2 = GIET ,strcat(s1,s2) is _________________
16. Memory space allocated for an integer array of eight elements is _________________
17. The main( ) function is ______________
32
-
8/6/2019 C & DS Notes
33/83
18. s1[10]=welcome l = strlen(s1) then l = ___________________
19. s1[10] = their,s2[10] = there ,x=strcmp(s1,s2) then x = _______________
20. x = z-1, then x = _______________
21. It is necessary to declare the type of a function in the program if ________________
22. Recursion is a process in which the function calls_______________
23. By default function returns __________________
24. The meaning of keyword void before the function name means____________________
25. If a storage class not mentioned in the declaration then default storage class is ________
26. Actual parameters are ___________________
27. What is a function __________________
28. The keyword return is used in __________________
29. Formal Arguments are _____________________
30. Recursive function is ____________________
31. Header file includes _____________________
32. Identifier storage class determines ____________________
33. call by value method refers to _____________________
34. Call by reference method used to __________________
35. Preprocessor allows ________________
36. #endif indicates _________________
33
-
8/6/2019 C & DS Notes
34/83
Review Questions
1. What is an array? How it differs from the ordinary variable?
2. What are subscripts? How are they written? What restrictions apply to the values that can be
assigned to subscripts ?
3. How arrays are usually processed of two matrices?
4. Write a program to print the multiplication of two matrices?
5. Write a program to find the Sum of elements above and below the main Diagonal of Matrix.
6. Write a program to print the Upper and Lower Triangular Elements of the Main Diagonal of a
Matrix.
7. What do you mean by function prototyping? Write down the advantages of function prototypes
in C
8. What is a function? State the advantages of using functions.
9. What is recursion? What advantage is there in its use?
10. Differentiate between recursion and iteration.
11Write a program to read a string and check whether it is a palindrome string or not Palindrome
is
string that reads the same from left to right and vice versa.
12. Write a program to find the number of vowels in the given line text.
13. Write about String built-in functions.
14. What are Storage Classes? Give the classification of storage classes.
34
-
8/6/2019 C & DS Notes
35/83
15. What is the difference between one dimension and two dimensional arrays.
16. Write a program to add two matrices using static statement and global variables.
UNIT III
Pointers:
The C language allows the programmer to ``peek and poke'' directly into memorylocations. This gives great flexibility and power to the language, but it also one of thegreat hurdles that the beginner must overcome in using the language.
All variables in a program reside in memory; the statements
float x;x = 6.5;
request that the compiler reserve 4 bytes of memory (on a 32-bit computer) forthe floating-point variable x, then put the ``value'' 6.5 in it.
Sometimes we want to know where a variable resides in memory. The address(location in memory) of any variable is obtained by placing the operator ``&'' before its
name. Therefore &x is the address ofx. C allows us to go one stage further and define a
variable, called a pointer, that contains the address of (i.e. ``points to'') other variables.For example:
float x;
float* px;x = 6.5;px = &x;
defines px to be a pointer to objects of type float, and sets it equal to the address ofx:
35
-
8/6/2019 C & DS Notes
36/83
Pointer use for a variable
The content of the memory location referenced by a pointer is obtained using the``*'' operator (this is called dereferencingthe pointer). Thus, *px refers to the value ofx.
C allows us to perform arithmetic operations using pointers, but beware that the``unit'' in pointer arithmetic is the size (in bytes) of the object to which the pointer points.For example, ifpx is a pointer to a variable x of type float, then the expression px + 1refers not to the next bit or byte in memory but to the location of the next
floatafter
x(4
bytes away on most workstations); ifx were of type double, then px + 1 would refer to
a location 8 bytes (the size of a double)away, and so on. Only ifx is of type char will px
+ 1 actually refer to the next byte in memory.
Thus, in
char* pc;float* px;
float x;
x = 6.5;px = &x;pc = (char*) px;
(the (char*) in the last line is a ``cast'', which converts one data type to another),
px and pc both point to the same location in memory--the address ofx--but px + 1 and
pc + 1 point to differentmemory locations.
Consider the following simple code.
void main(){
float x, y; /* x and y are of float type */float *fp, *fp2; /* fp and fp2 are pointers to float */x = 6.5; /* x now contains the value 6.5 */printf("Value of x is %f, address of x %ld\n", x, &x); /* print contents and address of x */fp = &x; /* fp now points to location of x */printf("Value in memory location fp is %f\n", *fp); /* print the contents of fp */
*fp = 9.2; /* change content of memory location*/printf("New value of x is %f = %f \n", *fp, x);
*fp = *fp + 1.5; /* perform arithmetic */printf("Final value of x is %f = %f \n", *fp, x);y = *fp; /* transfer values */
36
-
8/6/2019 C & DS Notes
37/83
fp2 = fp;printf("Transferred value into y = %f and fp2 = %f \n", y, *fp2);
}
Run this code to see the results of these different operations. Note that, while thevalue of a pointer (if you print it out with printf) is typically a large integer, denoting
some particular memory location in the computer, pointers arenot
integers--they are acompletely different data type.
Command-line arguments:
It is standard practice in UNIX for information to be passed from the commandline directly into a program through the use of one or more command-line arguments, or
switches. Switches are typically used to modify the behavior of a program, or to set thevalues of some internal parameters. You have already encountered several of these--forexample, the "ls" command lists the files in your current directory, but when the switch
-l is added, "ls -l" produces a so-called ``long'' listing instead. Similarly, "ls -l -a"
produces a long listing, including ``hidden'' files, the command "tail -20" prints out
the last 20 lines of a file (instead of the default 10), and so on.
Conceptually, switches behave very much like arguments to functions within C,and they are passed to a C program from the operating system in precisely the same wayas arguments are passed between functions. Up to now, the main() statements in our
programs have had nothing between the parentheses. However, UNIX actually makesavailable to the program (whether the programmer chooses to use the information or not)two arguments to main: an array of character strings, conventionally called argv, and an
integer, usually called argc, which specifies the number of strings in that array. The full
statement of the first line of the program is
main(int argc, char** argv)
(The syntax char** argv declares argv to be a pointer to a pointer to a character,
that is, a pointer to a character array (a character string)--in other words, an array ofcharacter strings. You could also write this as char* argv[]. Don't worry too much
about the details of the syntax, however--the use of the array will be made clearer below.)
When you run a program, the array argv contains, in order, allthe information on
the command line when you entered the command (strings are delineated by whitespace),
including the command itself. The integerargc gives the total number of strings, and istherefore equal to equal to the number of argumentsplus one. For example, if you typed
a.out -i 2 -g -x 3 4
the program would receive
argc = 7argv[0] = "a.out"argv[1] = "-i"argv[2] = "2"argv[3] = "-g"argv[4] = "-x"argv[5] = "3"
37
-
8/6/2019 C & DS Notes
38/83
argv[6] = "4"
Note that the arguments, even the numeric ones, are allstrings at this point. It isthe programmer's job to decode them and decide what to do with them.
The following program simply prints out its own name and arguments:
#include < stdio.h>main(int argc, char **argv){
int i;printf("argc = %d\n", argc);for (i = 0; i < argc; i++)
printf("argv[%d] = \"%s\"\n", i, argv[i]);}
UNIX programmers have certain conventions about how to interpret the argument
list. They are by no means mandatory, but it will make your program easier for others touse and understand if you stick to them. First, switches and key terms are always
preceded by a ``-'' character. This makes them easy to recognize as you loop through theargument list. Then, depending on the switch, the next arguments may containinformation to be interpreted as integers, floats, or just kept as character strings. Withthese conventions, the most common way to ``parse'' the argument list is with a for loop
and a switch statement, as follows:#include < stdio.h>#include < stdlib.h>
main(int argc, char** argv){
int a_value = 0;float b_value = 0.0;char* c_value = NULL;int d1_value = 0, d2_value = 0;int i;for(i = 1; i < argc; i++){
if (argv[i][0] == '-'){
switch (argv[i][1]){
case 'a': a_value = atoi(argv[++i]);break;
case 'b': b_value = atof(argv[++i]);break;
case 'c': c_value = argv[++i];break;
case 'd': d1_value = atoi(argv[++i]);d2_value = atoi(argv[++i]);break;
}}
}
printf("a = %d\n", a_value);printf("b = %f\n", b_value);
if (c_value != NULL) printf("c = \"%s\"\n", c_value);printf("d1 = %d, d2 = %d\n", d1_value, d2_value);
}
38
-
8/6/2019 C & DS Notes
39/83
Note that argv[i][j] means the j-th character of the i-th character string. The if statement
checks for a leading ``-'' (character 0), then the switch statement allows various courses of action
to be taken depending on the next character in the string (character 1 here). Note the use ofargv[+
+i] to increase i before use, allowing us to access the next string in a single compact statement.
The functions atoi and atof are defined in stdlib.h. They convert from character strings to
ints and doubles, respectively.
A typical command line might be:
a.out -a 3 -b 5.6 -c "I am a string" -d 222 111
(The use of double quotes with -c here makes sure that the shell treats the entire string, including
the spaces, as a single object.)
Arbitrarily complex command lines can be handled in this way. Finally, here's a simple programshowing how to place parsing statements in a separate function whose purpose is to interpret thecommand line and set the values of its arguments:
/********************************//* *//* Getting arguments from *//* *//* the Command Line */
/* *//********************************/
/* Steve McMillan *//* Written: Winter 1995 */
#include < stdio.h>#include < stdlib.h>
void get_args(int argc, char** argv, int* a_value, float* b_value){
int i;
/* Start at i = 1 to skip the command name. */
for (i = 1; i < argc; i++) {
/* Check for a switch (leading "-"). */
if (argv[i][0] == '-') {
/* Use the next character to decide what to do. */
switch (argv[i][1]) {
case 'a': *a_value = atoi(argv[++i]);break;
case 'b': *b_value = atof(argv[++i]);break;
default: fprintf(stderr,"Unknown switch %s\n", argv[i]);
}
39
-
8/6/2019 C & DS Notes
40/83
}}
}
main(int argc, char** argv){
/* Set defaults for all parameters: */
int a = 0;float b = 0.0;
get_args(argc, argv, &a, &b);
printf("a = %d\n", a);printf("b = %f\n", b);
}
QUIZ QUESTIONS1. int a,b,*ptr;
ptr=&a;a=9;b=*ptr;
a++;what is the value of a,b,*ptr.
2.int a.b*ptr;a=9;ptr=&a;b=*ptr;what is the value of a,b, *Ptr.
3.int a,b,*ptr;a=9;ptr=&a;b= *ptr;
*ptr += 2;what is the value of a,b, *ptr.
4. int a,b, *ptr; a=9;ptr=&a;b= *ptr;ptr=&b;++b;what is the value of a,b, *ptr ?
5. What is the need of malloc() function.6. What is the need of calloc() function.7. What is the need of pointer.8. What is the need of & operator.
9. What is the need of * operator.10.main()
{static char a[] = BOMBAY;
40
-
8/6/2019 C & DS Notes
41/83
char *b=BOMBAY;printf (\n %d %
-
8/6/2019 C & DS Notes
42/83
printf("%s\n",ptr);ptr++;printf("%s\n",ptr);
}18.#includemain()
{ char s1[]="Ramco";char s2[]="Systems";s1=s2;printf("%s",s1);
}19. main(){
char *p1="Name";char *p2;p2=(char *)malloc(20);
while(*p2++=*p1++);printf("%s\n",p2);
}20. main(){
char *p1="Name";char *p2;p2=(char *)malloc(20);while(*p2++=*p1++);printf("%s\n",p2);
}
21. .while((*p++=*q++)!=0){}is equal to
expl: while((*p++=*q++)!='\0'){}22. . int *x[](); means23. int a=1, b=2, c=3, *pointer;
pointer=&c;a=c/*pointer;
b=c;printf("a=%d b=%d",a,b);24. int a[5],*p;
for(p=a;p
-
8/6/2019 C & DS Notes
43/83
string[12];}sizeof(class)=?
28. int *p;i=10;
p=i;
printf("%d",*p);29. main(){
char a[2];*a[0]=7;*a[1]=5;printf("%d",&a[1]-a)}
30. #include
-
8/6/2019 C & DS Notes
44/83
}ii) main()
{int i,*ptr, x[10]={1,2,3,4};for (i=0 ;i< 10;i++)
{
printf(%d\n, *ptr);ptr++;}
}14. Name some areas to application of two-dimensional arrays.15.Write a program that uses the sizeof operator to print the size of an array declared in the
program. Use the sizeof operator on the name of the array.
UNIT -IV
Structures :
Structure is a collection of logically related items that can be potentially of different types. Eachsuch item is called member, because the members of a structure can be of various types, the
programmer can create aggregates of data that are suitable for a particular application. The dotoperatoris used to access the members of a structure.
Suppose the following declaration:
struct m {
int a;
char b;
char c[5];
};
struct m my_struct;
How many bytes the variable my_struct occupies in the memory?member a occupies two bytes, member b occupies 1 byte and member c occupies 5 bytes. Thensize of my_struct is 2+1+5 = 8.
Accessing Members of a Structure:
Beside the dot operator ".", We will introduce themember access operator "->".
44
-
8/6/2019 C & DS Notes
45/83
C provides the latter operator -> to access the members of a structure via a pointer, if a pointervariable is assigned the address of a structure, then a member of the structure can be accessed by aconstruct of the form
pointer_to _structure -> member_name.
PASSING OF STRUCTURES AS ARGUMENTS:Structures can be passed as arguments to functions.Struct complex
{float real, image;}
the structure complex is declared. This structure has two members and both of them arefloats,real part and the imap represent theimaginary part of the complex number.
struct complex a = {2.0, -3.0};struct complex b = (-4.0, -7.0};struct complex c;
in the main we have declared three variables and initialized two of them. However, it ispossible toaccept, these two complex numbers interactively also using scanf(), which we shallpresent in thenext program.
void print_complex(struct complex x){
char sign = +;if (x.image < 0){
sign=-;x.image= abs (x.image);
}
printf (\n%0.2 %c j%0,2f-. x.real,sig,x.image);}
SELF REFERENTIAL STRUCTURES :In C, we have the structures, which can be made self-referential. A self-referential
structure is one that includes within its structure at least one member which is a pointer to the samestructure type.
With self-referential structures, we can create very useful data structures such aslinkedlists, trees, etc.
The creation and usage of self-referential structures is elaborately discussed inchapters onlinked lists, trees and graphs.typedefREVITISED:
There typedef was only illustrated for basic data types. We now extend the usage oftypedef to other data types such as pointers and structures. The declaration
typedef char * stringmakes string as a data type which is same as character pointer (char *). We can now usedeclaration and casts such as,
string p; /*p is a character pointer */POINTERS TO STRUCTURES :
If a large structure is to be passed to a function, it is generally more efficient to pass apointer than to copy the whole structure into a local variable in the function. Pointers to structuresare just like the pointers to any other variable.
If p is a pointer to a structure p->member-of-structure refers to the particular member.Now an assignment p = &a makes p point to structure a. The real part of the structure acan now be referenced as (*p).real and the imaginary part can be references (*p).image. The
45
-
8/6/2019 C & DS Notes
46/83
parenthesis are necessary around p because the precedence of the structure member operator dot(.)is higher than *.
Pointers to structures are so frequently used that alternative notation is provided withoutparentheses as a short hand.ARRAY OF STRUCTURES
C provides the facility to declare arrays of structures. These structures can also be
initialized just like any other data type. In this way, C is consistent in representing data type.Thatis how we can consistently define, structures within a structure or an array of structures and so on.This property is referred as orthogonality of a language.
Struct oval_counter{
char *name;int count;
};the structure oval_counter is declared outside the main with two members. The first one is
the pointer to a character and the second is an integer.struct oval_counter x[] ={
{VOWELS, 0),{DIGITS, 0),{COSONENTS. 0),{SPECIAL SYMBOLS, 0}};
in the main the array of structure oval_counter is declared and initialized with appropriate pairs ofnames and the counter value
Unions :
A union, like structure, is a derived type. They follow the same syntax as structures but havemembers that share storage. A union type defines a set of alternative values that may be stored in ashared portion of memory.The declaration of this type is as follows:union int_or_float{int i;
float f;
};
union int_or_float a;/*The storage is allocated at this stage*/
This declaration allocates storage for the identifier a. For each variable the compiler allocates apiece of storage that can be accommodate the largest of the specified members. Note that the tagname along with the keyword union, can be used to declare variables of this type.
BIT FIELD:
In many hardware applications, it is necessary to pack several states of information into asingle machine word. For example, the status of a printer could be lead as a single word into the
program and each bit in the status word could mean some specific state of the printer like paperempty, power off, hardware error, etc. For each of this bits are referred as flags. The usual way to
handle the status word is to define a set of MASKS* corresponding to relevant bit positions as in,#definePAREREMTY 01#define POWEROFF 02
46
-
8/6/2019 C & DS Notes
47/83
#define HWERROR 0Note that the numbers chosen is a power of 2, since when we bitwise AND with the status
only the bit at kth position(given by 2k) is not masked and all other bits will be 0s.Thus, if we test the status word, we know whether the particular bit is set or not. For
example ,if ((flags & POWEROFF) ==1)
. .Where flags is the status word.Although, this is one way ot handling the status word, Coffers, the capability of defining and accessing fields within a word directly rather than using
bitwise, logical operators. This is possible with the bit fields. A bit-field is a set of adjacent bitswith in a single word. Not)c the set can contain, 0, 1, 2, , etc., bits. For example, the above#defines, could be placed by the definition of three bit fields.
struct{unsigned int PAPEREMPTY : 1;unsigned int POWKROFF : 1;unsigned int HWERROR : 1;} flags;
void main (void){
flags.PAPEREMPTY =0;flags.POWEROFF=0;flags.HWERROR =1;if(flags.PAPEREMPTY ==1)
printf(\nNo Paper in the Printer.)}if(flags.POWEROFF == 1)
printf(\nNo Power to the Printer.);if(flags.HWERROR ==1)
printf(\nThare la a Hardware Error.);
In the program we have initialized various bit fields with 0s and 1s However, in actual practice, thestatus word will be read into variable flags.
QUIZ QUESTIONS
1. #include
-
8/6/2019 C & DS Notes
48/83
}*head;
the struct head.x =100above is correct / wrong4.what is structure?
5.In structure storage class refers to?6.Who defines user defined name in the structure ?
7.What is data member in c?
8.Start of structure is shown by which keyword?9. main()
{struct{int a, b;
}x,y;x.a=10;y=x;
printf( %d,y.a);}
what is the output of above program?10. A union can also be stored as member of the struct ? true/false .11. Is it pointer can also store the address of the heterogeneous types of elements ? true /false12. what the data type that is similar to structure with a difference in the way data is stored andretrieved?13. main(){
struct emp{char ch[7];char *s;};static struct emp ={ programming ,basic};
printf(%C%c ,e.ch[0],*e.s);printf(%s%s,e.ch,e.s);}what is the output of above program?14. what is the use of structuctes with pointers?15.what is a collection of related variables under one name?16. what is the operator used to access the structure ?17. what are self referential structures?18. define bit fields?19. which is used to pass arguments to a program when the program is invoked from the commandline?20. main(int argc,char * argv[] ){int i;
printf ( %d ,argc);
for (i=1;i
-
8/6/2019 C & DS Notes
49/83
22. p=&a means23.what is the common word used for structure?24.Trees and link lists are created by which type of structure?25. we can store several Booleans variable in how many bytes if storage is limited ?26. which are frequentl used analying inputs from hard ware device?27.the bit fields can not be arranged in declaring as?
28.what is the operator used to assign bit fields?29.when a structure refers with in another structure is called?30.which is can also be used as member of structure?
Review Questions
1. What is a structure in C? How structure is declared?2. What is the use of struct keyword? Explain the use of dot operator.3. How are structure elements stored in memory4. Explain nested structure. Draw diagram to explain nested structure.5. How are arrays of structure variables defined. How are they beneficial to the programmer?
6. What is a union in C? How is data stored using union?7. What are the differences between union and structure?8. Explain the importance of bit fields. How do bit fields saves memory space?9. Is it possible to pass structure variable to function? Explain in detail the possible ways.10 How are structure elements accessed vising pointer? Which operator is used?11.Write statements that accomplish each of the following. Assume that the structure:struct person
{char last name [15], first name[15] , age[4];};.Has been defined and that the file is already open for writing.
(a) Initialize the file name age. dat so that there are 100 records with last name = unassigned,first name= and age = 0 (b) Input 10 last names, first names and ages and write them to the file.(c) Update a record; if there is no information in the record, tell the user No Information(d) Delete arecordtha has information by reinitializing that particular record.12. main()
{struct a{
char ch[7];char *str;
};static struct a s1 = {Nagpur, Bombay};
printf (%c%c,s1.ch[0],*s1.str);printf(%s%s\n,s1.ch,s1.str);
}What will be the output of the above program .
13. main(){struct node{int data;
struct node *link;};
struct node *p,*q;
49
-
8/6/2019 C & DS Notes
50/83
p = malloc (sizeof (struct node));q = malloc (sizeof (struct noae));prifitf(%d %d, sizeof (p), sizeof (q));}
What will be the output of the above program .14. main()
{union a{int i;
char ch[2];};
union a u;u.i= 256;printf (%d %d %d,u.i,u.ch[0],,u.ch[1]);
}What will be the output of the above program .
15.Explain the use of structures with pointers.16.Explain the general syntax of structures both having one object and array of objects using
appropriate examples.
UNIT V
Standard I/O :
Character level I/O
C provides (through its libraries) a variety of I/O routines. At the character level, getchar() reads
one character at a time from stdin, while putchar() writes one character at a time to stdout. For
example, consider
#include < stdio.h>
void main(){
int i, nc;
nc = 0;i = getchar();while (i != EOF) {
nc = nc + 1;i = getchar();
}printf("Number of characters in file = %d\n", nc);
}
This program counts the number of characters in the input stream (e.g. in a file piped into it atexecution time). The code reads characters (whatever they may be) from stdin (the keyboard),
uses stdout (the X-terminal you run from) for output, and writes error messages to stderr
(usually also your X-terminal). These streams are always defined at run time. EOF is a specialreturn value, defined in stdio.h, returned by getchar() when it encounters an end-of-file marker
when reading. Its value is computer dependent, but the C compiler hides this fact from the user by
50
-
8/6/2019 C & DS Notes
51/83
defining the variable EOF. Thus the program reads characters from stdin and keeps adding to the
counternc, until it encounters the ``end of file''.
An experienced C programmer would probably code this example as:
#include < stdio.h>
void main(){
int c, nc = 0;
while ( (c = getchar()) != EOF ) nc++;
printf("Number of characters in file = %d\n", nc);}
C allows great brevity of expression, usually at the expense of readability!
The () in the statement (c = getchar()) says to execute the call to getchar() and assign theresult to c before comparing it to EOF; the brackets are necessary here. Recall that nc++ (and, in
fact, also ++nc) is another way of writing nc = nc + 1. (The difference between the prefix and
postfix notation is that in ++nc, nc is incremented before it is used, while in nc++, nc is used
before it is incremented. In this particular example, either would do.) This notation is morecompact (not always an advantage, mind you), and it is often more efficiently coded by thecompiler.
The UNIX command wc counts the characters, words and lines in a file. The program above can be
considered as your own wc. Let's add a counter for the lines.
#include < stdio.h>
void main(){
int c, nc = 0, nl = 0;
while ( (c = getchar()) != EOF ){
nc++;if (c == '\n') nl++;
}
printf("Number of characters = %d, number of lines = %d\n",
nc, nl);}
Can you think of a way to count the number of words in the file?
Higher-Level I/O capabilities
We have already seen that printf handles formatted output to stdout. The counterpart statement
for reading from stdin is scanf. The syntaxscanf("format string", variables);
resembles that ofprintf. The format string may contain blanks or tabs (ignored), ordinary ASCII
characters, which must match those in stdin, and conversion specifications as in printf.
Equivalent statements exist to read from or write to character strings. They are:
51
-
8/6/2019 C & DS Notes
52/83
sprintf(string, "format string", variables);scanf(string, "format string", variables);
The ``string'' argument is the name of (i.e. a pointer to) the character array into which you want towrite the information.
Files:
Storage of data in variables and arrays is temporary. Files are usd for permanent retention oflarge amounts of data. Computer stores on secondary storage device such as magnetic disks,opticaldisks and tapes.C view search files simply as a sequence of bytes.Each file ends either with an end of file marker
or at a specific byte number recorded in data structures,when a file is opened an object is createdand a stream is associated with the object.The C file is composed of several interrelated functions.The most common of these are :
______________________________________________________________________________ Name Function
fopen() Opens a file
fclose() Closes a fileputc() Writes a character to a file.fputc() Same as putc()getc() Reads a character from a file.fgetc() Same as getc()fgets() Reads a file from a filefputs() Writes a string to a filefseek() Seeks to a specified byte in a fileftell() Returns the current file position
fprints() Is to a file what printf() is to consolefscanf() Is to a file what scanf() is to the console.
feof() Returns true if end-of-file is reached.ferror() Returns true if end-of-file is reached.
rewind() Resets the file position indicator to thebeginning of the file.
remove() Erases a file.fflush() Flushes a file.
The File Pointer:
The file name can be indicated by a file pointer.This can be used in a place of name of file.Thiscan be written as
FILE *fptr
Where *fptr-File Pointer Variable declared from name FILE.
Opening a file:
To Store or to retrieve the data to and from a file should be opened in the beginning of theprogram.To open a file ,the function fopen() is used.This function returns a pointer to a file.It is as follows:
File pointer=fopen(filename,mode);File pointer-This is the logical name given to the data and result file throught the program,thendata\result file is reffered by this file pointer.File name-A file name in which the data to be stored or retrieved.Mode-A file can be opeed in various ways.
Mode Meaning
r Opens a text file for reading.w Creates a text file for writing.
52
-
8/6/2019 C & DS Notes
53/83
a Append to a text file.rb Opens a binary file for reading.wb Create a binary file for reading.R+ Opens a text file for read/write.
W+ Create a text file for read/write.A+ Append or create a text file for read/write.
______________________________________________________________________________
Operatations On Files :
Similar statements also exist for handling I/O to and from files. The statements are
#include < stdio.h>
FILE *fp;
fp = fopen(name, mode);
fscanf(fp, "format string", variable list);fprintf(fp, "format string", variable list);
fclose(fp );
The logic here is that the code must
define a local ``pointer'' of type FILE (note that the uppercase is necessary here), which is
defined in < stdio.h> ``open'' the file and associate it with the local pointer via fopen
perform the I/O operations using fscanf and fprintf
disconnect the file from the task with fclose
The ``mode'' argument in the fopen specifies the purpose/positioning in opening the file: ``r'' for
reading, ``w'' for writing, and ``a'' for appending to the file. Try the following:
#include < stdio.h>
void main(){
FILE *fp;int i;
fp = fopen("foo.dat", "w"); /* open foo.dat for writing */
fprintf(fp, "\nSample Code\n\n"); /* write some info */for (i = 1; i
-
8/6/2019 C & DS Notes
54/83
2. A field is a group of characters that conveys meaning for example, a field consisting s solelyof
Uppercase and lowercase letters can be used to represent a persons name.3. What is a sequence bytes?4. Which key identifies a record as belonging to particular person entity that is unique from allother
Records in the file?55. The file name can be indicated by?6. To open a file, the function is used as?7. If error occurs fopen function returns a file pointer by returning?8. All the files that are opened should be closed after all input operations with the file usingwhich
Function?9) Which function reads characters from a file opened in read mode?10) Fprintf function works similar to?11) Which function is used for the printing of the result calculated in the program on the filereferred by the file pointer?
12) Which function works in the same way as scanf ?13) Which function is used to find out whether it is the end of file which is reached. ?14) Which function is used to indicate the size of file in bytes. ?15) This function writes the contents of any buffered data to the file associated with fp?.16)If you call a function with file pointer being null, all files opened for output are flushed ?whatis that function?17) Which function erases the specified file. ?18) In remove() function if successful, which value is returned?19 Main()
{char ch;
printf(enter any number.);scanf(%d, &a);fflush(stdin);printf(Enter any character.);scanf(n%d%c,a,ch);
}what is the output of above program?20) . main(){static char str[ ]=Programmingprintf(%s\n%s, str, Programming)
}What will be the output of following program segments?
21)main( ){
printf(%20s\n, Short leg);printf(%20s\n, Long leg);printf(%20s\n, deep fine leg);printf(%20s\n, backward short leg);printf(%20s\n, legs all the same!);
}What will be the output of following program segments?22) main(){static char str[ ]= The c standard library.chars;*s;s=str:
54
-
8/6/2019 C & DS Notes
55/83
while(*s)
{putch(*s);s++;}printf(\n);
s=str;while(*s){
putchar(*s);s++;}What will be the output of following program segments?
23). main( ){char name[20], sname[20];
puts (enter your name and surname\n);
gets(name, sname);puts(name, sname);printf(%s%sname.sname);}What will be the output of following program segments?
24) main(){char strl [30], str2[30];
printf(Enter a sentence\n);scanf%s, strt);
printf(%s, strl);
fflush(stdin);printf(\Enter a sentence);gets(str2);
printf(%d,str2);}what is the output of above program?
Review Questions
(UNIT-V)
1.What are files?2. What are streams? Discuss two types of streams..3.What is file pointer? What information is provided by it ?4. Describe the functions fclose and fopen.5. What are input and output functions written in C for files ?6. Describe fputsO and fgetsO functions.7. Write a program to find the size of the file using ftell and seek function.8.Write a program to read five numbers from a file and calculate average of the numbers and print
inanother output file.
9. What are the different modes in which a file can be opened ?10.What is difference between feof and EOF functions ?
55
-
8/6/2019 C & DS Notes
56/83
60
50
40
30
20
50
40
30
20
40
30
20
11.Write a program in C that compares two files and issues the messagefile1 and file2 are identical . when the files are the same or issue the message
file1 and file2: first difference in byte number =when they are different. The names of two files should appear as command line parameters.
12.Write a program to maintain the record of different parts available in the store using theirpart number, name, quantity, rate and write it in a file.
13.Write a program to prepare salary bill of company using an input data file to store the data andoutput file to store the pay slips of employers.14.Write a program to prepare roll list of students in a file by supplying the roll no from the screen.15.Distinguish between the following functions.
a) scanf() andfscanf() b) getc() and getchar() c) putc() and fputc()d) putw() and getw() e) ferror() and ferror() f) feof() andeof()
UNIT - VI
DATA STRUCTURES : Stacks & Queues
Stack:
Top 30
Top 20 20
Top
Stack created with push one element Push one elementsize 5 (Stack is (Stack having 1 (Stack having 2 elements,empty, Top=0) element, Top=1) Top=2)
Top
Top
Top
56
-
8/6/2019 C & DS Notes
57/83
Push three elements Pop one element Pop one element(Stack is full (Stack having (Stack having 3 elements,(5 elements),Top=5) 4 elements, Top=4) Top=3)
Pop three elements Stacked is deleted(Stack is empty,Top=0)
Top
Stack And Its Implementation In C :
The previous discussion used such construction (structures) in which the access to any particularelement was provided by means of dot operator "." Certain practical applications require arestriction when accessing elements of data structure used, and one of the classical examples ofsuch structures is a STACK.
Definition: A stack is a collection (linear) of elements of the same type which can be accessed onlyat one end called a TOP of the stack. Stack structure is often called LIFO (Last In First Out)structure.
According to the definition, the number of elements in a stack is potentially unlimited, and thisstructure allows Insertion / Deletion of elements at any time, it becomes a dynamic in nature.There are two basic operations on stack:
1. PUSH (Insertion Operation): Inserts an element at the TOP of the stack.2. POP (Deletion Operation): Deletes an element from the TOP of the stack.
When performing POP operations, a possible situation of UNDERFLOW (stack is empty) has tobe checked.
Implementation of stacks using ARRAY structure :
This way of implementation uses a STATIC structure ARRAY (It is declared in the program and itis known at the compile-time) for representation of dynamic structure static (it changes in time).
Such approach has certain disadvantage (Although array and stack are linear collections ofelements of the same type).
57
-
8/6/2019 C & DS Notes
58/83
The number of elements in array is limited (stack, according to definition is unlimited), andwhile using array for implementation of stack, we have to check a possible situation ofOVERFLOW (no chance to push a new element on to the stack, because array is full).
Stack is changing Dynamically, but the nature of array is static, Essentially stack should becreated (stack should be declared). From the beginning stack is empty. (array can beconsidered as a home for stacks elements). stack is a structure that contains two elements :
1. Array2. Single variable top, And it is empty because the variable tophold 0 in it.
When the first element is to be pushed onto the stack, we can clear the picture by the followingdiagram:
Suppose operation PUSH is applied several times, then the current status of a stack can berepresented as follows
Applications of stack structures :
Evaluation of arithmetic expressions:
Any parentheses ((...)) free expression is evaluated according to precedence rules (theorder of the arithmetic operations), for binary (require two operands) arithmeticoperations. These rules can be shortly summarized as follows
1. Exponentiation (^ or $).2. Multiplication and Division (* and /), higher priority.3. Summation and Subtraction (+ and -), lower priority.
If you would like to change the "default" priority rules of expressions evaluation, you have to useparentheses.
a - b * c not equivalent to (a - b) * c
For writing arithmetic expressions based on binary operators we normally use so called INFIXform, for example the operator between two operand like a + b is written in INFIX form.
If we would like the arithmetic expression represented in the INFIX form to be evaluated by thecompiler automatically the computer will definitely face with certain problems:
The initial expression (INFIX form), requires several steps ofscanning in order to "extract" all subexpression involved into evaluation
process: a-b*c+d/e, if there are operations that have the same precedence,they are performed from left to right.
scanning1: evaluation b*c, evaluation d/e
scanning2: evaluation a-b*c, evaluation (a-b*c) + (d/e)
Each expression may include a certain number of subexpression enclosedinto parentheses, this implies that the order of expressions evaluation is changed,
58
-
8/6/2019 C & DS Notes
59/83
and computer again has to scan the expression in order to search for the nextsubexpressions for evaluation.
Beside the well known and commonly used INFIX form of arithmetic expressions, two otherforms are known as PREFIX and POSTFIX are used as well. (PREFIX form is also calledPOLISH NOTATION, after polish mathematician Jan Lukasiewicz, who proposed it, POSTFIX
form is the INVERSE POLISH NOTATION).
INFIX FORM: (operand1)(operand2).
PREFIX FORM: (operand1)(operand2).
POSTFIX FORM: (operand1)(operand2).
Example1: a+b*c-d
PREFIX FORM: -+a*bcd
POSTFIX FORM: abc*+d-
If (a+b) * c - d
PREFIX FORM: -*+abcd
POSTFIX FORM: ab+c*d-
Example2: a-b/c*e+d-f
PREFIX FORM: -+-a*/bcedf
POSTFIX FORM: abc/*e-d+f-
Stack is becoming an underlying structure for performing calculations based on POSTFIX andPREFIX notation of the expression. The advantages of the two forms are obvious:
1. These forms are PARENTHESES FREE.2. Scanning of the expression is done only once (from left to right) and the final result is
automatically known when scanning is finished.
Example3: Suppose we want to evaluate the expression a+b*c-d, when a = 2, b = 3, c = 4, d = 5.
Convert the INFIX form to postfix form.
abc*+d- (Scanning this order 234*+5-)
operation * should be performed and it requires two operands which are popped from thestack(4 and 3), then do the corresponding operation then include the result on the stackagain.
The second operation is +, which requires two operands as well, so element 12 and 2 arepopped (2+12=14) and result is pushed onto the stack.
59
-
8/6/2019 C & DS Notes
60/83
The third operation is - (14-5=9), operation is performed and result is pushed onto the stack.
Note: While popping elements from the stack and performing required operations, don't forget thatoperators - and / are not commutative. It is important to keep in mind and control the order of theirusage in sub expressions.
Stack structure is also used for conversion of expression written in the INFIX form to itsPOSTFIX notation. While processing your program, a system (compiler) will do such conversionautomatically and stack is becoming the underlying structure for doing this work. When theconversion is performed, its result (POSTFIX expression) is used for calculation of theexpression's value and again stack is used here.
The process of conversion (INFIX to POSTFIX) requires a certain rules to follow:
1. While scanning the INFIX expression from left to right operands are not pushed onto thestack, instead they go directly to output stream. (screen of monitor).
2. The opening parenthesis "(" automatically is pushed onto the stack, and when a
corresponding closing parenthesis reached all characters which precede the openingparenthesis in the stack are popped (they go sequentially to the output stream) and bothparenthesis " ( ", " ) " are destroyed (ignored), they stay in memory.
Example4: Suppose the following expression: (a+b)*c-d; for simplicity of processing lets assumethat a character is used to indicate a beginning or the end of the expression, so expression abovewill look like ( a + b ) * c - d
We scan our expression from left to right
INPUT STACK OUTPUT
(
a
+
b
)
*
c
-
d
(
(
+ (
+ (
*
*
- *
- *
a
b
c
d
-
*
60
-
8/6/2019 C & DS Notes
61/83
Reading the output from top to bottom we get a POSTFIX form which looks as: ab+cd-*; whichcorresponds to the INFIX expression (a+b)*(c-d), and it is not the same as the original INFIXexpression. why?
While performing PUSH/POP operations on stack we have also to control a number of operands,which are used in corresponding operations (all discussed operations are binary operations ). Each
operation (+, *, /) has two operands.
QUEUES:
A queue is a linear collection of elements of the same type. A queue has a front and rear. The newelements can be added to the queue only at one end, which is rear of the queue and the deletion ofelements is possible also at one end, which is the front of the queue. It is possible to implement
queue as a linear linked list.
Three basic operations are applied to queue structure:
1. DELETION: delete(q), delete (remove) the element which currently at the front position ina queue.
2. INSERTION: insert(q,x), insert a new element at the rear of queue.3. EMPTY: empty(q), checks whether the queue is empty or not.
The situation UNDERFLOW is trying to delete an element while queue is empty, has to bechecked using function EMPTY.
The situation OVERFLOW is trying to insert an element while queue is full, it is checked usingfunction insert(q,x).
Operation insert(q,x) looks as follows:
STEP1: [overflow?] if rear >= n then give an error message and exit (n is max number of element).
STEP2: [prepare a new position for inserted element] rear = rear + 1. STEP3: [insertion] set q[rear] = x STEP4: [before insertion was done, queue was empty: rear = 0 and front = 0] if front == 0
then front = 1 and exit.
Operation delete(q) can be represented in a similar way:
STEP1: [underflow?] if front == 0 then display error message and exit. STEP2: [deletion] x = q[rear], where variable x is temporary location in which the value to
be deleted is stored in it. STEP3: [there was one element in the queue] if front == rear then front = rear = 0 STEP4: [incrimination] front = front + 1( the next, second element in the queue becomes
the new front element). As we can notice performing of insert / delete operation specifiedabove has an obvious shortage
61
-
8/6/2019 C & DS Notes
62/83
20
2030
2030 40
5060
30 40 50 60 40 50 60
Queue :
Front Rear Front Rear
Queue created with size 5 Inserted one element(Queue is empty, (queue having 1 element,
Front=0 Rear=0) Front=0 Rear=1)
Front Rear Front Rear
Inserted one element Inserted 3 elements(Queue having 2 elements, (Queue is full (5 elements),Front=0 Rear=2) Front=0 Rear=5)
62
-
8/6/2019 C & DS Notes
63/83
Front Rear Front Rear
Deleted one element Deleted one element(Queue having 4 elements, (Queue having 3 elements,Front=1 Rear=5) Front=2 Rear=5)
Front Rear
Deleted three Elements Queue is deleted(Queue is empty,Front=5 Rear=5)
Circular Queue :
Front Front 10Rear
RearCircular Queue created with size 7 One element is inserted into Circular Queue(Queue is empty, Front = Rear=0) (Queue having one element rear= (rear+1)
%7)
60 50
70 40
Front 10 20 Rear Rear 10 20 30Front
Inserted one element (Queue having 2 elements) Inserted 5 elements (Queue is full)
rear= (rear+1)%7 (7 elements) (rear= front)
63
-
8/6/2019 C & DS Notes
64/83
60 50 60 50
70 40 70 40
Rear 20 30 Rear 30 Front
Front
Deleted one element from the queue Deleted one element from the queue(Queue having 6 elements) (Queue having 5 elements)
FrontRear
Deleted 5 elements from the queue Queue is deleted(Queue is empty, Front = Rear)
QUIZ QUESTIONS
(UNIT-VI)
1)What are basic operations of stack?2)what is the time complexity of algorithm represented in which notation?
3)what are applications of stacks?4)what is the function used to release dynamically allocated memory?5)which operator has highest precedence in notation conversions?6)from infix to prefix a+(b+c(*cd)+e)+f/g7)which is non premitive linear structure?8)in empty queue what