Problem Solving and C Programming - Handout - v2 (1) .1
Problem Solving and C Programming - Handout - v2 (1) .1
and C Programming
Version: PSC/Handout/0307/2.1
Date: 05-03-07
Cognizant
500 Glen Pointe Center West
Teaneck, NJ 07666
Ph: 201-801-0233
www.cognizant.com
Problem Solving and C Programming
TABLE OF CONTENTS
Introduction ................................................................................................................................6
About this Document..................................................................................................................6
Target Audience.........................................................................................................................6
Objectives ..................................................................................................................................6
Pre-requisite ..............................................................................................................................6
Page 2
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Session 8: Pointers....................................................................................................................62
Learning Objectives .................................................................................................................62
Introduction ..............................................................................................................................62
Declaration and Initialization ....................................................................................................62
Pointer Arithmetic.....................................................................................................................64
Pointers and Arrays .................................................................................................................65
Dynamic Memory Allocation.....................................................................................................71
Summary .................................................................................................................................73
Test your Understanding..........................................................................................................73
Page 3
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Page 4
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Summary ...............................................................................................................................123
Test your Understanding........................................................................................................123
Syntax Summary......................................................................................................................125
References ...............................................................................................................................138
Websites ................................................................................................................................138
Books.....................................................................................................................................138
Page 5
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Introduction
Target Audience
In-Campus Trainees
Objectives
Explain the concepts of problem solving
Explain the concepts of C programming language
Write effective programs using C programming language
Pre-requisite
This module does not require any pre-requisites
Page 6
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Learning Objectives
After completing this chapter, you will be able to:
Explain the basic concepts of problem solving
List the steps involved in program development
List the advantages of top-down programming
Describe programming languages, their types, and features
A problem can be solved successfully only after making an effort to understand the problem. To
understand the problem, the following questions help:
What do we know about the problem?
What is the information that we have to process in order the find the solution?
What does the solution look like?
What sort of special cases exist?
How can we recognize that we have found the solution?
It is important to see if there are any similarities between the current problem and other problems
that have already been solved. We have to be sure that the past experience does not hinder us in
developing new methodology or technique for solving a problem. The important aspect to be
considered in problem-solving is the ability to view a problem from a variety of angles.
There is no universal method for solving a given problem. Different strategies appear to be good
for different problems. Some of the well known strategies are:
Divide and Conquer
Greedy Method
Dynamic Programming
Backtracking
Branch and Bound
Page 7
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Page 8
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Design
A design is the path from the problem to a solution in code. Program Design is both a product and
a process. The process results in a theoretical framework for describing the effects and
consequences of a program as they are related to its development and implementation.
Modular Design
Once the problem is defined clearly, several design methodologies can be applied. An important
approach is Top-Down programming design. It is a structured design technique which breaks up
the problem into a set of sub-problems called Modules and creates a hierarchical structure of
modules.
While applying top-down design to a given problem, consider the following guidelines:
A problem is divided it into smaller logical sub-problems, called Modules
Each module should be independent and should have a single task to do
Each module can have only one entry point and one exit point, so that the logic flow of
the program is easy to follow
When the program is executed, it must be able to move from one module to the next in
sequence, until the last module is executed
Each module should be of manageable size, in order to make the design and testing
easier
Page 9
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Developing Algorithms
Algorithm development process is a trial-and-error process. Programmers make initial attempt to
the solution and review it, to test its correctness. The errors identified leads to insertions, deletions,
or modifications to the existing algorithm.
This refining continues until the programmer is satisfied that, the algorithm is essentially correct
and ready to be executed. The more experience we gain in developing an algorithm, the closer our
first attempt will be to a correct solution and the less revision will be required. However, a novice
programmer should not view developing algorithm as a single-step operation.
Pseudo Code
Pseudo code is an informal high-level description of an algorithm that uses the structural
conventions of programming languages, but omits language-specific syntax. It is an outline of a
program written in English or the user's natural language.
Step 4: IF n = 0 then
Page 10
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Flowchart
Flowchart is a diagrammatic representation of an algorithm. It uses different symbols to represent
the sequence of operations, required to solve a problem. It serves as a blueprint or a logical
diagram of the solution to a problem. Typical flowchart symbols are given below:
Represents off page connector which are used to indicate that the flow chart
continues on another page. Page numbers are usually placed inside for easy
reference.
Connector Symbol represents the exit to, or entry from, another part of the
same flow chart. It is usually used to break a flow line that will be continued
elsewhere.
The Document Symbol is used to represent any type of hard copy input or
output (i.e. reports).
Page 11
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
START
Read n
True
If n=0 0 Print 1
False
False
If i<=n
True
fact = fact * i
i=i+1
Print fact
STOP
Page 12
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Coding
An algorithm expressed in programming languages is called Program. Writing a program is called
Coding. The logic that has been developed in the algorithm is used to write the program.
During execution, the executable object code is loaded into the computer’s memory and the
program instructions are executed.
Testing
Testing is the process of executing a program with the deliberate intent of finding errors. Testing is
needed to check whether the expected output matches the actual output. Program should be
tested with all possible input data and control conditions.
Testing is done during every phase of program development. Initially, requirements can be tested
for its correctness. Then, the design (algorithm, flow charts) can be tested for its exactness and
efficiency. Structured walk through is made to verify the design.
Programs are tested with several test criteria and the important ones are given below:
Test whether each and every statement in the program is executed at least once
(Basic path testing)
Test whether every branch in the program is traversed at least once (control flow)
Test whether the input data flows through the program and is converted to an output
(data flow)
The probability of discovering errors through testing can be increased by selecting significant test
cases. It is important to design test cases for abnormal input conditions.
Page 13
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
An algorithm should work correctly and produce meaningful results for any data. This is called
foolproof programming.
Debugging
Debugging is a process of correcting the errors. Programs may have logical errors which cannot
be caught during compilation. Debugging is the process of identifying their root causes. One of the
ways to ensure the correctness of the program is by printing out the intermediate results at
strategic points of computation.
Some programmers use the terms “testing” and “debugging” interchangeably, but careful
programmers distinguish between the two activities. Testing means detecting errors. Debugging
means diagnosing and correcting the root causes.
On some projects, debugging occupies as much as 50 percent of the total development time. For
many programmers, debugging is the hardest part of programming because of improper
documentation.
Maintenance
Programs require a continuing process of maintenance and modification to keep pace with
changing requirements and implementation technologies. Maintainability and modifiability are
essential characteristics of every program. Maintainability of the program is achieved by:
Modularizing it
Providing proper documentation for it
Following standards and conventions (naming conventions, using symbolic constants
etc)
A programming language can be defined as a vocabulary and set of grammatical rules for
instructing the computer to perform specific tasks. Each programming language has a unique set
of characters, keywords and the syntax for organizing programming instructions.
The term programming languages usually refers to high-level languages, such as BASIC, C, C++,
COBOL, FORTRAN, Ada, and Pascal.
Page 14
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Advantage
The program runs faster because no translation is needed. (It is already in machine
understandable form)
Disadvantages
It is very difficult to write programs in machine language. The programmer has to know
details of hardware to write program
It is difficult to debug the program
(b) Assembly Language
In assembly language, set of mnemonics (symbolic keywords) are used to represent machine
codes. Mnemonics are usually combination of words like ADD, SUB and LOAD etc. In order to
execute the programs written in assembly language, a translator program is required to translate it
Page 15
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
to the machine language. This translator program is called Assembler. Assembly language is
considered to be the second-generation language.
Advantages:
The symbolic keywords are easier to code and saves time and effort
It is easier to correct errors and modify programming instructions
Assembly Language has utmost the same efficiency of execution as the machine level
language, because there is one-to-one translation between assembly language
program and its corresponding machine language program
Disadvantages:
Assembly languages are machine dependent. A program written for one computer
might not run in other computer.
Compiler is a translator program which converts a program in high level language in to machine
language.
Higher level languages are problem-oriented languages because the instructions are suitable for
solving a particular problem.
For example, COBOL (Common Business Oriented Language) is mostly suitable for business
oriented applications. There are some numerical & mathematical oriented languages like
FORTRAN (Formula Translation) and BASIC (Beginners All-purpose Symbolic Instruction Code).
Numerical Languages
Early computer technology dates from the era just before World War 2 in the late 1930s to the
early 1940s. These early machines were designed to solve numerical problems and were thought
of as ELECTRONIC CALCULATORS. Numerical calculations were the dominant form of
application for these early machines.
Page 16
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Business Languages
Business data processing was an early application domain developed after numerical applications.
In 1959, the US department of Defense sponsored a meeting to develop COMMON BUSINESS
LANGUAGE (CBL), which would be a business-oriented language that used English as much as
possible for its notation. This, in turn, led to the formation of a Short Range Committee to develop
COBOL.
Systems Languages
Because of the need of efficiency, the use of assembly language held on for years in the system
area long after other application domains started to use higher-level languages. Many systems
programming languages such as CPL & BCPL were designed, though not widely used. The major
landmark here is the development of UNIX, where high level languages also proceed to work
effectively.
For example, FORTRAN is a particularly good language for processing numerical data, but it does
not lend itself very well to organize large programs. PASCAL is very good for writing well-
structured and readable programs, but it is not as flexible as the C programming language. C++
embodies powerful object-oriented features, but it is complex and difficult to learn. The choice of
which language to use depends on the type of computer used, type of program, and the expertise
of the programmer.
Following are the most important features that would make a programming language efficient and
easy to use:
Clarity, Simplicity and Unity: A programming Language provides, both a conceptual framework
for thinking about algorithms and a means for expressing these algorithms. The syntax of a
language should be such that programs may be written, tested and maintained with ease.
Orthogonality: This refers to the attribute of being able to combine various features of a language
in all possible combinations, with every combination being meaningful. Orthogonality makes a
language easy to learn and write programs, because there are fewer exceptions & special cases to
remember.
Naturalness for the application: A language needs syntax that when properly used allows the
program structure to reflect the underlying logical structure of the algorithm. The language should
provide appropriate data structures, operations, control structures and natural syntax for the
problem to be solved.
Page 17
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Support for abstraction: Even with the most natural programming language for an application,
there is always a substantial gap remaining between the abstract data structures & operations that
characterize the solution to a problem and the particular data structures and operations built into a
language.
Portability of Programs: Portability is an important criterion for many programming projects which
essentially indicates the transportability of the resulting programs from the computer on which they
are developed to other computer systems. A language whose definition is independent of the
features of a particular machine forms a useful base for the production of transportable programs.
Target Environments
Target environments can be classified into 3 categories – Batch Processing Environment,
Interactive Environment, and Embedded System Environment. Each poses different requirement
on languages adapted for those environments.
Batch-Processing Environments
In batch-processing environments, the input data are collected in ‘batches’ on files and are
processed in batches by the program. For example, the backup process on an organization. The
transaction details of all the departments are collected for backup at one place and the backup is
done at a time at the end of the day.
Page 18
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Interactive Environments
In interactive environment, a program interacts directly with a user at a display console, by
alternately sending output to the display & receiving input from the keyboard or mouse. Examples
include database management systems, word processing systems etc.
Summary
Program development life cycle involves analysis, algorithm development, coding,
documenting, compiling and running, testing, debugging, and maintenance.
Top-down program design, divides the problem into smaller logical sub problems,
called Modules.
An algorithm is a sequence of unambiguous instructions for solving a problem.
A programming language is a vocabulary and set of grammatical rules for instructing a
computer to perform specific tasks.
Two major types of programming languages are Low Level Languages and High Level
Languages.
The environment under which a program is designed, coded, tested & debugged is
called Host environment (programming environment)
The environment under which a program is executed is called Target environment.
Target environments can be classified into 3 categories.
o Batch processing environment
o Interactive environment
o Embedded System environment
2. Give the algorithm, pseudo code and flowchart for the following problem:
Sort a list of numbers in ascending order.
Page 19
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Answers:
3. Testing is to find errors in programs and debugging is to correct their root causes
4. True, True
Page 20
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Learning Objectives
After completing this chapter, you will be able to:
Explain the evolution of C language
List the features of C language
Explain the basic elements of C language
Explain the structure of a C program
Introduction to C Language
C is a general purpose high level programming language. Because of its flexibility and efficiency it
is widely used for software development. Its features allow the development of well-structured
programs. The data types and control structures are directly supported by most computers,
resulting in the construction of efficient programs.
Evolution of C Language
ALGOL was the first computer language to use a block structure. In 1967, Martin Richards
developed a language called BCPL (Basic Combined Programming Language) primarily, for
writing system software. In 1970, Ken Thompson created a language using many features of
BCPL and called it ‘B’. ‘B’ was used to create early versions of UNIX operating system at Bell
Laboratories. Both BCPL and B were “typeless” system programming languages.
C was developed by Dennis Ritchie at Bell Laboratories in 1972. It was evolved from ALGOL,
BCPL, and B. C uses many concepts of these languages and new features like data types. UNIX
operating system was coded almost entirely in C.
During 1970s, C had evolved into what is now known as “traditional C”. The popularity of C led to
the development of different versions of the language that were similar but often incompatible.
To assure that the C language remains standard, in 1973, American National Standards Institute
(ANSI) appointed a technical committee to define a standard for C. The committee approved a
version of C in 1989 which is now known as ANSI C. It was then approved by the International
standards Organization (ISO) in 1990. The standard was updated in 1999.
Page 21
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Page 22
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Characteristics of C Language
The increasing popularity of C is due to its various desirable qualities:
C language is well suited for structured modular programming
C is a robust language with rich set of built-in functions and operators
C is smaller which has minimal instruction set and programs written in C are efficient
and fast
C is highly portable (code written in one machine can be moved to other)
C is highly flexible
C allows access to the machine at bit level (Low level (Bitwise) programming)
C supports pointer implementation - extensive use of pointers for memory, array,
structures and functions
Structure of a C Program
A C program can be viewed as a group of building blocks, called functions. A function is a
subroutine that includes one or more statements designed to perform a specific task.
preprocessor directives
global declaration section
main()
{
:
}
user-defined function definitions;
The preprocessor directives provide instructions to the preprocessor, to include functions from the
system library, to define the symbolic constants and macro. The prototype of the user-defined
functions (function declaration) is specified after the preprocessor directives. The variables that are
used in common by more than one function are called Global Variables and are declared in global
declaration section. This section can have declarations for all the user-defined functions.
Every C program must have one main() function. This function contains two parts: declaration part
and executable part. The declaration part declares all the variables used in the executable part.
These two parts must appear between the opening and the closing braces. The program execution
begins at the opening brace and ends at the closing braces. The closing brace of the main function
is the logical end of the program. The executable portion of the main function will have three types
of statements: Input, Output and Processing statements. All the statements in the declaration and
executable parts end with a semicolon.
C program can have any number of user-defined functions and they are generally placed
immediately after the main() function, although they may appear in any order.
All sections except the main() function may be absent when they are not required. C is a case
sensitive language. Comments are enclosed within /* and */. C program can be documented using
these comment lines.
Page 23
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Example 2.1
/* Program to accept 2 integers from the keyboard as input, calculate
and print their sum */
#include <stdio.h>
main( )
{
int num1,num2,sum;
printf (“\n Program to find the sum of two numbers\n”);
printf(“\n Please enter 2 integer numbers”);
scanf(“%d%d”, &num1,&num2);
sum = num1+num2;
printf (“\n The following data was input: %d & %d ”, num1, num2);
printf(“\n The sum of two numbers is = %d”, sum);
}
C Compilation Model
The C Compilation model describes the program development process in terms of language. The
key features of the C compilation model are as follows:
The Preprocessor
The preprocessor accepts source code as input and interprets preprocessor directives denoted
by #. It removes comments and empty lines in the program.
Page 24
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Example 2.2
#include -- includes contents of a named file. These files are usually called header files.
#include <math.h> -- standard library maths file.
#include <stdio.h> -- standard library I/O file
#define -- defines a symbolic name or constant, macro definition
#define MAX_ARRAY_SIZE 100
C Compiler
The C compiler translates the preprocessed code (user written program) to assembly code
(machine understandable code).
Assembler
The assembler creates the object code. [On UNIX, file with a.o suffix and on MSDOS files with
.OBJ indicates object code files.]
Link Editor
If a source file references library functions or functions defined in other source files, the link editor
combines these functions with main(), to create an executable file. External variable references are
resolved here.
C Fundamentals
Basic elements of C language constitute Character set, Identifiers, Operators and Expression.
Character Set
Character set defines the characters that are used to form words, numbers and expressions. The
characters in C are grouped into the following categories:
Letters
o Uppercase A….Z
o Lowercase a….z
Digits
o All decimal digits 0…9
Special characters
o =, +, - , % , ? , Blank spaces etc.
Escape Sequences: Escape sequences are non printable characters, which begin
with backward slash and followed by one or more special characters. The frequently
used escape sequences are given below:
o Horizontal tab ( \t )
o Vertical tab ( \v )
o Carriage return (\r )
o New line ( \n )
o Form feed (\f )
o Back Space ( \b )
o Back Slash ( \\ )
o Null ( \0 )
Page 25
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Keywords
Keywords have standard, predefined meanings in C. These keywords can be used only for their
intended purpose and they cannot be used as programmer-defined identifiers. Keywords serve as
basic building blocks for program statements. All keywords must be written in lowercase. ANSI C
supports 32 keywords. The following table shows the list of keywords.
do if static While
Identifiers
Identifiers are names given to various programming elements such as variables, constants, and
functions. It should start with an alphabet, followed by the combinations of alphabets and digits. No
special character is allowed except underscore (_). An Identifier can be of arbitrarily long. Some
implementation of C recognizes only the first eight characters and some other recognize first 32
characters.
Example 2.3
Valid identifiers : sum_2_nos basic_pay _amount
Invalid identifiers: 5subjects emp name #ofstudents
Data Types
Data types are used to indicate the type of value represented or stored in a variable, the number of
bytes to be reserved in memory, the range of values that can be represented in memory, and the
type of operation that can be performed on a particular data item.
Page 26
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
The basic data types can be augmented by the use of data type qualifiers.
Type Qualifiers
Data type qualifiers add additional information to the data types. They are,
short
long
signed
unsigned
A number of qualifiers or modifiers may be assigned to any basic data type to vary the number of
bits utilized and the range of values represented by that data type.
Here, short int may require less space than an int or it may require the same amount of memory.
Similarly, a long int may require the same amount of memory as an int or it may require more
memory, never less than int.
Unsigned character
unsigned char 8 bits 0 to 255
(positive)
signed char
Represents single character. 8 bits -128 to 127
char
Short
signed short represents both positive and
16 bits -32,768 to 32,767
short int negative integer quantity
signed short int
Page 27
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
long
signed long Represents both positive
32 bits -2,147,483,648 to 2,147,483,647
long int and negative long integer
signed long int
long double Increases the size of double. 80 bits 3.4 * (10-4932) to 1.1 * (104932)
Variables
A variable is an identifier that represents a value. The value represented by the identifier may be
changed during the execution of the program. Variable names must be chosen in such a way that
it should be a valid identifier satisfying all the basic conditions.
Variable names are case sensitive (ex: variable EMPNAME is different from variable empname).
The variable name can be chosen by the programmer in a meaningful way so as to reflect its
function or nature in the program.
Declaration of a variable
Declaration is used to specify the variable names used in the program and the type of data that the
variable can hold.
Page 28
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
General form:
var_data_type list variables;
Example 2.4
int i, j, k;
float x, y, z;
char ch;
Initialization
Variables can be initialized in the declaration statement itself or within the program using
assignment statement.
General Form:
[data type] variable name = value;
Example 2.5
int total=0, ct=1;
float sum = 0.0;
int tot, ct=1;
tot = 0;
Constants
A constant in C refers to the fixed values that do not change during the execution of a program.
Symbolic Constants
A symbolic constant is defined in the preprocessor area of the program and is valid throughout the
program. The preprocessor directive #define is used to define symbolic constants in a program.
Symbolic constants are usually represented in upper case letters.
Each reference to ‘MAX’ in program will cause the value of 100 to be substituted. This value
cannot be changed by the program.
Page 29
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Constant Variables
A constant variable is declared and initialized in the variable declaration section of the program
and cannot be modified thereafter. The type of value stored in the constant must be specified in
the declaration. Keyword ‘const’ is used to declare constant variables.
Example 2.6
const int size = 100;
const float pi=3.14;
const char ch = ‘a’;
const long a = 50000L; or const long a = 50000l;
const int a = 0567; (Octal representation – prefix 0)
const int a = 0Xa92 (Hexadecimal representation – prefix 0x or 0X)
Operators
C supports a rich set of operators. An operator is a symbol that tells the computer to perform
mathematical or logical operations. Operators are used in programs to manipulate data. C
operators can be classified into a number of categories. They include:
Arithmetic operators
+ Addition
- Subtraction
* Multiplication
/ Division (second operand must be nonzero)
% Modulus (both operands must be integer and second operand must be non zero)
Relational operators
Logical operators
&& Logical AND (true only if both the operands are true)
|| Logical OR (true if either one operand is true)
! Logical NOT (negate the operand)
Expressions which use logical operators are evaluated to either true or false.
Page 30
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Assignment operators
= Assignment operator which assign a value to an identifier.
+=, *=, -=, /=. %= Compound assignment operators are used whenever, left hand side identifier is
used in the right hand side expression. (a = a+b equals to a+=b)
Unary operators
+ Unary plus
- Unary minus
Example:
int i=5;
printf(“%d”, ++i); /*prints 6 - pre increment */
printf(“%d”, i++); /* prints 6 - post increment */
printf(“%d”, i); /* prints 7 */
-- may be in the form of pre decrement or post decrement (-- k: pre increment, k--: post
increment)
In the above statement, if condition is evaluated to true, the value of variable a will be assigned to
variable big else b will be assigned.
Bitwise operators
& Bit wise AND
| Bit wise OR
<< Left shift
>> Right shift
Special operators
& Address operator
* Indirection operator
comma Comma operator
sizeof() Size of operator (sizeof(int) = 2 bytes)
Page 31
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Order of Precedence
All the operators have its own precedence and associativity. High priority operators are evaluated
prior to lower priority ones. Operators of the same priority group are evaluated from left to right
fashion. The expression a + b – c is evaluated as (a + b) – c.
From high priority to low priority the order for all C operators is given below:
! – sizeof()
Logical NOT, unary minus, indirection, address Right to Left
(Typecast) * &
Expressions
Expression is a combination of operands, operators, function calls that evaluates to a value. The
three types of expressions are Arithmetic expression (uses arithmetic operators), Relational
expression (uses relational operators), and Logical expression (uses logical operators).
Page 32
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Assignment Statement
Assignment statement is used to assign a value to a variable. In C, the assignment operator is “=”.
The left side of the “=” is always a variable, whose address specifies where to store the data on
the right side.
For example, the statement x = y + z; computes the value of y+z and store the result in the
variable x. However, x + 3 = y; is not legal because x + 3 is an arithmetic expression (i.e.) not a
storage location.
For example:
a = b = c = d = 3;
...which is the same as, but more efficient than:
a = 3;
b = 3;
c = 3;
d = 3;
Example 2.8
(1) a = (b = 2, c=3, b+c); 5
(2) a = (b=2, c=3, b+c, b-c); -1
(3) int a; float b;
a=b=3.5; a= 3 b=3.5
(4) int c, a=3, b=4;
c= a>b; c=0
d = a == b; d=0
e = a != b; e=1
Type Casting
C provides a mechanism for allowing the programmer to change the default data type of a given
expression. This is called Typecasting. Typecasting allows a variable to behave like a variable of
another type.
C provides two types of type conversions: Implicit and Explicit type conversions.
In implicit type conversion, if the operands of an expression are of different types, the lower data
type is automatically converted to the higher data type before the operation evaluation. The result
of the expression will be of higher data type. The final result of an expression is converted to the
type of the variable on the LHS of the assignment statement, before assigning the value to it.
For example,
float to int assignment causes truncation of the fractional part.
double to float causes round of digits.
long int to int causes dropping of the excess higher order bits.
Page 33
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
In explicit type conversion, the user has to enforce the compiler to convert one data type to
another data type by using typecasting operator. This method of typecasting is done by prefixing
the variable name with the data type enclosed within parenthesis. The original value of the variable
is not altered.
General Form:
(data type)variable/expression/value;
Narrowing: Converting the higher data type value to lower data type value.
Widening: Converting the lower data type value to higher data type value.
Example 2.9
float sum;
sum = (int) (1.5 * 3.8);
The typecast (int) tells the C compiler to interpret the result of (1.5 * 3.8) as the integer 5, instead
of 5.7. Then, 5.0 will be stored in sum, because the variable sum is of type float.
Example 2.10
float to (int or char) - narrowing
(char or int) to float - widening
Example 2.11
int a, b, c, d, e, f;
float x, y, z;
a=14; b=4;
c = a/b; /*c=3 */
d = a % b; /*d=2 */
x = a / 10.0; /*x=1.4 (Mixed-mode expression)*/
y = a / 10; /*y=1.0 */
e = -a % -b;
/*-2 (Modulus operation retains the sign of the first operand)*/
f = a % -b; /*f=2*/
Page 34
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Example 2.12
a b c
int a=0, b=0, c=0; 0 0 0
a=++b + ++c; 2 1 1
a=b++ + c++; 2 2 2
a=++b + c++; 5 3 3
a=b-- + --c; 5 2 2
c = a>b; 5 2 1 (Relational expression evaluated to true)
c = a && b 5 2 1 (Logical expression evaluated to true.
Non zero value is true and Zero is false)
There are two types of Input and Output (I/O) statements: Unformatted I/O statements and
Formatted I/O statements.
Character Input
There are several functions available to input a character from the console.
getchar ()
This function accepts a single character from the stream stdin (keyboard buffer). This single
character includes alphabets, digits, punctuations, return, and tab.
General form:
char-variable = getchar();
Example 2.13
char ch;
ch = getchar();
getch (); - character input from console & doesn’t echo the character.
Page 35
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
String Input
gets ()
This function accepts a string terminated by a new line character. Blank space is also considered
as a character. To get a line of text, this function serves the purpose.
General Form:
Example 2.14
char ch[5];
gets(ch);
Character Output
putchar()
This function displays a single character in the standard output (stdout), monitor.
General Form:
putchar(char variable);
Example 2.15
char ch;
ch = getchar();
putchar(ch);
String Output
puts()
This function displays the string in the standard output.
General Form:
puts(str);
Example 2.16
char ch[5];
gets(ch);
puts(ch);
Page 36
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
“%-+s0w.pmc”
Where:
- left justify
+ print with sign
s print space with no sign
0 pad with leading zero
w field width
p precision
m conversion character ( h, l, L)
c conversion character (d, f, u, o, x, g, e)
scanf()
scanf () function is used to read formatted data items.
General Form:
scanf (“format string”, list of variables);
Format string specifies the field format in which the data is to be entered.
List of variables specify the address of memory locations where the data is to be stored. Address
operator (&) is used before the variables.
Format string and variables are separated by comma. Format string, also known as control string
contains field specifications, which directs the interpretation of input data. By default, the delimiter
while reading the values is space. Delimiter can be user-defined. To read a string using ‘%s’, ‘&’
need not be used.
Page 37
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Example 2.17
scanf (“%c %d %f”, &ch, &i, &x);
scanf (“%[^\n]s”, str);
/*accepts all inputs including space. Stops when it encounters new
line.*/
scanf (“%d=%d”, &a, &b);
/*delimiter between two input is = (10=20)*/
scanf (“%2d%5d”,&a,&b);
/*if the input is 12345 & 10, a=12 & b=345 if the input is 12 & 3456,
a= 12 & b=3456*/
scanf (“%d%d”, &a,&b);
/*if the input is 12345 & 10, a=12345 & b=10*/
sscanf()
sscanf() function to read values from a string. This functions returns the number of inputs read
successfully.
General Form:
sscanf (str, “format string”, list of variables);
printf()
printf () function is used to output the values. This function returns the number of characters
printed.
General Form:
printf (“format string”, list of variables);
Example 2.18
printf (“char=%c, int=%3d, floating point=%6.2f”,ch, i, x);
printf (“sum = %*.*f”, w, p, sum);
/* width & precision can be user defined*/
printf (“name = %10.4s”, name);
/* column width 10, first 4 characters printed.*/
sprintf()
sprintf() function is used to output values to a string.
General Form:
sprintf (str, “format string”, list of variables);
Page 38
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Summary
C is a structured programming language.
C program is a collection of functions.
C supports four basic primitive data types: int, char, float, double.
C has a rich set of operators.
C has Unformatted and Formatted Input / Output statements.
3. What will be the value of the variables x and s after the following piece of code is
executed?
float x, s, y=7.5;
x= (int) y;
s= (int) y + 3.5;
Page 39
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Answers:
1. a,c ( “ “ , - are not the valid characters to form an identifier)
2. valid
3. x = 7.0 , s = 10.5
4. ?: is called ternary operator (conditional operator) used to carry out simple decision
making.
5. getche() echoes the input character on screen, but getch() will not echo the character.
7. welcome7
Page 40
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Learning Objectives
After completing this chapter, you will be able to:
Apply selection statements in your programs
Apply control structures in your programs
Statements in C
Example 4. 1
a=8;
c=a+b;
; Null statement
Example 4. 2
{ { {
a=10; a=1;
b=10; x=a*b; {
c=a + b; y = x * b – k; b=2; c=3;
} } }
}
Sequence
A program, which consists of declaration statements, input-output statements, and one or more
simple expression statements, is executed in a sequential manner.
Page 41
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Selection Statements
Selection statements are used to alter the normal sequential flow of control. It provides the ability
to decide the order of execution. The following are the selection constructs available in C:
“ if ” statement
Conditional / Ternary operator statement (? :)
“switch” statement
‘if’ Statement
The if statement, allows us to establish decision-making in the programs. Programs may require
certain logical tests to be carried out at some particular points. The tests and subsequent decisions
are made by evaluating a given expression as either True (non zero) or False (zero). An
expression involves arithmetic, relational, and/or logical operators. Depending on the result of the
expression the statements are executed.
Simple “if-else”
General Form:
if (expression)
{
statements1;
}
[ else
{
statements2;
} ]
statements3;
Expression can be arithmetic, logical, and/or relational expression. If the expression is evaluated to
true (nonzero), the statements1 are executed and the control is transferred to the statements
(statements3) next to the if construct is executed. If the expression is evaluated to false (zero), the
statements1 will be skipped and the else part statements (statements2) are executed. If the else
part is not specified, the statements (statements3) next to the if construct is executed.
Page 42
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Short-circuit Evaluation
Whenever the expression with the operators && and || are evaluated, the evaluation process stops
as soon as the outcome, true or false is known. For example:
expr1 && expr2
If the value of expr1 is zero, the evaluation of expr2 will not occur [ 0 AND anything is 0]
expr1 || expr2
If expr1 has non-zero value, the evaluation of expr2 will not occur [ 1 OR anything is 1]
General Form:
if (expression)
{
statements1;
if (expression)
statements-1;
}
else
{
statements2;
if (expression)
statements-2;
}
Example 4.4
Program to find the maximum of 3 numbers.
if (a>b)
if (a>c)
printf(“largest = %d”, a);
else
printf (“largest = %d”,c);
else
if (c>b)
printf (“largest = %d”,c);
else
printf (“largest = %d”,b);
Page 43
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
General Form:
if (expression)
statements1;
else if (expression)
statements2;
else if(expression)
statements3;
else
statements4;
Each condition is evaluated in order and if any condition is true the corresponding statement is
executed and the remainder of the chain is skipped. The final ‘else’ statement is executed only if
none of the previous conditions are satisfied. Final ‘else’ serves as a default case and is useful in
detecting an impossible or error condition.
Example 4.5
if (mark >= 75)
printf(“Honours\n”);
else if (mark >=60)
printf(“First Class\n”);
else if (mark >=50)
printf(“Second Class\n”);
else if (mark >=45)
printf(“Third Class\n”);
else
printf(“Fail\n”);
General form:
[variable = ]expr1? expr2: expr3;
Where:
expr2 is evaluated, if the value of expr1 is non-zero (true part).
expr3 is evaluated, if the value of expr1 is zero (false part).
Page 44
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Example 4.6
max = (a>b) ? a : b;
which is similar to the following if-else statement.
if (a>b)
max = a;
else
max = b;
Switch Statement
This is a conditional control statement that allows some particular group of statements to be
chosen from several available groups. It is a multi-way conditional statement generalizing the ‘if-
else’ statement. A switch statement allows a single variable to be compared with several possible
case labels, which are represented by constant values. If the variable matches with one of the
constants, then an execution jump is made to that point. A case label can not appear more than
once and there can only be one default expression.
General Form:
switch (expression)
{
case item1: statement 1;
break;
case item2: statement 2;
break;
case itemn: statement n;
break;
default : statement;
}
Expression in the switch statement, must be an integer valued expression. Expression may be a
constant value, variable, array variable, pointer variable, relational expression, logical expression,
and/or arithmetic expression. Items which represent the case labels must be an integer constant or
character constant. Default case is optional and if specified, default statements will be executed, if
there is no match for the case labels.
The break is needed to terminate the switch after the execution of particular choice. Otherwise the
next cases get evaluated.
Page 45
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Example 4.7
switch (op)
{
case ‘+’:
c=a+b;
break;
case ‘-’:
c=a-b;
break;
case ‘*’:
c=a*b;
break;
case ‘/’:
c=a/b;
break;
default:
printf (“Invalid operator”);
}
Iteration Statements
Most of the real world applications require some set of instructions to perform repetitive actions on
a stream of data. There are several ways to execute loops in C. The statements used for looping
are: ‘for’, ‘while’, ‘do- while’.
‘for’ statements
This statement is used to repeat a statement or a set of statements for a specified number of times
or until a condition satisfied.
General Form:
for (expression1; expression2; expression3)
{
statement / block of statements;
}
Where:
expression1 initializes the counter/index variable. The initialization is usually an
assignment statement that is used to set the index variable or loop control variable.
expression2 is to set a terminating condition. It is evaluated at the beginning of every
iteration. If the test condition is True, the statements inside the loop are executed. If the
test condition is False, the control is transferred to the statement, which follows the
loop.
expression3 is the loop variant/modifier (increment / decrement), which is evaluated at
the end of every iteration.
Page 46
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Example 4.8
(1) for (x=0; ((x>3) && (x<9)); x++)
(2) for (x=0, y=4; ((x>3) && (y<9)); x++, y+=2)
(3) for (x=0, y=4, z=4000; z ; z/=10)
(4) c=2;
for (;c<=20;c=c+2)
(5) for (c=2;;++c) infinite loop
(6) c=2;
for (;c<=20;)
{
printf (“%d”, c);
c++;
}
(7) int c=0;
for(;;) infinite loop
{
c+=1;
printf (“c=%d”, c);
}
Example 4.9
for (i=1;i<=3;i++)
{
printf(“\n i = %d”,i);
for (j=1;j<=3; j++)
printf (“\n j = %d”,j);
}
In the above example, the loop controlled by the value of ‘i’ is called the outer loop. The second
loop, controlled by the value of ‘j’, is called inner loop. All statements in the inner loop are within
the boundaries of the outer loop. Different variables must be used to control each loop. For each &
every iteration through the outer loop, the inner loop runs completely.
‘while’ statement
The while is an entry controlled loop statement. The conditional expression is evaluated at the
beginning and the result of the expression decides on the execution of the body of loop. If the
result is True, the body of the loop is executed,
Page 47
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
General Form:
while (expression)
{
Statements;
}
Expression can be a constant value, variable or any expression. If the expression evaluates to
True, the body of the loop is executed, otherwise statements after the while block is executed.
After executing the body of the loop, the expression is checked again. The body of the loop is
executed repeatedly until the expression is False. If the expression is initially False, the body of
loop is not executed at all.
The body of the loop may have one or more statements. The braces are needed only if the body
contains two or more statements.
Example 4.10
Different ways to use while loops
(1) while(x--){ };
(2) while(x = x+1){ };
(3) while(x) { };
(4) while(1);
(5) while ( (ch = getche ( )) != ‘q’)
putchar(ch);
(6) c=1;
while (c<=10)
{
printf (“%d”,c);
++c;
}
General Form:
do
statement (s);
while (expression);
On reaching the do statement, the program proceeds to evaluate the body of the loop first. At the
end of the loop, the expression in the while statement is evaluated. If the expression is evaluated
to True, the program continues to evaluate the body of the loop once again. This process
continues as long as the expression evaluates to True. When the condition becomes False, the
loop will be terminated and control is transferred to the next statement following the do..while.
Since the expression is tested at the end of the loop, the body of the loop is executed at least
once.
Page 48
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Example 4.11
int d=1;
do
{
printf (“%d\n”,d);
++d;
} while (d<=10);
Break Statement
The break statement can appear in the switch statement and the loop statements. It causes the
execution of the current enclosing switch case or the loop to terminate.
General Form:
break;
Example 4.12
for(loop=0;loop<50;loop++)
{
If (loop==10)
break; /* control will come out of the loop. */
printf("%d\n",loop);
}
Only numbers 0 through 9 are printed.
Continue Statement
The continue statement can only appear in the loop statements. It is used to terminate the current
iteration. It skips rest of the statements in the body of the loop and begins the next iteration.
General Form:
continue;
Example 4.13
for(loop=0;loop<100;loop++)
{
if (loop==50)
continue;
printf("%d\n",loop);
}
Page 49
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Summary
if statement is a condition based decision making statement.
Ternary operator is more efficient form for expressing simple if statements.
Switch statement is a conditional control statement that allows some particular group of
statements to be chosen from several available groups.
Looping allows a program to repeat a section of code any number of times or until
some condition occurs.
for, while, and do-while statements are repetitive control structures available in C
, that are used to carry out conditional looping.
break statement is used to terminate the loop but continue statement skips the current
iteration and continues the loop with the next iteration.
Page 50
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Answers:
1. c
2. Default case is executed, whenever evaluated expression does not matches with any of the
case labels.
3. 3
4. While is an entry controlled loop (condition is checked in the beginning) and do..while is exit
controlled loop (condition is checked at the end). The loop statements of do..while will get
executed at least once.
5. 01
Page 51
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Learning Objectives
After completing this chapter, you will be able to:
Understand the concept of array and its memory organisation
Know how arrays are declared and initialized in C
Use multi dimensional arrays
Know about various character and string functions
Individual memory location is referred by index. [index 0 refers first location , index 1 refers
second location, etc.]. Address of an array element is calculated as below:
Address of ith location = base address + (size of the individual data element * index i )
Address of 0th element = 1000 + (2 * 0) = 1000
Address of 1st element = 1000 + (2 * 1) = 1002 …
In C, the name of the array refers to the base address of the array.
Page 52
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Array Declaration
Arrays are declared with appropriate data type and size. Arrays can be of single dimension or of
multi dimensions. Array declaration reserves space in memory.
General Form:
datatype arrayname[size] ;
Arrays are defined by appending an integer encapsulated in square brackets at the end of a
variable name. Each additional set of brackets defines an additional dimension to the array (multi
dimensional arrays). When addressing an element in an array, indexing begins at 0 and ends at 1
less than the defined size of an array.
Example 6.1
int x[5];
Defines an integer array x of 5 integers, starting at x[0], and ending at x[4].
char str[16]="qwerty";
Defines a character array, which is represents a string of maximum of 16 characters.
float sales_amt[10];
Defines a floating point array sales_amt of 10 floating point numbers, starting at sales_amt[0] and
ending at sales_amt[9].
int matrix[2][2];
Defines a 2*2 matrix (totally 4 elements) of integers.
General Form:
arrayname[index or subscript]
Example 6.2
x[0] to access the 1st element in array
x[4] to access the 5th element in array
str[2] to access the 3rd character in the string (character array)
sales_amt [8] to access the 9th sales amount in the array
Page 53
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Array Initialization
Array elements can be initialized during declaration or can be initialized in the program. When
arrays are initialized during declaration, partial initialization is allowed. In partial initialization, the
uninitialized array elements are initialized to Zero or Null depending on the data type of the array.
Zero is initialized for numeric array and Null for character array.
If initialized, array can be declared without specifying the exact size. In such cases, size of the
array equals the number of elements initialized.
General Form:
datatype arrayname[size] = {value(s)};
OR
datatype arrayname[ ] = {value(s)};
Example 6.3
int a[5]={1,2,3,4,5};
/*a[0] = 1, a[1] = 2 , a[2] = 3 , a[3] = 4 and a[4] = 5*/
int a[5]={0};
/*all the array elements are initialized to zero*/
int a[5]={1,2,3,4};
/*a[4] = 0*/
int a[ ] = {1,2,3,4};
/*a[0]=1, a[1]=2, a[2]=3, a[3]=4 (if size not specified, size depends
upon the number of values initialized. ) */
float b[2]={10.2,45.34};
/* b[0] = 10.20 , b[1] = 45.34 */
Array name is a constant pointer (pointer is a variable which holds address of another variable) to
the base address of the array. Thus, the base address can not be changed. The following
expressions are illegal:
a++ (base address of array ‘a’ is modified by adding one)
a+=2 (base address of array ‘a’ is modified by adding two)
Page 54
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Example 6.5
int a[3];
(1) scanf(“%d”, &a[0]); /*gets value for 1st location*/
scanf(“%d”, &a[1]); gets value for 2nd location*/
scanf(“%d”, &a[2]); gets value for 3rd location*/
Example 6.6
int a[3];
(1) printf(“%d”, a[0]); /*prints value of 1st location*/
printf(“%d”,a[1]); /*prints value of 2nd location*/
printf(“%d”, a[2]); /*prints value of 3rd location*/
(2) printf(“%d%d%d”,a[0],a[1],a[2]);
/* prints value of first 3 locations*/
(3) for(i=0;i<3;i++)
printf(“%d”,a[i]);
/*loop statement is used to print the array elements */
Multi-dimensional Array
The elements of an array can themselves be arrays. Multidimensional arrays will also occupy the
contiguous memory locations. Two dimensional arrays can be viewed as set of one dimensional
array (rows & columns) and 3 dimensional arrays can be viewed as set of two dimensional arrays.
General Form:
datatype arrayname [row ][column]
Page 55
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Example 6. 7
int a[2][2]; creates 8 bytes of contiguous memory locations. (2*2 = 4 elements).
Elements are stored in row major order. Elements of 1st row are stored first and then the elements
of next row. It is necessary to specify the size of the column in declaration.
Assume that array starts at location 1000,
a[0][0] will be in location 1000 - row 0 & column 0
a[0][1] will be in location 1002 - row 0 & column 1
a[1][0] will be in location 1004 - row 1 & column 0
a[1][1] will be in location 1006 - row 1 & column 1
Example 6.8
int num[2][3] = {1,2,3,4,5,6};
int num[2][3] = {1,2,3,4,5}; /*num[1][2] = 0*/
int num[2][3] = {{1,2,3},{1,2,3}};
/*row elements are initialized separately*/
int num[2][3] = {{1,2},{4}};
/*num[0][2] = 0 num[1][1]=num[1][2]=0*/
Advantages
Simple and easy to use
Stored in Contiguous locations
Fast retrieval because of its indexed nature
No need to worry about the allocation and de-allocation of arrays
Limitations
Conventional arrays are static in nature. Memory is allocated in the beginning of the
execution. If m elements are needed, out of n locations defined, n-m locations are
unnecessarily wasted
No automatic array bounds checking during compilation
Page 56
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Strings
Strings are sequence of characters. In C, there is no built-in data type for strings. String can be
represented as a one-dimensional array of characters. A character string is stored in an array of
character type, one ASCII character per location. String should always have a NULL character
(‘\0’) at the end, to represent the end of string.
String constants can be assigned to character array variables. String constants are always
enclosed within double quotes and character constants are enclosed within single quotes.
Example 6.10
(1) char c[4]={‘s’,’u’,’m’,’\0’);
(2) char str[16]="qwerty"; /*Creates a string. The value at str[5] is
the character ‘y’. The value at str[6] is
the null character. The values from str[7]
to str[15] are undefined.*/
(3) char name[5];
int main( )
{
name[0] = ‘G’;
name[1] = ‘O’;
name[2] = ‘O’;
name[3] = ‘D’;
name[4] = ‘\0’;
return 0;
}
(4) char name[5] = “INDIA” /* Strings are terminated by the null
character, it is preferred to allocate one
extra space to store null terminator */
Array of Strings
Two dimensional character arrays are used to represent array of strings.
Declaration
General Form:
char arrayname [no. of strings] [max no. of chars in strings];
Example 6.11
char studname[50][15];
/* 50 student names each with 15 characters at the maximum */
Page 57
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Initialization
General Form:
char arrayname [ r ] [ c ]={“values”};
Example 6.12
char name[3][5] = {“bata” ,”cat” ,”at”}
char name[3][5] = {{‘b’,’a’,’t’,’a’,’\0’}, {‘c’,’a’,’t’,’\0’},
{‘a’,’t’,’\0’}}
String can be read either character-by-character or as an entire string (using %s format specifier).
Array name itself specifies the base address and %s is a format specifier which will read a string
until a white space character is encountered.
[Note: no need to use & operator while reading string using %s]
Example 6.13
(1) char name[20];
int i=0;
while((name[i] = getchar ()) != ‘\n’ )
i++;
(2) scanf( “%s“ , name);
(3) printf(“%s” , name);
C does not allow one array to be assigned to another, thus statements of the following form are
illegal”
name = “GOOD”; Or name1 = name; assignment not allowed
name1 = name + “to c “ concatenation is not allowed
if (name1 == name) two strings cannot be compared with the ‘equal to’ operator
Page 58
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
String Functions
C does not provide any operator, which manipulates the entire string at once. Strings
are manipulated either via pointers or via special routines available from the standard
string library string.h.
Page 59
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Character Functions
C provides the following collection of character functions, which can manipulate a single character.
The header file, ctype.h, is used for the character functions.
Functions Functionality
int isalnum (c) True if c is alphanumeric.
int isalpha (c) True if c is a letter.
int isascii( c) True if c is ASCII .
int iscntrl (c) True if c is a control character (\n,\f,\r,\a)
int isdigit (c) True if c is a decimal digit
int isgraph (c) True if c is a graphical character (all characters, except space)
int islower (c) True if c is a lowercase letter
int isprint (c) True if c is a printable character (all characters including white space)
int ispunct (c) True if c is a punctuation character (, . ,‘, ‘, “,:,)
int isspace( c) True if c is a space character (\n,\f,\r,\t,\v,’ ‘)
int isupper (c) True if c is an uppercase letter
int isxdigit (c) True if c is a hexadecimal digit
toupper (x) Converts lowercase letter to uppercase
tolower (x) Converts uppercase to lowercase
toascii (x) Converts the char to ASCII value
Summary
An array can be defined as a collection of homogenous elements stored in consecutive
memory locations.
Array name is a constant pointer to the base address of the array.
Conventional array always has a predefined size and the elements of an array are
referenced by means of an index / subscript.
An array can be of more than one dimension. There is no restriction on the number of
dimensions.
String is represented as an array of characters.
C supports a number of in-built string functions to manipulate strings.
Page 60
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
4. When a one dimensional array is being declared, under what condition may the size be
omitted, with array name followed by an empty pair of square brackets?
Answers:
1. No, array can contain only similar data items.
2. Array elements are accessed by relative addressing method (base address + index), in
order to access the first element, which is in base address, index must be 0.
5. 0 0 0
Page 61
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Session 8: Pointers
Learning Objectives
After completing this chapter, you will be able to:
Explain the significance of pointers
Declare pointer
Initialize pointers
Use pointers with arrays
Implement dynamic memory allocation
List the advantages and disadvantages of pointers
Introduction
Pointer is a variable that contain the memory address of another variable. Pointers are one of the
powerful and frequently used features of C, as they have a number of useful applications.
Variables contain the values and pointer variables contain the address of variables that has the
value. Variable directly references the value and Pointer variable indirectly references the value.
Referencing a value through a pointer is called Indirection.
Whenever a variable is declared, memory is allocated for the variable according to the data type
specified.
1000
Page 62
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Declaration
General Form:
data-type *pointer-name;
Example 8.1
int x, *px;
px = &x; x = 5 ;
x px variables
5 1000
values
1000 3000 addresses
Example 8.2
Now execute the following printf statements and observe the results.
printf(“ x = %d “ , x); prints 5
printf(” address of x = %d “ , &x); prints 1000
printf (“ address pointed by pointer = %u”, px); prints 1000
printf (“address of the pointer = %u”, &px); prints 3000
printf (“content pointed by pointer = %d”, *px); prints 5
Initialization
Pointer variables should be initialized to 0, Null or an address. No other constant can be initialized
to a pointer variable. Pointer variable of a particular data type can, hold only the address of the
variable of same data type.
Example 8.3
Valid and Invalid pointer assignments
int a , b , *p = &a , *q = NULL; valid.
q = p; valid - both p and q is pointing to the memory location of variable a
b = &a; invalid – ordinary variables cannot hold address.
q = a; invalid - cannot assign value to the pointer variable
Page 63
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Pointer Arithmetic
Pointer Addition or subtraction is done in accordance with the associated data type.
int adds 2 for every increment
char adds 1 for every increment
float adds 4 for every increment
long int adds 4 for every increment
All the operations can be done on the value pointed by the pointer.
Page 64
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Arrays
Array is used to store the similar data items in contiguous memory locations under single name.
Array addressing is in the form of relative addressing. Compiler treats the subscript as a relative
offset from the beginning of the array. Array subscripting notation is converted to pointer notation
during compilation, so writing array subscripting expressions using pointer notation can save
compile time.
Pointers
Pointer addressing is in the form of absolute addressing. Exact location of the elements can be
accessed directly by assigning the starting location of the array to the pointer variable. The pointer
variable is incremented to find the next element.
C treats the name of the array as if it is a pointer to the first element. Thus, if v is an
array, *pv is the same as v[0], *(pv+1) is the same as v[1], and so on.
Initialization
To initialize a pointer variable, conventional array is declared and pointer variable can be made to
point to the starting location of the array. Array elements are accessed using pointer variable.
General Form:
pointer_variable = &array_name [starting index];
OR
pointer_variable = array_name;
Example 8. 6
int a[5] = {1,2,3, 4,5} , *ptr , i ;
ptr = a ; similar to ptr = &a[0];
Assume that array starts at location 1000
&a[0] = 1000 a[0] = 1 ptr + 0 = 1000 *(ptr+0) = 1
&a[1] = 1002 a[1] = 2 ptr + 1 = 1002 *(ptr+1) = 2
&a[2] = 1004 a[2] = 3 ptr + 2 = 1004 *(ptr+2) = 3
&a[3] = 1006 a[3] = 4 ptr + 3 = 1006 *(ptr+3) = 4
&a[4] = 1008 a[4] = 5 ptr + 4 = 1008 *(ptr+4) = 5
Page 65
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Accessing value
Example 8.7
printf (“%d “,*(ptr+i)); displays the a[i] value
printf (“%d “,*ptr); displays the a[0] value
printf (“%d “,*(a+i)); displays the a[i] value
Accessing address
Example 8.8
printf (“%u “, (ptr+i)); displays address of a(i)
General Form:
ptr_vble = &array_name [starting index1]…[starting indexn];
OR
ptr_vble = array_name;
Example 8.9
int a[2][2] = {1,2,3,4} , *ptr ;
ptr = &a[0][0] ;
Assume that the array starts at location 1000
&a[0][0] = 1000 a[0][0] = 1 ptr+0 = 1000 *(ptr+0) = 1
&a[0][1] = 1002 a[0][1] = 2 ptr+1 = 1002 *(ptr+1) = 2
&a[1][0] = 1004 a[1][0] = 3 ptr+2 = 1004 *(ptr+2) = 3
&a[1][1] = 1006 a[1][1] = 4 ptr+3 = 1006 *(ptr+3) = 4
For example,
(p+0) + 1 if it is used to represent 0th row and 1st column and
(p+1) + 0 if it is used to represent 1st row and 0th column results in p+1.
So, multi dimensional arrays can be represented by pointer in the following two ways:
Pointer to a group of arrays
Array of pointers
Page 66
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
int (*p)[2] p is a pointer points to a set of one dimensional array, each with 2 elements.
Note: First dimension need not be specified but the second dimension has to be specified. Here, a
single pointer is used and it needs to know how many columns are there in a row.
Accessing value
Example 8.10
printf (“%d “,*(*(ptr + i) +j); displays the x(i,j) value
printf (“%d “,*(a[ i ] + j); displays the x(i,j) value
printf (“%d “,*(a + i)[ j ]; displays the x(i,j) value
Example 8.11
main()
{
int i, j;
int a[2][3]={1,2,3,4,5,6};
int *pa=&a[0][0];
for (i=0;i<2;i++)
{
for (j=0;j<3;j++)
printf(“\t%d”,*(*(pa+i)+j));
printf(“\n”);
}
}
Output:
1 2 3
4 5 6
Array of Pointers
Multi dimensional array can also be expressed in terms of an array of pointers.
Here, we have 2 pointers ptr[0], ptr[1] and each pointer can point to a particular row . Thus, only
one indirection is enough to represent a particular element.
Page 67
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Example 8.12
int a[2][2] = {1,2,3,4} , *ptr[2] ;
ptr[0] = a[0]; /* ptr[0] is now pointing to the 0th row ( & a[0][0]) */
ptr[1] = a[1]; /* ptr[1] is now pointing to the 1st row ( & a[1][0]) */
Example 8.13
(1) *p[3] declares p as an array of 3 pointers
(2) (*p)[3] declares p as a pointer to a set of one dimensional array of 3 elements
char *p = NULL;
Once the pointer is declared, the address of the array is assigned to this pointer. When an array is
referenced by its name, it refers to the address of the 0th element.
p = name;
Now issue the following printf statements and check the output:
When a pointer variable is referred with the indirection operator, it refers the content of the address
pointed by the pointer variable. The above printf statements produce the outputs as follows:
Character output = D
String output = Data Structures
The reason for the output produced by the second printf statement is because of the %s format
specifier, which will print the string till it encounters a ‘\0’ character. Pointer automatically gets
incremented to the next location.
Page 68
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Character-type pointer variable can be assigned an entire string as a part of its variable
declaration.
An array of character pointers offers a convenient method for storing strings. Each pointer is used
to represent a particular string.
Ragged Arrays
Consider the following array declaration.
This array occupies 30 bytes and the row length is fixed. Instead of making each row a fixed
number of characters, make it a pointer to a string of varying length.
If the elements of array are string pointers, a set of initial values can be specified as part of the
array declaration.
An advantage is that a fixed block of memory need not be reserved in advance. The above
statement allocates variable length block of memory and occupies only 14 bytes. It declares 4
pointers each pointing to a string. Thus, substantial saving in memory. Arrays of this type are
referred as Ragged arrays (used only in the initialization of string arrays).
Example 8.14
(1) char *ps = “xyz”;
pointer ‘ps’ is stored in 2 bytes and ‘ps’ contains the address of the string that requires 4 bytes.
(2) char s[ ] = “xyz”;
string ‘s’ is stored in 4 bytes.
Page 69
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Pointer to a constant
The address of a constant variable can be assigned to a pointer variable. The following example
explains the pointer variable to a constant variable:
Example 8.15
const int a=10;
int *pa = &a;
/* suspicious pointer conversion. Wise to avoid such assignments */
Variable ‘a’ is a constant variable. The value cannot be modified.
Pointer variable ‘pa’ can take any other address and value of ‘a’ can be changed using pointer
even though it is constant variable.
Constant Pointer
The pointer variable can be a constant. A pointer variable can take the address of a non-constant
data and constant data.
Constant pointer to non-constant data always points to the same memory locations and the data at
that location can be modified through the pointer. Pointers variables that are declared ‘const’ must
be initialized when they are declared.
Example 8.16
int a;
int *const pa = &a;
Constant pointer to constant data always points to the same memory location and the data at that
memory location cannot be modified.
Example 8.17
int b;
const int * const pb = &b;
Example 8.18
int a; float b;
void *pab;
pab=&a;
*(int *) pab =100;
pab=&b;
*(float *) pab = 105.55;
Page 70
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
These functions provides the ability to reserve as much memory as may required during program
execution, and then release this memory when it is no longer required.
Thus, arrays can be represented in terms of pointers and an initial memory location can be
allocated to pointer variable by means of this memory allocation functions.
int *p;
p = (int *) malloc ( 10 * sizeof(int)) ;
The above program constructs will return memory block of 20 bytes, which can hold 10 integers.
The starting address is pointed by the pointer ‘p’.
This will return 10 continuous memory blocks of 2 bytes each and initializes them to 0. This can be
used to allocate space for arrays and structures.
free(p) will release the memory pointed by a pointer variable ‘p’. free() will take a void pointer.
Example 8.19: Program for adding two matrices using array of pointers
void main()
{
int *a[3] , *b[3] , *c[3];
int i,j;
for(i=0 ; i<3; i++)
{
a[i] = (int *)malloc( 3 * sizeof(int));
/* memory is allocated to individual pointers */
b[i] = (int *)malloc( 3 * sizeof(int));
c[i] = (int *)malloc( 3 * sizeof(int));
}
printf(" \n enter the values of matrix 1 \n");
for(i=0; i<3; i++)
for(j=0; j<3; j++)
scanf("%d", a[i]+j);
printf("\n enter the values of second matrix");
Page 71
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Chain of Pointers
Multi dimensional arrays can be declared using pointer to pointer representation and memory can
be allocated dynamically.
int **p; represents 2 dimensional array
In the above declaration p is a pointer variable, which holds the address of another integer pointer.
As such, there is no restriction imposed by the compiler as to how many levels we can go about in
using a pointer.
However, beyond 3 levels, it will make the code highly complex and un-maintainable.
Example 8.20
addr.ptr2 addr.ptr1 value
int x,*p1,**p2;
x=100;
p1=&x;
p2=&p1;
To access the value we can use either **p2 or *p1
Advantages
It gives direct control over memory and thus we can play around with memory by all
possible means. For example, we can refer to any part of the hardware like keyboard,
video memory, printer, etc directly
As working with pointers is like working with memory, it will provide enhanced
performance
Pass by reference is possible only through the usage of pointers. Useful while returning
multiple values from a function
Allocation and freeing of memory can be done wherever required and need not be
done in advance(Dynamic Memory Allocation)
Page 72
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Limitations
If the allocated memory is not freed properly, it cause memory leakages
If not used properly, it makes the program difficult to understand and may cause the
illegal memory references
Summary
Pointer is a variable which can hold the address of another variable.
& operator is used to refer the address of a variable and * operator is used for
dereferencing the pointer.
Pointer can point to an array of any dimensions.
There are two ways to represent multi dimensional arrays by means of pointers:
o Single pointer points to set of arrays
o Array of pointers
Strings can easily be represented using pointer – Ragged arrays.
malloc(), calloc() functions are used to allocate memory dynamically.
free() function is used to de-allocate the memory.
Page 73
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Answers:
1. True, false, false, false
2. Generic pointers (void pointers) can point to data items of any type.
3. 100, 300
4. The first statement assigns 4 to a. The second statement assigns 5 to the location pointed to
by the location pointed to by c. Since c points to b, this is same as assigning 5 to the location
pointed to by b. Since b points to a, this statement is equivalent to assigning 5 to a. The third
statement castes **c, which is value of a, into type int *, assign the value to a. The result is
meaningless, because values cannot be assigned to pointers.
5. 2 5 5
6. malloc(), calloc() will both allocate the memory dynamically, but the difference is calloc() will
return a contiguous memory location and initializes it to 0.
Page 74
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Learning Objectives
After completing this chapter, you will be able to:
Explain the need for user-defined functions
Define functions
Invoke functions
Differentiate between different argument passing mechanisms
Pass arrays and pointers as arguments to a function
Define recursion
Use different storage classes in to a program
Use command line arguments
Thus, complex problems can be solved by breaking them into a set of sub-problems, called
Modules. Each module can be implemented independently and later can be combined into a single
unit.
C supports modularity by means of functions. C functions are classified into two categories.
User defined functions
Library functions
Page 75
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Function Prototype
Like variables, functions are declared and declaration of a function is called Function Prototype.
Prototype specifies the signature (name) of the function, the return type, and number and data
types of the arguments. It helps the compiler to know about the function. Functions must be
declared before it is called.
Function prototyping is not mandatory in C. It is mandatory when the function is called prior to its
definition. They are desirable, however, because they further facilitate error checking between
function calls and the corresponding function definition.
Example 10.1
int find_big (int, int);
/* function find_big returns integer value, takes 2 integer
arguments */
void swap (int *, int *);
/* function ‘swap’ does not return any value, takes 2 pointer
variables. */
float add(float, int);
/* function ‘add’ returns float value, takes 1 float variable and 1
integer variable */
Example 10.2
(1)
main()
{
int a,b;
int sum(int, int) ; /* function prototyping. */
scanf("%d%d” , &a, &b);
printf(“ %d “ , sum(a, b);
}
int sum(int a , int b)
{
return a+b;
}
Page 76
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
(2)
void fun()
Function is defined prior to its
{
reference. So compiler will
printf(“"prototype not needed “); identify the function name.
}
main()
{
fun();
}
Function Definition
Function definition is used to define the function with appropriate name, parameters, and the
operations to be carried out by the function. Functions can be defined at any location in the
program. If the function is defined before the ‘main’ program, there is no need for the function
prototype.
A function definition has two principle components: Function header (first line), Function body.
General form:
return-type function-name(type arg1, type arg2, …..)
{
local variables Declaration;
executable statement 1;
executable statement 2;
:
return expression;
}
Function Header
function-name specifies the name of the function and it must be a valid identifier
arg1,arg2 … specifies formal arguments (formal parameters)
return-type represents the data type of the data item returned by the function
Function Body
Function can have declaration statements and any number of valid executable statements.
Local Variables - The variables declared inside any function are local to that function. It can be
accessed only within that function. Memory for the local variables is allocated only when the
function is invoked and de-allocated when the control moves out of the function.
Global Variables - The variables that are common to all the functions are declared outside the
functions. If it is declared in the Global declaration section, it is used by all the functions in the
program. Memory for the global variables is allocated, when the program gets executed and de-
allocated only at the end of program execution.
Page 77
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
return statement is used to transfer the control back to the calling program. A function may or may
not return a value to the calling function. A function may receive any number of values from the
called function. If it returns a value, it is achieved by the return statement. There can be multiple
return statements, each containing different expression. If there is no return statement, the closing
braces (}) in the function body acts as a return statement.
General Form:
return;
OR
return(expression);
expression can be a variable name, constant value or any single valued expression.
Example 10.3
(1) return; does not return any value; (control is transferred to calling program)
(2) return 0; returns zero
(3) return(a*b); returns the product of a & b
(4) return(a<b); returns True (1) or False (0)
Example 10.4
Function for finding the biggest of two integers
int find_big(int a, int b)
{
if ( a > b)
return a; Function Name – find_big
else Return Type – integer
return b;
Formal arguments – 2 (a, b)
}
If the function doesn’t receive any arguments and doesn’t return any data, then void keyword is
used to represent that. Default return type is ‘int’.
Example 10.5
(1) void display(void)
{
printf(“this is a function”);
}
(2) main()
{
return 0;
}
Page 78
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Function Call
Functions are invoked by specifying its name, followed by a list of parameters enclosed within
parentheses.
General form:
[variable name =] function name(actual arguments);
Actual arguments are the parameters passed to the called function. The number, data type, and
the order of the actual arguments and formal arguments should match. Variable names of the
actual arguments and the formal arguments need not be same.
When the function call is encountered, the control is transferred to the called function and the
statements in the function are executed. When the return statement is executed or last statement
is execution, the control is transferred back to the place of function call in the calling function. If a
function is returning a value, that value is substituted in place of a function call in the calling
function. The LHS variable name in the function call is optional. If the function returns value, the
value returned is stored in the LHS variable name.
Example 10.6
Program for finding biggest of two integers using the function find_big
int find_big(int, int);
/* function prototype, global declaration */
main( )
{
int num1, num2, big;
scanf(“%d%d”, &num1, &num2);
big=find_big(num1,num2);
/* function call statement, num1 & num2 are actual arguments */
printf(“ The biggest is : %d “, big);
}
int find_big(int a, int b) /* a & b are formal arguments */
{
if ( a > b)
return a;
else
return b;
}
Note: Function can also be called using printf (“The biggest is: %d”, find_big(num1,num2))
statement.
Recursion
If a function is having a self-reference, it is called Recursion. It is a process by which a function
calls itself.
Page 79
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Example 10.7
main()
{
int n, fact(int);
printf(“Enter an integer\n”);
scanf(“%d“,&n);
printf(“Factorial = %d“,fact(n));
}
fact(int k);
{
if (k<=1)
return 1;
else
return(k*fact(k-1);
}
If n = 4, then
call 1 = 4 * fact(3); call 2 = 3 * fact(2) ; call 3 = 2 * fact(1)
In fourth call, the condition evaluates to 1 and returns 1 to the calling part (call 3), which in turn
return the value to its calling function. Function will be evaluated in Last In First Out manner
(Stack)
Nesting of Functions
Functions may be nested. The main function may call function1, which in turn call function2, which
may call function3.
Passing Arguments
A function is referenced by its name and providing appropriate values for the arguments. On
seeing the name of the function in calling statement, the control is immediately transferred to the
function. The parameter values are substituted and the function is executed. When the return
statement is encountered, control is transferred back to the called function, along with the value
returned.
Page 80
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Example 10.8
No Arguments and no return value No arguments but return value
main() main()
{ {
border(); int sum;
printf(“\t\t Hello World\n””) sum=add();
border(); printf(“\nSum = %d”,sum);
} }
border() add()
{ {
int i; int a,b;
for(i=1;i<=80;i++) scanf(“%d%d”, &a,&b);
printf(“-“); return(a+b);
printf(“\n”); }
return;
}
Example 10.9
With arguments and no return value With arguments and return value
main() main()
{ {
int n; char c; int sum,a,b;
printf(“Enter the size of border & style\n”); printf(“Enter2 integers\n”);
scanf(“%d%c”, &n,&c); scanf(“%d%d”,&a,&b);
border(n,c); sum=add(a,b);
printf(“\t\t Hello World\n””) printf(“\nSum = %d”,sum);
border(n,c);
} }
border(int m, char s) add(int x,int y)
{ {
int i; return a+b ;
for(i=1;i<=m;i++) }
printf(“%c“,s);
printf(“\n”);
return;
}
Page 81
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Call by Value
Arguments are usually passed by value in C function calls. The values of the actual arguments are
copied in to the respective formal arguments. Actual and formal arguments refer to the different
memory locations and the value of actual argument is copied into the formal argument. So, any
changes made to the formal argument are not reflected in their corresponding actual arguments.
The value of the actual argument will remain same.
Call by Reference
In this approach, the addresses of actual arguments are passed to the function call and the formal
arguments will receive the address. The actual and formal arguments refer to the same memory
location. So, changes in the formal arguments are reflected in actual arguments.
Note: Actual arguments are address of the ordinary variable, pointer variable or array name.
Formal arguments should be a pointer variable or array.
This approach is of practical importance while passing arrays to functions and returning back more
than one value to the calling function. Passing arrays to functions is call by reference by default.
Page 82
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Example 10.12
int maximum( int val[] )
/*size of the array need not be mentioned */
{
int max_value, i;
max_value = val[0];
for( i = 0; i < 5; ++i )
if ( val[i] > max_value )
max_value = val[i];
return max_value;
}
Page 83
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
main()
{
int values[5], i, max;
printf("Enter 5 numbers\n");
for( i = 0; i < 5; ++i )
scanf("%d", &values[i] );
max = maximum(values);
/* array name is used to pass an entire array without any
subscripts */
printf("\nMaximum value is %d\n", max );
}
Example 10.13
void print_table(int xsize,int ysize, float table[][5])
{
int x,y;
for (x=0;x<xsize;x++)
{
for (y=0;y<ysize;y++)
printf("\t%f",table[x][y]);
printf("\n");
}
}
Note: Second dimension is mentioned with its size. In case of three dimensional arrays, second &
third dimension has to be mentioned. This is to represent the column size. The array elements are
stored in row major form.
Arrays can not be returned with return statement since return can pass only a single-value back to
the calling program. Therefore, in order to return an array to the calling program, the array must
either be defined as global array, or it must be passed as a formal argument to a function.
Page 84
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Page 85
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
It is possible to pass a portion of an array, rather than an entire array, to a function using pointers.
Function Pointer
Function will also have a memory address like other variables. So, we can have a pointer variable
to point to the starting location of a function and can execute the function by means of the pointer
variable, which will speeds up the execution.
General Form:
return-type (* function_pointer_name)(argument list..)
Page 86
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Example 10. 17
int display();
int (*func_ptr) ();
func_ptr = display;
(*func_ptr) (); /*invokes the function display */
Example 10.18
main()
{
void abc();
abc();
(*abc)(); /* calling the function by function pointer */
}
void abc()
{
printf(“function”);
}
Output:
functionfunction
Storage Classes
Variables in C can be characterized by their data type and storage classes. Data type refers to the
type of information represented by a variable and storage classes define its life time and scope.
Scope
The scope of the variable (where it can be used), is determined by where it is defined. If it is
defined outside of all the blocks, it has file scope. This means, it may be accessed anywhere in the
current source code file. This is normally called a global variable and is normally defined at the top
of the source code. All other types of variables are local variables. If a variable is defined in a block
(encapsulated with {and}), its scope begins when the variable is defined and ends when it hits the
terminating. This is called block scope.
Life Time
Life time refers to the permanence of a variable – How long the variable will retain its value in
memory.
General Form:
storage-class-specifier type-specifier variable-names,...
The storage-class-specifier can be any one of the following:
auto
static
register
extern
Page 87
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Example 10.19
main()
{
int a = 5 ;
{
int a =6 ;
printf (“%d “ , a); prints 6
}
printf(“ %d “ , a); prints 5
}
One important feature of automatic variables is that their value cannot be changed by whatever
happens in some other function in the program. A variable local to the main function will be
normally alive throughout the whole program, although it is active only in main(). In the case
recursive functions, the nested variables are unique auto variables, a situation similar to function
nested auto variables, with identical names.
A static variable may be either internal (local) or external (global). Internal variables are those
declared inside a function (or block). The scope is only to the function in which it has been
declared but the variable exists in the memory throughout the entire life of the program .Thus,
internal static variables retain values between function calls.
Page 88
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Example 10.20
main()
{
int i;
for (i=1;i<=5;i++)
incre();
}
incre()
{
static int x = 0;
x = x +1;
printf(“ x = %d\n”,x);
}
Output:
x = 1
x = 2
x = 3
x = 4
If the declaration of register variable exceeds the availability, they will be automatically converted
into non register variables (automatic variable).
Register variables are local (Visible) to the block in which they declared. It retains its value till the
control remains in that block. If not initialized in the declaration, the variable is initialized to zero.
External variables can be accessed from any function and the changes done by one function will
be reflected through out the entire scope. When using external variables, we must distinguish
between:
External Variable Definition
External Variable Declaration
If not initialized in the declaration, it is initialized to zero. External variables are useful when
working with multiple source files.
Page 89
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Example 10. 21
int a = 5 ;
/* external variable definition (No need to use extern keyword) */
main()
{
extern int b;
/* external variable declaration, just to say that the
variable is declared somewhere else in the same program or
other programs. */
void fun();
fun();
printf(“ %d “ , a); /* prints 10 */
printf(“ %d “ , b); /* prints 20 */
}
void fun()
{
a = 10 ;
}
int b = 20;
A C program is executed by calling its main() function. The function is called with one integer
argument that indicates how many words are in the command line and another argument that is a
character array of pointers containing the command line words.
Page 90
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Example 10.21
main( int argc, char* argv[])
{
int i;
printf(“\n Total Number of Arguments = %d”,argc);
for( i = 0; i < argc; i++)
printf(“\nArgument number %d = %s”,i , argv[i]);
}
When the following command is given in the command prompt,
C:\tc\bin> CMLPGM c cpp java (CMLPGM program name, c cpp java arguments)
The following result is displayed
Number of Arguments = 4
Argument number 0 = CMLPGM
Argument number 1 = c
Argument number 2 = cpp
Argument number 3 = java
Summary
Functions are smaller self-contained components which carry out some specific, well
defined task.
Functions facilitates reusability and brings logical clarity to the programs.
C functions should be considered with three aspects: i) function definition, ii) function
call, iii) function prototyping
Arguments can be passed to a function via call by reference method or by call by value
method.
Arrays can be passed to a function by simply specifying its name.
A function calling itself is called recursion.
C supports four storage class specifiers (auto, static, extern and register) to define
scope and life time for the variable.
The command line arguments, argc and argv are used to pass arguments to main()
function.
Page 91
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
2. What is relationship between the actual parameters and its formal parameters?
Page 92
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Answers:
1. Function prototyping is like a function declaration statement which informs the compiler
about the function (its name, type of its arguments, return data type). In C, it is needed
only when the function is called prior to its definition.
2.
a. There must be a one-to-one correspondence between the actual and formal
parameters.
b. Corresponding parameters must be of same type.
3. 3 4
4. In call by reference, address of the actual parameters are passed to corresponding formal
parameters but in call by value, only the values of the actual parameters are copied in to
corresponding formal parameters.
5. 10
Page 93
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Learning Objectives
After completing this chapter, you will be able to:
Appreciate the concept of structures and unions
Define and utilize the advantages of structures and unions
Differentiate structures and unions
Declare enumerated variables
Define new data types using typedef statement
Introduction
Structures and Unions are the main constructs available in C by which programmers can define
new data type. Structures and unions provide a way to group together logically related data items.
Structure
Structure is a derived data type used to represent heterogeneous data items. A structure is an
aggregation of components that can be treated as a single variable. The components are called
Members.
For example, an employee is represented with the following attributes: employee code (string /
integer), employee name (string), department code (string), salary (float).
Declaration
C provides facilities to define structures via a template and to declare a tag to be associated with
such structures so that it is not necessary to repeat the definition. “struct” keyword is used to
define structures.
General form:
struct tag_name
{
type variable-name, variable-name,........;
type variable-name, variable-name,........;
type variable-name, variable-name,........;
:
:
type variable-name, variable-name,........;
};
Page 94
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Structure definition and declaration of structure variables can be combined together. Here, tag
name is optional.
Note: If tag name is not specified in the declaration, no extra structures can be created.
Example 12.1
1) struct employee
{
int code;
char name[20];
int dept_code;
float salary;
} ;
struct employee emp1, emp2;
Initialization
Structure variables can be initialized at the time of declaration. The format used is quite similar to
initializing an array. If the structure variable is declared before the main function in the global
declaration section, the member variables are automatically initialized to zero or Null depending on
the data type of the member variable. If it is partially initialized, uninitialized members are assigned
zero or Null.
Page 95
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Example 12.2
struct stud
{
int rollnum;
char name[20];
int semester;
float avg;
};
struct stud stud1={101,”Dina”, 1, 90.78}, stud2={102, “Raja”, 1};
For the structure variable ‘stud2’, the ‘avg’ will be initialized to 0.0
Individual structure members can be initialized only via structure variable. No storage class can be
specified for structure members.
struct employee
{
int empno = 101 ; illegal;
static char[20] empname = “AAAA”; illegal;
}
General Form:
struct_vble . member-field-name
Example 12.3
emp1.code
emp1.name
emp1.dept_code
emp1.salary
emp2.code
emp2.name
Operations on Structures
Two structure variables cannot be compared for equality, even though the values stored in the
member variables are same. This is because, slack bytes are added in-between two member
variables and these slack bytes have garbage value. While comparing structure variables, the
values in slack bytes are also compared, which is always not same for different structure variables.
Assignment operation is allowed. For example, if ‘a’ and ‘b’ are two structure variables of the same
structure type, the assignment expression a = b is valid. It causes each member of ‘a’ to be
assigned the value of the corresponding member of ‘b’.
Page 96
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Example 12.4
struct emp
{
int empno;
char name[20];
float basic;
} emp1;
printf (“Size = %d”,sizeof(emp1)); Size = 26
Nested Structure
Just as arrays of arrays, structures can contain members that themselves are structures. This can
be a powerful method to create complex data types.
Example 12.5
struct date
{
int day;
int month;
int year;
};
struct employee
{
int code;
char name [20];
struct date doj;
int dept_code;
float salary;
}emp1,emp2;
In this example, if we want to access the year of joining of an employee of emp1, then we can do
so by writing:
emp1.doj.year
Page 97
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Accessing values:
student [1].rollnum
student [1].name
student [1].semester
student [1].avg
In this declaration, ‘ptr’ is a pointer type variable, which can hold an address of a variable of the
type ‘student’.
Page 98
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Example 12.8
struct stud
{
int rollnum;
char name[20];
int semester;
float avg;
};
struct stud student={101,”raja”, 1, 95.67}, *ptr ;
To make ‘ptr’ to point to the structure ‘student’, we can write as
ptr = &student;
The notation for referring a member field of a structure pointed by a pointer is as follows:
(*pointer). memberfieldname
(OR)
pointer -> memberfieldname
Example 12.9
Self-Referential structures
A structure containing a member that is a pointer to the same structure type is called self-
referential structures. It is used to build various kinds of linked data structures.
Example 12.10
struct employee
{
char name[20];
char gender;
float salary;
struct employee *empptr;
};
Page 99
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Example 12.11
struct emp
{
int empno;
char empname[10];
};
main( )
{
void display(struct emp);
struct emp emp1 = { 101 , “AAAA”} ;
display(emp1);
}
Entire structure can be passed to a function using call by reference method. We can use pointer to
structures, or we can pass address of the structure variable using & operator.
Example 12.12
struct emp
{
int empno;
char empname[10];
};
void main( )
{
void change(struct emp *);
struct emp emp1 = { 101 , “AAAA”} ;
change(&emp1);
printf(“%d” , emp1->empno); /* prints 102 */
}
void display(struct emp *emp2)
Page 100
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
{
emp2->empno=102;
}
Example 12.13
emp1 = emp_pay (wage, x, y); wage is a structure variable of sal structure.
emp1 is a structure variable of employee structure.
struct employee emp_pay (struct sal pay, int a, float b) { } function definition
Unions
Union, like a structure, is a derived data type. Unions follow the same syntax as structures. The
programmer is responsible for interpreting the stored values correctly. Union differs from structure
in storage and in initialization.
Declaration
The declaration can be thought of as a template - it creates the type, but no storage is allocated. In
the declaration, keyword ‘union’, the tag name, and the members of the union are given. The tag
name, along with the keyword ‘union’, can be used to declare variables of the union type. For each
variable, the compiler allocates a piece of storage that can accommodate the largest of the
specified members.
General Form:
union tag_name
{
type variable-name, variable-name,........;
type variable-name, variable-name,........;
type variable-name, variable-name,........;
:
:
type variable-name, variable-name,........;
}union-variable, union-variable...... ;
Page 101
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Initialization
Union can be initialized only with a value for the first union member. No other member can be
initialized.
Example 12.14
union item
{
int m;
float x;
char c;
};
static union item product = {100};
/* m will be initialized with 100 */
Union of Structures
Structures and unions can be members of structures and unions.
struct stud_type
{
int rollno;
char name[15];
int age;
float avg;
};
Page 102
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
union person
{
char surname[10];
struct employee_type e1;
struct stud_type s1;
}ex;
In the above example, the union allows the structure variables, e1 and s1, to share common
memory. That is, the user can use either e1 or s1, but not both, at the same time.
The elements of this union of structures are accessed using dot operator as follows:
ex.e1.salary
Enumeration
Enumeration is a derived data type, similar to structures or a union. Its members are constants that
are written as identifiers, though they have signed integer values. These constants represent
values that can be assigned to corresponding enumeration variables. “enum” keyword is used to
declare enumerated variables.
General Form:
enum tag { member1 , member2 , …… member n } ;
tag is a name that identifies enumerations having this composition and members represent the
identifiers that may be assigned to variables of this type. The member names must differ from one
another.
Example 12.16
enum escapes { bell = `\a', backspace = `\b', tab = `\t’, newline =
`\n', vtab = `\v', return = `\r'}
main()
{
enum escapes e1;
e1 = getch();
if (e1 == newline)
printf("newline");
}
Page 103
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Enumeration variables can be processed in the same manner as other integer variables. As with
arrays, first enumerated name has index value 0, next value is calculated as previous plus one.
We can also override the 0 start value by assigning some other value.
Typedef Statement
The ‘typedef’ allows users to define new data types that are equivalent to existing data types. It is
used to give new names to existing data types.
General Form
Example 12.17
typedef numbers int;
numbers is the new name given to integer data type and it can be used to declare integer
variables.
numbers n1, n2 ; n1 , n2 are the integer variables.
Example 12.18
typedef struct
{
int empno;
char empname[10];
}employee;
employee is the name given to the structure of the above type. Then structure variables can be
declared as follows,
Page 104
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Summary
Structure is a derived data type used to store heterogeneous data items under a single
unit.
Structure members can be accessed by structure variables using dot ( . ) operator.
Structures can be nested and can also have self reference.
Structure can be passed to a function by both call by value approach and call by
reference approach.
Unions are similar to structures but the main difference is that union members share
the common memory location whereas memory is allocated to individual structure
members.
In unions, only one member is accessible at a time.
enum keyword is used to define enumerations.
typedef statement is used to define new data types which are compatible with existing
ones.
Page 105
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Answers:
1. The elements of an array are always of the same type, whereas the members of a
structure can be of different types.
2. Self referential structures will contain a member that is a pointer to the parent structure
type. It is very useful in applications that involve linked data structures.
3. *p1->p;
4. Size = 19
Page 106
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Learning Objectives
This session will enable you to:
Explain the concept of file and its types
Know the basic file operations
Perform formatted, unformatted and block file I/O operations
Access files in both sequential and random order
Make use of pre-processor directives
Introduction
When a large volume of data is involved, supplying data through the keyboard during the
execution or displaying the output on the screen is not convenient. The input data can be stored on
disks and the program may access the data from disks for processing. Similarly, the results may
be stored on disks. For such applications, files are needed. A file is a place on the disk where a
group of related data is stored. In C, file manipulations may be done in two ways:
Low-level I/O using system calls
High-level I/O using functions from standard I/O library
The files accessed through the library functions are called Stream Oriented files and the files
accessed with system calls are known as System Oriented files.
Text streams are composed of a set of lines. Each line has zero or more characters and is
terminated by a new line character. Text streams consist of printable characters, the tab character,
and the new-line character. Conversions may occur on text streams during input and output.
Spaces cannot appear before a newline character, a text stream removes these spaces even
though implementation defines it. A text stream, on some systems, may be able to handle lines of
up to 254 characters long (including the terminating new line character).
Binary streams are composed of only 0’s and 1’s. It is simply a long series of 0’s and 1’s. More
generally, there need not be a one-to-one mapping between characters in the original file and the
characters read from or written to a text stream. But in the binary stream there will be one-to-one
mapping because no conversion exists, and all characters will be transferred as such.
Page 107
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
File Operations
Files are associated with streams and must be open in order to use it. The point of I/O within a file
is determined by the file position. When a file is opened, the file position points to the beginning of
the file unless the file is opened for an append operation - in which case the position points to the
end of the file. The file position indicates where the next operation (read/write) will occur.
When a file is closed, no more actions can be taken on it until it is opened again. Exiting from the
main function causes all open files to be closed.
In C, ‘FILE’ is a structure that holds the description of a file and is defined in stdio.h.
Page 108
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
General form:
FILE *fp;
fp = fopen(“name”, “mode”);
fscanf(fp, "format string", variable list);
fprintf(fp, "format string", variable list);
fclose(fp );
Where:
The ‘fp’ is a file pointer or file handler.
The ‘name’ is to represent filename and it is a string of characters. (Extensions can be
specified like test.c, details.dat etc)
The ‘mode’ argument in the fopen() specifies, the purpose/positioning of opening the
file. It is a string enclosed within double quotes.
w write text mode (truncates file to zero length if it already exits or creates new file)
a append text mode for writing (opens or creates file and sets file pointer to the end-of-file)
wb write binary mode (truncates file to zero length if it already exits or creates new file)
ab append binary mode for writing (opens or creates file and sets file pointer to the end-of-file)
w+ read and write text mode (truncates file to zero length if it already exists or creates new file)
a+ read and write text mode (opens or creates file and sets file pointer to the end-of-file)
r+b or
read and write binary mode
rb+
w+b or read and write binary mode (truncates file to zero length if it already exists or creates new
wb+ file)
a+b or
read and write binary mode (opens or creates file and sets file pointer to the end-of-file)
ab+
Page 109
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
If the file does not exist and it is opened with read mode (r), the file open fails and it will return
NULL to file pointer.
If the file is opened with append mode (a), all write operations occur at the end of the file
regardless of the current file position.
If the file is opened in the update mode (+), output cannot be directly followed by input and input
cannot be directly followed by output without an intervening fseek(), fsetpos(), rewind(), or fflush().
fopen() returns the file pointer position for successful open and returns NULL, if the file does not
open or the file does not exist.
fclose() returns zero for successful close and returns EOF (end of file) when error is encountered
in closing a file. By default, all the files opened are closed when the program is terminated. It is
good to close all the files opened with fopen(), because files can be reopened only if they are
closed.
The Standard I/O provides variety of functions to handle files. It supports the following ways of
reading from and writing into file:
Character I/O
String I/O
Formatted I/O
Block I/O
Integer I/O
Character I/O
Using character I/O, one character (byte) can be written to or read from a file at a time.
Writing in to a file
To write into a file, the file must be opened in ‘w’ mode The function putc() is used to write a byte
to a file.
General Form:
putc(ch,fptr);
This function writes the character ch into a file pointed by the file pointer fptr. This fptr may be
stdout, which represents standard output device, monitor as a file. On success, the character is
returned. If an error occurs, the error indicator for the stream is set and EOF is returned.
Page 110
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
General Form:
ch =getc (fptr);
This function reads a character from the file and it is returned to the program defined character
variable. After the reading a character, the pointer is moved to the next position. The fptr may be
stdin, which represents a standard input device, keyboard as a file. On success, the character is
returned. If the end-of-file is encountered, EOF is returned and the end-of-file indicator is set. If an
error occurs, the error indicator for the stream is set and EOF is returned. The EOF is end of file
status flag, which is true if end of file is reached, otherwise false.
Page 111
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
String I/O
Using string I/O, string can be written to, or read from, a file at a time.
General Form:
fputs (str, fptr);
General Form:
fgets(str,n,fptr);
Numeric I/O
Using numeric I/O, integers can be written to, or read from, a file at a time.
General Form:
putw (i, fptr);
General Form:
i = getw( fptr);
Page 112
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Formatted I/O
The formatted I/O functions can handle a group of data in a single call.
The fprintf() function takes the format string specified by the format argument and applies each
following argument to the format specifiers in the string, in a left to right fashion. Each character in
the format string is copied to the stream except for conversion characters which specify a format
specifier.
General Form:
fscanf( fptr, format-string, addresses-list);
The fscanf() function takes input in a manner that is specified by the format argument and stores
each input field into the corresponding arguments, in a left to right fashion.
Each input field is specified in the format string with a conversion specifier which specifies how the
input is to be stored in the appropriate variable. Other characters in the format string specify
characters that must be matched from the input, but are not stored in any of the following
arguments. If the input does not match, the function stops scanning and returns. A white space
character may match with any white space character such as space, tab, carriage return, new line,
vertical tab, or form feed, or the next incompatible character.
Page 113
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Block I/O
Block I/O is used to read or write a specified number of bytes. The data handled by block
input/output function will be in ‘raw data format’ (i.e. bytes of data).
Writing in to a file
The function used is fwrite().Transfers a specified number of bytes beginning at a specified
location in memory to a file. Used to write a structure or an array of structures to an output file. The
function writes data from the array pointed to by ptr to the given stream. It writes ‘n’ blocks of size
‘size’. The total number of bytes written is (size*n). On success the number of elements written is
returned. On error the total number of elements successfully written (which may be zero) is
returned.
Page 114
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
General Form
fwrite (ptr, size, n, fp);
Where:
ptr pointer to the data block (source)
size size of each block (number of bytes to be written)
n number of blocks to be written
fp file pointer (destination)
General Form
fread (&str, size, n, fp);
Where:
&str destination memory address
size size of each block (number of bytes to be read)
n number of blocks to be read
fp file pointer (source)
Example 14.4: Program using Block I/O
main()
{
FILE *fptr;
struct tag
{
char name[10];
int age ;
}stud[10] , stud1[10];
int i ;
clrscr();
fptr=fopen("ex.dat" , "w" );
for(i=0 ; i<5 ; i++)
scanf("%s %d ",stud[i].name , &stud[i].age);
fwrite(&stud , sizeof(stud[0]) , 5 , fptr);
fclose(fptr);
fptr = fopen("ex.dat" , "r" );
fread(&stud1 , sizeof(stud1[0]) , 5 , fptr);
printf(" \n\n printing the values ");
for(i=0 ; i<5 ; i++)
printf("\n %s \t %d " , stud1[i].name , stud1[i].age);
}
Page 115
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
ftell()
This function takes a file pointer and returns a long int, which corresponds to the current file pointer
position. If it is a binary stream, then the value is the number of bytes from the beginning of the file.
If it is a text stream, then the value is a value usable by the fseek() function to return the file
position to the current position. On success, the current file position is returned. On error, the value
-1L is returned and error number (errno) is set.
General Form:
n = ftell(fptr);
fseek()
This function sets the file position to the given offset (specified in long integer format).
General Form:
fseek( fptr, offset, from_where)
The argument offset signifies the number of bytes to seek from the given ‘from_where’ position.
The argument from_where can be:
On a text stream, from_where should be SEEK_SET and offset should be either zero or a value
returned from ftell(). The end-of-file indicator is reset. The error indicator is NOT reset. On
success, zero is returned. On error, a nonzero value is returned.
Example 14.3
fseek (fp, 0L, 0); Move the file pointer to the beginning.
fseek (fp, 0L, 2); Move the file pointer to the end of file.
fseek (fp, 10L, 0); Move after 10 bytes from the beginning.
fseek (fp, 10L, 1); Move after 10 bytes from the current
fseek (fp, -10L, 1); Move backward 10 bytes from the current
fseek (fp, -10L, 2); Move backward 10 bytes from the EOF.
Page 116
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
rewind()
This function sets the file position to the beginning of the file of the given stream. The error and
end-of-file indicators are reset.
General Form:
rewind(fptr);
Preprocessor Directives
One of C's most useful features is its preprocessor. Preprocessor directives are lines included in
the code that are not program statements but directives for the preprocessor. These lines are
always preceded by a pound sign (#). The preprocessor is executed before the actual compilation
of code begins, therefore the preprocessor digests all these directives before any executable code
is generated for the statements.
Preprocessing is a step that takes place before compilation that lets you to:
Replace preprocessor tokens in the current file with specified replacement tokens.
Embed files within the current file
Conditionally compile sections of the current file
Generate diagnostic messages
Remove the blank lines in the program, change the line number of the next line of
source and change the file name of the current file.
Remove comments from the source file.
A token is a series of characters delimited by white space. The white space allowed on a
preprocessor directive may be the space, horizontal tab, vertical tab, form feed, or carriage return.
Preprocessor directives begin with the # token followed by a preprocessor keyword. The # token
must appear as a first character. The # is not part of the directive name and can be separated from
the name with white spaces.
A preprocessor directive ends at the new-line character unless the last character of the line is the \
(backslash) character. If the \ character appears as the last character in the preprocessor line, the
preprocessor interprets the \ and the new-line character as a continuation marker. The
preprocessor deletes the \ (and the following new-line character) and splices the physical source
lines into continuous logical lines. No semicolon (;) is expected at the end of a preprocessor
directive.
Page 117
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Except for some #pragma directives, preprocessor directives can appear anywhere in a program.
Preprocessor Directives
Name Action
#elif Conditionally includes source text if the previous #if, #ifdef, #ifndef, or #elif test fails.
#else Conditionally includes source text if the previous #if, #ifdef, #ifndef, or #elif test fails.
Preprocessing Operations:
Pre processing operations are mainly classifieds into 1) File Inclusion, 2) Macro substitution and 3)
Conditional Compilation.
Preprocessing will be done before compilation, compilation process operates on the preprocessor
output, which is then syntactically and semantically analyzed and translated, and then linked as
necessary with other programs and libraries.
File Inclusion
Page 118
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
The #include directive allows external files to be added in to our source file, and then processed
by the compiler.
General Form:
#include <header file> OR #include “header file”
The only difference between both expressions is the places (directories) where the compiler is
going to look for the included file.
If the file name is enclosed between angle-brackets <>, the file is searched in the directories where
the compiler is configured to look for the standard header files. Therefore, standard header files
are usually included in angle-brackets, while other user specificed header files are included using
quotes.
In the second case where the file name is specified between double-quotes, the file is searched
first in the current working directory. In case that it is not there, the compiler searches the file in the
default directories where it is configured to look for the standard header files.
Example 14.4
#include <stdio.h>
#include “stdio.h”
Preprocessor Macros:
#define preprocessor directive is used to define a macro that assigns a value to an identifier. The
preprocessor replaces subsequent occurrences of that identifier with its assigned value until the
identifier is undefined with the #undef preprocessor directive, or until the end of the program
source is reached, whichever comes first.
There are two basic types of macro definitions that you can use to assign a value to an identifer:
Object-like Macros Replaces a single identifier with a specified token or constant value.
(Symbolic constants)
Symbolic Constants
The preprocessing directives #define and #undef allow the definition of identifiers which hold a
certain value. These identifiers can simply be constants or a macro function.
Page 119
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
#define
General Form:
#define symbolicvaraiablename value
Example 8.5
#define SIZE 10
#define NAME “xyz” /* good practice is to use upper case
letters */
#undef:
General Form:
#undef variablename
Example 14.6
#undef SIZE
Macros:
General Form:
#define macroname(argument list) macrodefn
Example:
#define sqarea(a) ((a)*(a))
main()
{
areaofsquare=sqarea(a);
…..
}
Arguments in the macro definition are enclosed with parenthesis to avoid miscalculation.
Continuation character for macro definition is \. There is no need for semicolon after the macro
definition.
Page 120
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Example 14.7
#define sqarea(a) ((a)*(a))
#define sqa(b) b*b
#define add(a,b) ((a)+(b));
main()
{
areaofsquare=sqarea(a); /* areaofsquare = (a) * (a); */
areaofsquare=sqarea(3); /* areaofsquare = (3) *(3); */
areaofsquare=sqarea(3+4); /* areaofsquare=(3+4)*(3+4); */
areaofsquare=sqa(3+4); /* areaofsquare=3+4*3+4; (1) */
addition=add(2,3); /* addition=(2)+(3);; (2) */
}
(1) miscalculation because of no parentheses
(2) two semicolons in macro expansion.
General Form:
#if constant_expression
#else
#endif
OR
#if constant_expression
#elif constant_expression
#endif
The compiler only compiles the code after the #if expression if the constant_expression evaluates
to a non-zero value (true). If the value is 0 (false), then the compiler skips the lines until the next
Page 121
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
#else, #elif, or #endif. If there is a matching #else, and the constant_expression evaluated to 0
(false), then the lines between the #else and the #endif are compiled. If there is a matching #elif,
and the preceding #if evaluated to false, then the constant_expression after that is evaluated and
the code between the #elif and the #endif is compiled only if this expression evaluates to a non-
zero value (true).
Example 14.8
Check whether a variable is defined. If so, change the value of that variable to 1 after undefining it.
#if define(NUMBER)
#undef NUMBER
#define NUMBER 1
#endif
# and ## operators
Example 14.9
#define name(x) #x
main()
{
…..
printf(name(xyz)); /* printf(“xyz”); */
….
}
## concatenation operator
Example 14.10
#define name(x,y) x##y
main()
{
…..
printf(name(ssn,somca)); /* printf(“ssnsomca”); */
….
}
Page 122
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Summary
Files are used to store bulk of related information in secondary storage.
Files can be classified as system oriented and stream oriented files.
fopen(), fclose() functions are used for opening and closing of files.
Input, Output operations on files can be of character I/O, string I/O, formatted I/O and
block I/O.
Direct access of a file is supported by fseek(), ftell(), and rewind() functions.
Preproccessing is done before compilation.
Preprocessor directives are identified by # symbol.
Preprocessor directives perform i) macro substitution, ii) file inclusion and iii)
conditional compilation.
Page 123
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Answers:
1. stdin, stdout, stderr
3. EOF is a constant returned by many I/O functions to indicate that the end of an input file
has been reached. Its value on most computers is -1.
4. No significance, trying to move file pointer in the forward direction from the end of file.
5. 50 50
Page 124
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Syntax Summary
Program Structure/Functions
type fnc(type1,: : : ) function declarations
type name external variable declarations
main() { main routine
declarations local variable declarations
statements
}
/* */ comments
main(int argc, char *argv[]) main with args
exit(arg) terminate execution
C Preprocessor
#include <filename> include library file
#include "filename" include user file
#define name text replacement text
#define name(var) text replacement macro
Example. #define max(A,B) ((A)>(B) ? (A) : (B))
#undef name undefine
# quoted string in replace
## concatenate args and rescan
#if, #else, #elif, #endif conditional execution
#ifdef, #ifndef is name defined, not defined?
name defined? defined(name)
line continuation char \
Page 125
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Data Types/Declarations
character (1 byte) char
integer int
float (single precision) float
float (double precision) double
short (16 bit integer) short
long (32 bit integer) long
positive and negative signed
only positive unsigned
pointer to int, float *int, *float
enumeration constant enum
constant (unchanging) value const
declare external variable extern
register variable register
local to source file static
no value void
structure struct
create name by data type t typedef typename
size of an object (type is size_t) sizeof object
size of a data type (type is size_t) sizeof(type name)
Initialization
initialize variable type name=value
initialize array type name[]={value1,: : : }
initialize char string char name[]="string"
Constants
long (suffix) L or l
float (suffix) F or f
exponential form e
octal (prefix zero) 0
hexadecimal (prefix zero-ex) 0x or 0X
character constant (char, octal, hex) ‘a’, ‘\ooo’, ‘\xhh’
newline, cr, tab, backspace \n, \r, \t, \b
special characters \\, \?, \, \"
string constant (ends with \0) "abc: : : de"
Page 126
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Structures
struct tag { structure template
declarations declaration of members
};
Page 127
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
logical or ||
conditional expression expr1 ? expr2 : expr3
assignment operators +=, -=, *=, ……
expression evaluation separator ,
Unary operators, conditional expression and assignment operators group right to left; all others
group left to right.
Flow of Control
Statement terminator ;
Block delimiters {}
Exit from switch, while, do, for break
Next iteration of while, do, for continue
go to goto label
Label label:
Return value from function return expr
Flow Constructions
if statement if (expr) statement
else if (expr) statement
else statement
while statement while (expr)
statement
for statement for (expr 1; expr2; expr3)
statement
do statement do statement
while(expr );
switch statement switch (expr) {
case const1: statement1 break;
case const2: statement2 break;
default: statement
}
Page 128
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Page 129
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Input/Output <stdio.h>
Standard I/O
Standard input stream stdin
Standard output stream stdout
Standard error stream stderr
End of file EOF
Get a character getchar()
Print a character putchar(chr )
Print formatted data printf("format ",arg 1,..)
Print to string s sprintf(s,"format ",arg 1,… )
Read formatted data scanf("format ",&name1,… )
Read from string s sscanf(s,"format ",&name1,…. )
Read line to string s (< max chars) gets(s,max)
Print string s puts(s)
File I/O
Declare file pointer FILE *fp
Pointer to named file fopen("name","mode")
Where modes: r (read), w (write), a (append)
Get a character getc(fp)
Write a character putc(chr ,fp)
Write to file fprintf(fp,"format",arg 1,: : : )
Read from file fscanf(fp,"format",arg 1,: : : )
Close file fclose(fp)
Non-zero if error ferror(fp)
Non-zero if EOF feof(fp)
Read line to string s (< max chars) fgets(s,max,fp)
Write string s fputs(s,fp)
Page 130
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Page 131
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Conversions
Function Type Functions
Convert string s to double atof(s)
Convert string s to integer atoi(s)
Convert string s to long atol(s)
Convert prefix of s to double strtod(s,endp)
Convert prefix of s (base b) to long strtol(s,endp,b)
Convert prefix of s (base b) to unsigned long strtoul(s,endp,b)
Storage Allocation
Function Type Functions
Allocate storage malloc(size), calloc(nobj,size)
Change size of object realloc(pts,size)
Deal locate space free(ptr)
Page 132
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
[.precision] Defines the amount of precision to print for a number type (optional).
Flags:
+ Forces the sign (+ or -) to always be shown. Default is to just show the - sign. Overrides the
space flag.
space Causes a positive value to display a space for the sign. Negative values still show the -
sign.
# Alternate form:
Conversion Character Result
0 For d, i, o, u, x, X, e, E, f, g, and G leading zeros are used to pad the field width instead of
spaces. This is useful only with a width specifier. Precision overrides this flag.
Width:
The width of the field is specified here with a decimal value. If the value is not large enough to fill
the width, then the rest of the field is padded with spaces (unless the 0 flag is specified). If the
value overflows the width of the field, then the field is expanded to fit the value. If a * is used in
place of the width specifer, then the next argument (which must be an int type) specifies the width
of the field. Note: when using the * with the width and/or precision specifier, the width argument
comes first, then the precision argument, then the value to be converted.
Page 133
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Precision:
The precision begins with a dot (.) to distinguish itself from the width specifier. The precision can
be given as a decimal value or as an asterisk (*). If a * is used, then the next argument (which is of
an int type) specifies the precision. Note: when using the * with the width and/or precision specifier,
the width argument comes first, then the precision argument, then the value to be converted.
Precision does not affect the c type.
Result
[.precision]
. or .0 For d, i, o, u, x, X types the default precision value is used unless the value is zero in
which case no characters are printed.
For f, e, E types no decimal point character or digits are printed.
For g or G types the precision is assumed to be 1.
.n For d, i, o, u, x, X types then at least n digits are printed (padding with zeros if
necessary).
For f, e, E types specifies the number of digits after the decimal point.
For g or G types specifies the number of significant digits to print.
For s type specifies the maximum number of characters to print.
Modifier:
A modifier changes the way a conversion specifier type is interpreted.
Page 134
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
[type] Output
e, E Type double printed as [-]d.dddeñdd where there is one digit printed before the decimal
(zero only if the value is zero). The exponent contains at least two digits. If type is E then
the exponent is printed with a capital E.
g, G Type double printed as type e or E if the exponent is less than -4 or greater than or equal to
the precision. Otherwise printed as type f. Trailing zeros are removed. Decimal point
character appears only if there is a nonzero decimal digit.
s Type pointer to array. String is printed according to precision (no precision prints entire
string).
n The argument must be a pointer to an int. Stores the number of characters printed thus far
in the int. No characters are printed.
% A % sign is printed.
Page 135
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
Assignment suppressor:
Causes the input field to be scanned but not stored in a variable.
Width:
The maximum width of the field is specified here with a decimal value. If the input is smaller than
the width specifier (i.e. it reaches a nonconvertible character), then what was read thus far is
converted and stored in the variable.
Modifier:
A modifier changes the way a conversion specifier type is interpreted.
[type] Input
d Type signed int represented in base 10. Digits 0 through 9 and the sign (+ or -).
i Type signed int. The base (radix) is dependent on the first two characters. If the first
character is a digit from 1 to 9, then it is base 10. If the first digit is a zero and the second
digit is a digit from 1 to 7, then it is base 8 (octal). If the first digit is a zero and the second
character is an x or X, then it is base 16 (hexadecimal).
o Type unsigned int. The input must be in base 8 (octal). Digits 0 through 7 only.
u Type unsigned int. The input must be in base 10 (decimal). Digits 0 through 9 only.
x, X Type unsigned int. The input must be in base 16 (hexadecimal). Digits 0 through 9 or A
through Z or a through z. The characters 0x or 0X may be optionally prefixed to the value.
e, E, f, Type float. Begins with an optional sign. Then one or more digits, followed by an optional
g, G decimal-point and decimal value. Finally ended with an optional signed exponent value
designated with an e or E.
s Type character array. Inputs a sequence of non-white space characters (space, tab,
carriage return, new line, vertical tab, or form feed). The array must be large enough to
hold the sequence plus a null character appended to the end.
Page 136
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
[type] Input
[...] Type character array. Allows a search set of characters. Allows input of only those
character encapsulated in the brackets (the scan set). If the first character is a carrot (^),
then the scan set is inverted and allows any ASCII character except those specified
between the brackets. On some systems a range can be specified with the dash character
(-). By specifying the beginning character, a dash, and an ending character a range of
characters can be included in the scan set. A null character is appended to the end of the
array.
c Type character array. Inputs the number of characters specified in the width field. If no
width field is specified, then 1 is assumed. No null character is appended to the array.
p Pointer to a pointer. Inputs a memory address in the same fashion of the %p type
produced by the printf function.
n The argument must be a pointer to an int. Stores the number of characters read thus far in
the int. No characters are read from the input stream.
Page 137
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
References
Websites
http://refcards.com/refcards/c/c-refcard-letter.pdf
http://cm.bell-labs.com/cm/cs/who/dmr/chist.html
http://www.lysator.liu.se/c/bwk-tutor.html#introduction
http://www.acm.uiuc.edu/webmonkeys/book/c_guide/
Books
Deitel & Deitel, “C How to Program”, Third Edition, Prentice Hall
Byron Gottfried, “Programming in C”, Tata McGraw Hill
R.G.Dromey, “How to solve it by Computer”, Eastern Economy Edition
Al Kelley, Ira Pohl, “A Book on C”, Fourth Edition, Pearson Education Asia
Page 138
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected
Problem Solving and C Programming
STUDENT NOTES
Page 139
©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved
C3: Protected