Est 102 Computer Programming in c
Est 102 Computer Programming in c
COURSE MATERIAL
• To become an ultimate destination for acquiring latest and advanced knowledge in the
multidisciplinary domains.
• To provide high quality education in engineering and technology through innovative
teaching-learning practices, research and consultancy, embedded with professional
ethics.
• To promote intellectual curiosity and thirst for acquiring knowledge through outcome
based education.
• To have partnership with industry and reputed institutions to enhance the employability
skills of the students and pedagogical pursuits.
• To leverage technologies to solve the real life societal problems through community
services.
ABOUT THE DEPARTMENT
DEPARTMENT VISION
To produce competent professionals with research and innovative skills, by providing them with
the most conducive environment for quality academic and research oriented undergraduate
education along with moral values committed to build a vibrant nation.
DEPARTMENT MISSION
Course Outcomes: After the completion of the course the student will be able to
Develop readable* C programs with branching and looping statements, which uses
CO 2
Arithmetic, Logical, Relational or Bitwise operators.
Write readable C programs with arrays, structure or union for storing the data to be
CO 3
processed
Divide a given computational problem into a number of modules and develop a readable
CO 4 multi-function C program by using recursion if required, to find the solution to the
computational problem
CO 5 Write readable C programs which use pointers for array processing and parameter passing
CO 6 Develop readable C programs with files for reading input and storing output
readable* - readability of a program means the following:
1. Logic used is easy to follow
2. Standards to be followed for indentation and formatting
3. Meaningful names are given to variables
4. Concise comments are provided wherever needed
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
CO1
CO2
CO3
CO4
CO5
CO6
Assessment Pattern
Remember 15 10 25
Understand 10 15 25
Apply 20 20 40
Analyse 5 5 10
Evaluate
Create
Mark distribution
Marks Marks
Attendance : 10 marks
Continuous Assessment Test 2 (for lab, internal examination, for 2 hrs) : 20 marks
Internal Examination Pattern: There will be two parts; Part A and Part B. Part A contains 5 questions
with 2 questions from each module (2.5 modules x 2 = 5), having 3 marks for each question. Students
should answer all questions. Part B also contains 5 questions with 2 questions from each module (2.5
modules x 2 = 5), of which a student should answer any one. The questions should not have sub-
divisions and each one carries 7 marks.
End Semester Examination Pattern: There will be two parts; Part A and Part B. Part A contains 10
questions with 2 questions from each module, having 3 marks for each question. Students should
answer all questions. Part B contains 2 questions from each module of which a student should answer
any one. Each question can have maximum 2 sub-divisions and carry 14 marks.
Course Outcome 1 (CO1): Write an algorithm to check whether largest of 3 natural numbers is prime or
not. Also, draw a flowchart for solving the same problem.
Course Outcome 2 (CO2): Write an easy to read C program to process a set of n natural numbers and to
find the largest even number and smallest odd number from the given set of numbers. The program
should not use division and modulus operators.
Course Outcome 3(CO3):Write an easy to read C program to process the marks obtained by n students
of a class and prepare their rank list based on the sum of the marks obtained. There are 3 subjects for
which examinations are conducted and the third subject is an elective where a student is allowed to
take any one of the two courses offered.
Course Outcome 4 (CO4): Write an easy to read C program to find the value of a mathematical function
f which is defined as follows. f(n) = n! / (sum of factors of n), if n is not prime and f(n) = n! / (sum of
digits of n), if n is prime.
Course Outcome 5 (CO5): Write an easy to read C program to sort a set of n integers and to find the
number of unique numbers and the number of repeated numbers in the given set of numbers. Use a
function which takes an integer array of n elements, sorts the array using the Bubble Sorting Technique
and returns the number of unique numbers and the number of repeated numbers in the given array.
Course Outcome 6 (CO6): Write an easy to read C program to process a text file and to print the
Palindrome words into an output file.
QP CODE: PAGES:3
Reg No:
Name :
APJ ABDUL KALAM TECHNOLOGICAL UNIVERSITY FIRST SEMESTER B.TECH DEGREE EXAMINATION,
MONTH & YEAR
PART A
11. (a) Draw a flow chart to find the position of an element in a given sequence, using linear
searching technique. With an example explain how the flowchart finds the position of a
given element. (10)
(b) Write a pseudo code representing the flowchart for linear searching. (4)
OR
12. (a) With the help of a flow chart, explain the bubble sort operation. Illustrate with an
example. (10)
(b) Write an algorithm representing the flowchart for bubble sort. (4)
13. (a) Write a C program to read an English Alphabet through keyboard and display whether
the given Alphabet is in upper case or lower case. (6)
(b) Explain how one can use the builtin function in C, scanfto read values of different data
types. Also explain using examples how one can use the builtin function in C, printffor text
formatting. (8)
OR
15. (a) Write a function in C which takes a 2-Dimensional array storing a matrix of numbers and
the order of the matrix (number of rows and columns) as arguments and displays the sum
of the elements stored in each row. (6 )
(b) Write a C program to check whether a given matrix is a diagonal matrix. (8)
OR
16. (a) Without using any builtin string processing function like strlen, strcat etc., write a
program to concatenate two strings. (8)
(b) Write a C program to perform bubble sort. (6)
17. (a) Write a function namely myFact in C to find the factorial of a given number. Also, write
another function in C namelynCr which accepts two positive integer parameters n and r and
returns the value of the mathematical functionC(n,r)( n! / ( r! x (n - r)!) ). The function nCr is
expected to make use of the factorial function myFact. (10)
(b) What is recursion? Give an example. (4)
OR
18. (a) With a suitable example, explain the differences between a structure and a union in C.
(6)
(b) Declare a structure namely Student to store the details (roll number, name, mark_for_C)
of a student. Then, write a program in C to find the average mark obtained by the students
in a class for the subject Programming in C (using the field mark_for_C). Use array of
structures to store the required data (8)
19. (a) With a suitable example, explain the concept of pass by reference. (6)
(b) With a suitable example, explain how pointers can help in changing the content of a
single dimensionally array passed as an argument to a function in C.
(8)
OR
20. (a) Differentiate between sequential files and random access files? (4)
(b) Using the prototypes explain the functionality provided by the following functions. (10)
rewind()
i. fseek()
ii. ftell()
iii. fread()
SYLLABUS
Programming in C (Common to all disciplines)
Module 1
Basics of Computer Hardware and Software
Basics of Computer Architecture: processor, Memory, Input& Output devices
Application Software & System software: Compilers, interpreters, High level and low level languages
Introduction to structured approach to programming, Flow chart Algorithms, Pseudo code (bubble
sort, linear search - algorithms and pseudocode)
Module 2
Program Basics
Basic structure of C program: Character set, Tokens, Identifiers in C, Variables and Data Types ,
Constants, Console IO Operations, printf and scanf
Operators and Expressions: Expressions and Arithmetic Operators, Relational and Logical Operators,
Conditional operator, size of operator, Assignment operators and Bitwise Operators. Operators
Precedence
Control Flow Statements: If Statement, Switch Statement, Unconditional Branching using goto
statement, While Loop, Do While Loop, For Loop, Break and Continue statements.(Simple programs
covering control flow)
Module 3
Arrays and strings
Arrays Declaration and Initialization, 1-Dimensional Array, 2-Dimensional Array
String processing: In built String handling functions (strlen, strcpy, strcat and strcmp, puts, gets)
Linear search program, bubble sort program, simple programs covering arrays and strings
Module 4
Working with functions
Introduction to modular programming, writing functions, formal parameters, actual parameters
Pass by Value, Recursion, Arrays as Function Parameters structure, union, Storage Classes, Scope
and life time of variables, simple programs using functions
Module 5
Pointers and Files
Basics of Pointer: declaring pointers, accessing data though pointers, NULL pointer,array access
using pointers, pass by reference effect
File Operations: open, close, read, write, append
Sequential access and random access to files: In built file handlingfunctions (rewind() ,fseek(), ftell(),
feof(), fread(), fwrite()), simple programs covering pointers and files.
Text Books
1. Schaum Series, Gottfried B.S.,Tata McGraw Hill,Programming with C
2. E. Balagurusamy, Mcgraw Hill,Programming in ANSI C
3. Asok N Kamthane, Pearson,Programming in C
4. Anita Goel, Pearson, Computer Fundamentals
Reference Books
1. Anita Goel and Ajay Mittal, Pearson, Computer fundamentals and Programming in C
2. Brian W. Kernighan and Dennis M. Ritchie, Pearson, C Programming Language
3. Rajaraman V, PHI, Computer Basics and Programming in C
4. Yashavant P, Kanetkar, BPB Publications, Let us C
1.1 Basics of Computer Architecture: Processor, Memory, Input& Output devices 2 hours
Linear search program, bubble sort program, simple programs covering arrays
3.3 3 hours
and strings
4.3 structure, union, Storage Classes,Scope and life time of variables, simple 3 hours
programs using functions
5.1 Basics of Pointer: declaring pointers, accessing data though pointers, NULL 3 hours
pointer,array access using pointers, pass by reference effect
The mark obtained out of 50 will be converted into equivalent proportion out of 20 for CIE
computation.
LIST OF LAB EXPERIMENTS
1. Familiarization of Hardware Components of a Computer
2. Familiarization of Linux environment – How to do Programming in C with Linux
3. Familiarization of console I/O and operators in C
i) Display “Hello World”
ii) Read two numbers, add them and display theirsum
iii) Read the radius of a circle, calculate its area and display it
iv) Evaluate the arithmetic expression ((a -b / c * d + e) * (f +g)) and display its solution.Read
the values of the variables from the user through console.
BASICS OF COMPUTER
HARDWARE &
SOFTWARE
BASICS OF
COMPUTER
ARCHITECTURE
■ Computer is an electronic machine that makes
performing any task very easy
■ In computer, CPU executes each instruction provided toit, in
a series of steps, this series of steps is called Machine Cycle,
and is repeated for each instruction
■ One machine cycle involves
• Fetching of instruction
• Decoding the instruction
• Operand fetching
• Executing the instruction
BASICS OF
COMPUTER
ARCHITECTURE
■ Computer system has five basic units that help
computer to perform operations, which are given
below:
1. Input Unit
2. Output Unit
3. Storage Unit
4. Arithmetic Logic Unit
5. Control Unit
Basic Units of Computer System
Input Unit
■ Input unit connects external environment with
internal computer system
■ It provides data and instructions to computer
system
■ Commonly used input devices are keyboard,
mouse, magnetic tape etc.
■ Input unit performs following tasks:
• Accept data and instructions from outside
environment
• Convert it into machine language
• Supply the converted data to computer system
Output Unit
■ It connects internal system of a computer toexternal
environment
■ It provides results of any computation, or
instructions to outside world
■ Some output devices are printers, monitor etc.
Storage Unit
■ This unit holds data and instructions
■ It also stores intermediate results before theseare
sent to output devices
■ It also stores data for later use
■ Storage unit of a computer system can be dividedinto
two categories:
1. Primary Storage
2. Secondary Storage
Primary Storage
■ Primary memory is computer memory that is accessed
directly by CPU
■ RAM and ROM is used as primary storage memory
■ RAM(Random Access Memory) memory is used to store
data which is being currently executed
■ It is used for temporary storage of data and data is lost,
when computer is switched off
■ ROM(Read Only Memory) Stores crucial information
essential to operate system, like program essential to boot
computer
■ ROM Always retains its data
Secondary Storage
■ Every computer also has storage device that’sused
for storing information on a long-term basis, and is
known as secondary storage
■ Any file you create or download is saved to
computer’s secondary storage
■ There are two types of storage device used as
secondary storage in computers:
1. HDD (Hard Disk Drive)
❑ Sequence Statements
❑ Iteration Statements
■ Step-6 Stop
Algorithm & Flowchart to find Area
and Perimeter of Circle
Algorithm
Step-1 Start
Step-2 Input Radius of Circle say R
Step-3 AREA= 3.142*R*R
Step-4 CIRCUM= 2*3.142*R
Step-5 Display AREA,
CIRCUMStep-6 Stop
Flowchart for Arithmetic Operation
Flowchart to find
Largest of two numbers
Flowchart to find
Largest of three numbers
Flowchart to check whether a
number is odd or even
PSEUDO CODE
■ It's simply an implementation of an algorithm in form
of annotations and informative text written in plain
English
■ It has no syntax like any of programminglanguage
and thus can't be compiled or interpreted by computer
■ It's the cooked up representation of an algorithm
■ Pseudo code, as name suggests, is a false code or a
representation of code which can be understood by
person with some school level programming knowledge
Advantages of Pseudo code
■ Improves readability of any approach. It's one of best
approaches to start implementation of analgorithm
■ Acts as a bridge between program and algorithm or
flowchart
■ Also works as a rough documentation, so program of
one developer can be understood easily when a pseudo
code is written out
■ Easier bug(error) detection and fixing
Advantages of Pseudo code
■ In industries, approach of documentation is essential.
And that's where a pseudo-code proves vital
■ Main goal of a pseudo code is to explain what exactly
each line of a program should do, hence making code
construction phase easier for programmer
Disadvantages of Pseudo code
BASICS OF C PROGRAMMING
C PROGRAM
□ Set of instructions that are provided to computer is
known as a program and development of program is
known as programming
□ Programming is a problem-solving activity
□ C was evolved from ALGOL, BCPL (Basic Combined
Programming Language) and B by Dennis Ritchie
□ C is structured, high level, machine independent
language
□ C is a very powerful and widely used language
□ It forms (or is basis for) core of modern languagesJava
and C++
STRUCTURE OF A C PROGRAM
STRUCTURE OF A C PROGRAM
□ Documentation section consists of a set of commentlines
giving name of program, author and otherdetails
□ Single line comment is represented using //
□ Multiple line comment is represented using
/*……………….*/
□ Comment lines are not executable statements and
therefore anything between/*and*/ is ignored by
compiler
□ Link section provides instruction to the compiler to link
functions from system library
STRUCTURE OF A C PROGRAM
□ Definition section defines all symbolic constants
□ There are some variables used in more than one function.
Such variables are called global variables and are
declared in global declaration section that isoutside of all
functions. This section also declares all user defined
functions
□ Every C program must have one main() function section
□ This section contains two parts, declaration part and
executable part
STRUCTURE OF A C PROGRAM
□ C permits different forms of main statements. Theyare
❑ main ( )
❑ int main ( )
❑ void main ( )
❑ main (void)
❑ void main (void)
❑ int main (void)
□ Declaration part declares all variables used in
executable part
□ There is at least one statement in executable part
STRUCTURE OF A C PROGRAM
□ These two parts must appear between opening and
closing braces
□ Program execution begins at opening brace andends at
closing brace
□ Closing brace of main function section is logical endof
program
□ All statements in declaration and executable partsend
with a semicolon(;)
□ Subprogram section contains all user defined
functions that are called in main function
□ All sections, except main function section may be
absent when they are not required
C Program to print Hello World
//This program prints Hello World
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
/*printf() function displays content that is
passed between double quotes*/ printf("Hello
World");
getch();
}
C PROGRAM TOKENS
■ Smallest individual unit in a program is known as
tokens. C has following tokens
❑ Keywords
❑ Identifiers
❑ Constants (literals)
❑ Strings
❑ Special Characters
❑ Operators
Keywords
■ These are words whose meaning has already been
explained to C compiler
■ Keywords cannot be used as variable names
■ Also known as “Reserved words”
■ There are only 32 keywords in C
■ Examples:
Identifiers
■ These are user-defined names
■ C identifiers represent name in C program, for
example, variables, functions, arrays, structures, unions,
labels, etc
■ An identifier can be composed of letters such as
uppercase, lowercase letters, underscore, digits, but the
starting letter should be either an alphabet or an
underscore
Rules for constructing C identifiers
□ The first character of an identifier should be either analphabet or
an underscore, and then it can be followed by any of the
character, digit, or underscore(_)
□ It should not begin with any numerical digit
□ In identifiers, both uppercase and lowercase letters are distinct.
Therefore, we can say that identifiers are case sensitive
□ Commas or blank spaces cannot be specified within an identifier
□ Keywords cannot be represented as an identifier
□ Length of identifiers should not be more than 31 characters
□ Identifiers should be written in such a way that it is
meaningful, short, and easy to read
Identifiers Example
□ Example of valid identifiers
❑ Total
❑ Sum
❑ Average
❑ _m _
❑ sum_1
□ Example of invalid identifiers
❑ 2sum (starts with a numerical digit)
❑ int (reserved word)
❑ char (reserved word)
❑ m+n (special character, i.e., '+')
Constants
□ These are data items that never change their valueduring
a program run. These are fixed values
□ They are also called literals
□ Types of Constants are
a) Integer constant: These are whole numbers without any
fractional part. It must have at least one digit and must not
contain any decimal point. It can be either positive ornegative
Examples are 426,+200,-760
b) Character constant: A character constant is one character
enclosed in single quotes. Examples are „A‟, ‟5‟ ,‟=‟ . A
character constant have corresponding ASCII values. For
example ASCII value of „A‟ is 65 and ASCII value of „a‟ is97
Constants
c) String constant: Multiple character constants are treated as
string constant
❑ A string constant is a sequence of characters surrounded by
double quotes
❑ Examples are “abcd”, ”seena”
❑ Each string constant is by default (automatically) added
with a special character ‟\0‟ which makes end of a string
❑ Thus size of a string is Number of characters + null character
(„\0‟)
❑ For example “abc” size is 4. Thus “abc” will be
automatically represented as “abc\0” in memory.‟\0‟ is an
end-of-string marker
Constants
d) Floating constant: Floating constants are also called real
constants. These numbers have fractional part. It mayalso
have either positive or negative. Examples are 17.8,
-13.867
Special Characters
□ Following special symbols are used in C having some special
meaning and thus, cannot be used for some other purpose
[] () {} , ; : * … = #
□ Brackets []: These opening and closing brackets are used as array
element reference
□ Braces {}: Opening and closing curly braces are used to mark start
and end of a block of code containing more than one statement
□ Comma ( , ): To separate more than one statement
□ Semicolon ( ; ): Used at end of statements for termination
Special Characters
□ Parenthesis () : Are used to indicate function parameters&
function calls
□ Asterick ( * ): This special symbol is used to create a
pointer variable
□ Assignment Operator ( = ): For assigning values, this
special symbol is used
□ Preprocessor ( # ): This you must have seen attachedwith the
header files
Operators
□ An operator is a symbol that tells computer to perform
certain mathematical or logicalmanipulations
□ Operators are used in programs to manipulatedata and
variables
□ An expression is a sequence of operands and operators
that reduces to a single value
Operators
■ C operators are
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment and decrement operators
6. Conditional operators
7. Bitwise operators
8. Special operators
ARITHMETIC OPERATORS
□ C provides all basic arithmetic operators
Prefix Postfix
++m; m++;
--m; m--;
++m; is equivalent to m = m+1;
▪ --m; is equivalent to m = m–1
▪ We use increment and decrement statements infor
and while loops extensively
INCREMENT(++) AND
DECREMENT(--)
OPERATORS
□ m = 5;
y = ++m;
In this case, value of y and m would be 6
□ Suppose, if we rewrite above statements asm =
5;
y = m++;
then, value of y would be 5 and m would be 6
□ Prefix operator first adds result to operand and thenresult
is assigned to variable on left
□ Postfix operator first assign value to variable on leftand
then increments operand
CONDITIONAL OPERATOR
■ It is a ternary operator (3 operands)
■ Conditional expression is of form
exp1 ? exp2 : exp3
where exp1, exp2, and exp3 are expressions
■ exp1 is evaluated first
■ If it is true, then exp2 is evaluated and becomevalue
of expression
■ If exp1 is false, exp3 is evaluated and its value
become value of expression
CONDITIONAL OPERATOR
□ For example, consider following statementsa =
10;
b = 15;
x = (a > b) ? a : b;
□ In this example, x will be assigned value of b ie, 15
□ This can be achieved using the if..else statementsif (a
> b)
x = a;
else
x = b;
BITWISE OPERATORS
□ Bitwise operators are used for manipulation ofdata at
bit level
□ These operators are used for testing bits, orshifting
them right or left
BITWISE OPERATORS
■ Syntax is:
char string_name[size];
Eg: char city [10];
char name[30];
CHARACTER ARRAYS & STRINGS
■ When compiler assigns a character string to a character
array, it automatically supplies a null character (\0) at
end of string
■ Therefore size of a string
Size = maximum number of characters in string + one
■ Character arrays can be initialized when they are
declared
CHARACTER ARRAYS & STRINGS
■ Initialization can be in either of following two
forms
char city [9] =”NEW YORK”;
char city[9]={„N‟,‟E‟,‟W‟,‟ ‟,‟Y‟,‟O‟,‟R‟,‟K‟,‟\0‟};
■ Following format is also valid in C
■ char string[ ]= {„N‟,‟E‟,‟W‟,‟ ‟,‟Y‟,‟O‟,‟R‟,‟K‟,‟\0‟};
READING STRING FROM KEY BOARD
1. Using scanf( ) function
char address[10]; scanf
(“%s”,address);
■ In case of character arrays, ampersand (&) is not
required before variable name
■ Problem with scanf ( ) function is that it terminatesits
input on the first white space it finds
■ If we typed NEW YORK then only string “NEW” will be
read in to array address. Address array is created in
memory as shown below
READING STRING FROM KEY BOARD
■ Unused locations are filled with garbage value
■ If we want the entire line “NEW YORK”, we use
two character arrays of size
char ad1[5],ad2[5];
scanf (“%s%s”,ad1,ad2);
■ • Then assign the string “NEW” to ad1 and“YORK”
to ad2.
■ scanf ( ) is not capable of receiving multi-word
strings
READING STRING FROM KEY BOARD
■ Way to avoid this limitation is by using function
gets ( )
■ It does not skip white space
■ Usage of functions gets( ) and its counterpartputs( ) is
shown below
STRING HANDLING FUNCTIONS
■ String conversion functions are stored in header file
<string.h>
1. strlen - Finds length of a string
2. strlwr - Converts a string to lowercase
3. strupr - Converts a string to uppercase
4. strcat - Appends one string at the end of another
5. strcpy - Copies a string into another
6. strcmp - Compares two strings
7. strdup - Duplicates a string
8. strrev - Reverses string
strlen ( )
■ This function counts number of characters presentin a
string
Output
string = Newyear length = 7
string = Humpty Dumpty length = 13
strcpy( )
■ This function copies contents of one string into
another
Output
source string = Soniya
target string = Soniya
strcat( )
■ This function concatenates source string at end oftarget
string
Output
source string = Brother target
string = HelloBrother
strcmp( )
■ This function compares two strings to find out whether
they are same or different
■ Two strings are compared character by character until
there is a mismatch or end of one of strings is reached,
whichever occurs first
■ If two strings are identical, strcmp( ) returns a value
zero
■ If they‟re not, it returns numeric difference between
ASCII values of first non-matching pairsof characters
strcmp( )
□ In first call two strings are
identical “Jerry” and “Jerry”
and value returned bystrcmp
( ) is zero
□ In second call, result is 4,
which is numeric difference
between ASCII value of „J‟
and ASCII value of „F‟
□ In third call, result is -4, which
is numeric difference between
Output
ASCII value of „F‟ and ASCII
value of „J‟
0 4 -4
<ctype.h>
□ Character function use ctype.h header file. It is used for
character testing and conversion functions
• isalpha (c): Determine if argument is alphabetic. It
return non zero value if true, 0 otherwise. Return type
is int
• isdigit (c): Determine if argument is a decimal digit. It
return non zero value if true, 0 otherwise. Return
type is int
• islower (c): Determine if argument is lower case. It
return non zero value if true, 0 otherwise. Return type
is int
<ctype.h>
• isupper (c): Determine if argument is upper case. It
return non zero value if true, 0 otherwise.Return type is
int
• tolower (c): Convert letter to lower case. Return type is
int
• toupper (c): Convert letter to upper case. Return type is
int
Example to print length of a string using
strlen() library function and gets
Example to print length of a string
using gets( ) and null character
TWO DIMENSIONAL ARRAYS
□ Two-dimensional array is also called a matrix
□ Two dimensional arrays are declared as followstype
array_name [row-size] [column-size];
□ Example:
OR
int stud[4][2] = { 1334, 18, 1812, 44, 1004, 99, 1112, 10 } ;
TWO DIMENSIONAL ARRAYS
□ It is important to remember that while initializing a 2-D
array it is necessary to mention second (column)
dimension, whereas first dimension (row) is optional
□ Thus declarations,
int arr[2][3] = { 52, 30, 23, 55, 56, 85 } ;
int arr[ ][3] = { 52, 30, 23, 55, 56, 85 } ;
are perfectly acceptable
□ Whereas,
int arr[2][ ] = { 52, 30, 23, 55, 56, 85 } ;
int arr[ ][ ] = { 52, 30, 23, 55, 56, 85 } ;
would never work
Memory Map of a 2-Dimensional
Array
□ Array elements have been stored row wise and
accessed row wise
□ We can access array elements column wise as well
□ Traditionally, array elements are being stored and
accessed row wise
Memory Map of a 2-Dimensional
Array
□ Array arrangement shown below is only conceptually
true
□ This is because memory doesn‟t contain rows and
columns
□ In memory whether it is a one-dimensional or a two-
dimensional array, elements are stored in one
continuous chain
□ Arrangement of array elements of a two- dimensional
array in memory is shown in figure
MODULE 4
Function Declarations
■ void add(int,int);
■ int add (int,float);
■ float add(float,float);
■ void add ();
Example for Function without argument
and return value
Example for Function without argument and
with return value
Example for Function with argument and
without return value
Example for Function with argument and
with return value
PASS BY VALUE ( CALL BY VALUE )
□ In this method ‘value’ of each of actual arguments
(arguments in function call statement) in calling
function is copied into corresponding formalarguments
(arguments in function definition section) of called
function
□ Function creates its own copy of argument values and
then uses them
□ With this method changes made to the formalarguments
in called function have no effect on values of actual
arguments in calling function
□ That is, any change in formal parameter is not reflected
back to actual parameters
PASS BY VALUE ( CALL BY VALUE )
EXAMPLE
□ Factorial of a number is product of all integers between 1and
that number
□ For example, 4 factorial is 4 * 3 * 2 * 1
2. Register
3. Static
4. External
Automatic Storage Class
□ A variable declared inside a function by default,
automatic
□ They are created when function is called anddestroyed
automatically when function is exited
□ We can write explicitly as auto int number;
Static Storage Class
□ Static variable initialized once when program is
compiled
□ Value of static variable cannot change
static int x;
AUTO & STATIC – A COMPARISON
External Storage Class
□ External variable’s scope is global, not local
□ External variables are declared outside all functions,
yet are available to all functions that care to use
them
□ We can write explicitly as extern int y;
External Storage Class
External Storage Class
Register Storage Class
□ We can tell compiler that a variable should be kept in one
of machine’s registers, instead of keeping inmemory
□ Register access is faster than memory access
is same as
Structure Initialization
□ Like variables and arrays, structure variables canalso
be initialized where they are declared
□ Closing brace in structure type declaration mustbe
followed by a semicolon
ACCESSING STRUCTURE
ELEMENTS
□ In arrays we can access individual elements of an array
using a subscript. Structures use a different scheme
□ They use a dot (.) operator
□ So to refer to pages of structure defined in sample
program we have to use,
b1.pages
□ Similarly, to refer to price we would use,
b1.price
□ Note that before dot there must always be a structure
variable and after dot there must always be a structure
element
ASSIGNING VALUES TO
STRUCTUREELEMENTS
ARRAY OF STRUCTURES
□ Array of structures: an array of structure data typeswhich
themselves are a collection of dissimilar data types
ARRAY OF STRUCTURES
STRUCTURE ASSIGNMENT
□ Values of a structure variable can be assigned to
another structure variable of same type using
assignment operator
□ It is not necessary to copy structure elementspiece-meal
□ Obviously, programmers prefer assignment to piece-
meal copying
□ This is shown in following example
STRUCTURE ASSIGNMENT
PASSING STRUCTURE TO A
FUNCTION
UNION
■ Syntax is same as structures
■ In structure each member has its own storage location,
whereas all members of a union use samelocation
■ It can handle only one member at a time
■ Union may be used in all places where a structureis
allowed
■ To access a union member, we can use samesyntax that
we use for structure members
■ That is,
code.m code.x code.c all are valid
UNION
□ Compiler allocates a piece of storage that is large
enough to hold largest variable type in union
□ In below declaration, member x requires 4 byte
memory
□ So only 4 byte memory is allocated
END….
MODULE 5
*p1, **p2 ;
□ Here, x is an ordinary int, p1 is a pointer to an int (often
called an integer pointer), whereas p2 is a pointer to an
integer pointer
□ Representation **p2 is called multiple indirection
POINTER TO A POINTER (Chain
of Pointers)
POINTER INCREMENTS & SCALE
FACTOR
□ Expression p1++; will cause pointer p1 to point tonext
value of its type
□ If p1 is an integer pointer with an initial value say 2800,
then after operation p1=p1+1, value of p1 will be 2802,
and not 2801
□ When we increment a pointer its value is incremented
by length of the data type that its point to. This length
called scale factor
□ Following operations can be performed on a pointer:
POINTER INCREMENTS & SCALE
FACTOR
□ Addition of a number to a pointer
int i = 4, *j, *k ; j
= &i;
j = j + 1; j
= j + 9;k =
j + 3;
□ Subtraction of a number from a pointer
int i = 4, *j, *k ;j
= &i;
j = j - 2;
j = j - 5;
k = j - 6;
Subtraction of one pointer from
another
OUTPUT
8 36
Comparison of two pointer
variables
OUTPUT
The two pointers point to the same location
Comparison of two pointer
variables
□ Do not attempt following operations on
pointers... they would never work out
(a) Addition of two pointers
(b) Multiplication of a pointer with a constant
(c) Division of a pointer with a constant
POINTER & ARRAY
□ Array name gives address of first element of array
POINTER & ARRAY
POINTER & ARRAY
□ Suppose we have an array
num [ ] = {24, 34, 12, 44, 56, 17}
POINTER & ARRAY
PASS BY REFERENCE (CALL BY
REFERENCE)
□ In this method addresses of actual arguments in calling
function are copied into formal arguments of calledfunction
□ That is same variables value can be accessed by any of two
names: original variables name and reference name
□ We are actually passes address
□ Note that this program manages to exchange values ofa and
b using their addresses stored in x and y
□ That is, any change in formal parameter is reflectedback
to actual parameters
□ Usually in C programming we make a call by value
PASS BY REFERENCE (CALL BY
REFERENCE)
NULL POINTER
□ It is always a good practice to assign a null value to a
pointer variable in case you do not have exactaddress to
be assigned
□ This is done at time of variable declaration
□ A pointer that is assigned NULL is called a null pointer
□ Null pointer is a constant with a value of zero defined
in several standard libraries
NULL POINTER
FILE MANAGEMENT
□ A file represents a sequence of bytes on diskwhere a
group of related data is stored
□ File is created for permanent storage of data
□ It is a readymade structure
□ A file is a place on disk where a group of relateddata
is stored
FILE OPERATIONS
1. Creation of a new file
2. Writing to a file
3. Opening an existing file
4. Reading from a file
5. Moving to a specific location in a file (seeking)
6. Closing a file
FUNCTIONS FOR FILE HANDLING
General format for declaring and
opening a file
FILE *fp;
fp=fopen (“filename”,”mode”);
Output :
7
END…..