Handout: Problem Solving and
'C' Programming
Version: PSC/Handout/1107/1.0 Date: 16-11-07
Cognizant 500 Glen Pointe Center West Teaneck, NJ 07666 Ph: 201-801-0233 www.cognizant.com
TABLE OF CONTENTS
About this Document ... 6
Target Audience ... 6
Objectives ... 6
Pre-requisite ... 6
Session 2: Introduction to Problem Solving and Programming Languages ... 7
Learning Objectives ... 7
Problem Solving Aspect ... 7
Program Development Steps ... 8
Introduction to Programming Languages ... 14
Types and Categories of Programming Languages ... 15
Program Development Environments ... 18
Summary ... 19
Test your Understanding ... 19
Session 3: Introduction to C Programming Language ... 21
Learning Objectives ... 21
Introduction to C Language ... 21
Evolution and Characteristics of C Language ... 21
Structure of a C Program ... 23 C Compilation Model ... 24 C Fundamentals ... 25 Character Set ... 25 Keywords ... 26 Identifiers ... 26 Data Types ... 26 Variables ... 28 Constants ... 29 Operators ... 30 Expressions ... 32 Type Casting ... 33
Input and Output Statements ... 35
Try It Out ... 39
Summary ... 39
Session 5: Selection and Control Structures ... 41
Learning Objectives ... 41
Basic Programming Constructs ... 41
Sequence ... 42
Selection Statements ... 42
‘if’ Statement ... 42
Conditional / Ternary / ?: Operator ... 44
Switch Statement ... 45
Iteration Statements ... 46
‘for’ statements ... 46
‘while’ statement ... 48
‘do - while’ statement ... 48
Break, Continue Statements ... 49
Try It Out ... 50
Summary ... 51
Test your Understanding ... 51
Session 7: Arrays and Strings ... 53
Learning Objectives ... 53
Need for an Array ... 53
Memory Organization of an Array ... 53
Declaration and Initialization ... 54
Basic Operation on Arrays ... 55
Multi-dimensional Array ... 56 Strings ... 58 String Functions ... 59 Character Functions ... 61 Try It Out ... 61 Summary ... 63
Test your Understanding ... 63
Session 9: Functions ... 65
Learning Objectives ... 65
Need for Functions ... 65
Function Prototype ... 66
Function Definition ... 67
Function Call ... 69
Passing Arguments ... 70
Try It Out ... 75
Summary ... 77
Test your Understanding ... 77
Session 10: Functions/Structures and Unions... 79
Learning Objectives ... 79
Storage Classes ... 79
Command Line Arguments ... 82
Introduction to Structures and Unions ... 83
Declaration and Initialization ... 84
Structures and Arrays ... 87
Structures and Functions ... 88
Try It Out ... 89
Summary ... 90
Test your Understanding ... 90
Session 14: Structures and Unions / Files and Preprocessor directives ... 92
Learning Objectives ... 92 Unions ... 92 Union of Structures ... 93 Enumeration ... 94 Typedef Statement ... 95 Introduction to Files ... 95 File Operations ... 96 Character I/O ... 98 String I/O ...100 Numeric I/O ...100 Formatted I/O ...101 Block I/O ...102 Try It Out ...104 Summary ...106
Test your Understanding ...106
Session 15: Files and Preprocessor directives / Pointers ...108
Learning Objectives ...108
Random File Operations ...108
Preprocessor Directives ...109
Introduction to Pointers ...115
Pointer Arithmetic ...116
Pointers and Arrays ...117
Try It Out ...123
Summary ...125
Test your Understanding ...125
Session 17: Pointers ...127
Learning Objectives ...127
Functions and Pointers ...127
Structures and Pointers ...129
Dynamic Memory Allocation ...130
Try It Out ...133
Summary ...136
Test your Understanding ...136
Syntax Summary ...138
References ...151
Websites ...151
Books ...151
Introduction
About this Document
This document provides the following topics:
Problem solving concepts
An introduction to C programming language
Basic concepts of C programming language
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
Session 2: Introduction to Problem Solving and
Programming Languages
Learning Objectives
After completing this session, you will be able to:
Explain the Problem Solving Aspect
Identify the steps involved in program development
Know about the Programming Languages and it’s types and categories
Understand the Program Development Environments
Problem Solving Aspect
Problem solving is a creative process. It is an act of defining a problem, determining the cause of the problem, identifying, prioritizing, and selecting alternatives for a solution and implementing a solution.
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
Program Development Steps
The various steps involved in Program Development are:
o Defining or Analyzing the problem o Design (Algorithm)
o Coding
o Documenting the program
o Compiling and Running the Program o Testing and Debugging
o Maintenance
Analyzing or Defining the Problem
The problem is defined by doing a preliminary investigation. Defining a problem helps us to understand the problem clear. It is also known as Program Analysis.
Tasks in defining a problem:
o Specifying the input requirements o Specifying the output requirements o Specifying the processing requirements
Specifying the input requirements
Determine the inputs required and source of the data. The input specification is obtained by answering the following questions:
o What specific values will be provided as input to the program? o What format will the values be?
o For each input item, what is the valid range of values that it may assume? o What restrictions are placed on the use of these values?
Specifying the output requirements
Describe in detail the output that will be produced. The output specification is obtained by answering the following questions:
o What values will be produced? o What is the format of these values?
o What specific annotation, headings, or titles are required in the report? o What is the amount of output that will be produced?
Specifying the Processing Requirements
Determine the processing requirements for converting the input data to output. The processing requirement specification is obtained by answering the following questions:
o What is the method (technique) required in producing the desired output? o What calculations are needed?
Example 2.1 Find the factorial of a given number
Input: Positive valued integer number Output: Factorial of that number
Process: Solution technique which transforms input into output. Factorial of a number can be calculated by the formula n! = 1*2*3*4….*n
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. A well designed program is more likely to be:
Easier to read and understand later
Less of bugs and errors
Easier to extend to add new features
Easier to program in the first place
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
Top-down design has the following advantages:
Breaking up the problem into parts helps us to clarify what is to be done
At each step of refinement, the new parts become more focussed and, therefore, easier to design
Modules may be reused
Breaking the problem into parts allows more than one person to work on the solution simultaneously
Algorithm (Developing a Solution technique)
An algorithm is a step-by-step description of the solution to a problem. It is defined as an ordered sequence of well-defined and effective operations which, when carried out for a given set of initial conditions, produce output, and terminate in a finite time. The term “ordered sequence” specifies, after the completion of each step in the algorithm, the next step must be unambiguously defined. An algorithm must be:
Definite
Finite
Precise and Effective
Implementation independent ( only for problem not for programming languages)
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
Example 2.2: Algorithm for finding factorial of a given number
Step 1: Start
Step 2: Initialize factorial to be 1, i to be 1 Step 3: Input a number n
Step 4: Check whether the number is 0. If so report factorial is 1 and goto step 9 Step 5: Repeat step 6 through step 7 n times
Step 6: Calculate factorial = factorial * i Step 7: Increment i by 1
Step 8: Report the calculated factorial value Step 9: Stop
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.
Example 2.3: Pseudo Code for finding factorial of a given number
Step 1: START
Step 2: DECLARE the variables n, fact, i Step 2: SET variable fact =1 and i =1
Step 3: READ the number n Step 4: IF n = 0 then
Step 4.1: PRINT factorial = 1 Step 4.2: GOTO Step 9
Step 5: WHILE the condition i<=n is true, repeat Step 6 through Step 7 Step 6: COMPUTE fact = fact * i
Step 7: INCREMENT i by 1 Step 8: PRINT the factorial value Step 9: STOP
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 Start, End
Represents Input, Output data
Represents Process (actions, calculations)
Represents Decision Making
Represents Pre-defined Process / module
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).
Represents control flow
Example 2.4: Flow Chart for finding factorial of a given number
Print 1 Declare the variables
n, fact, i
Initialize fact =1,i =1
Read n If n=0 0 If i<=n fact = fact * i i = i + 1 True False True False START Print fact STOP 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.
Documenting the Program
Documentation explains how the program works and how to use the program. Documentation can be of great value, not only to those involved in maintaining or modifying a program, but also to the programmers themselves. Details of particular programs, or particular pieces of programs, are easily forgotten or confused without suitable documentation.
Documentation comes in two forms:
External documentation, which includes things such as reference manuals, algorithm descriptions, flowcharts, and project workbooks
Internal documentation, which is part of the source code itself (essentially, the declarations, statements, and comments)
Compiling and Executing the Program
Compilation is a process of translating a source program into machine understandable form. The compiler is system software, which does the translation after examining each instruction for its correctness. The translation results in the creation of object code.
After compilation, Linking is done if necessary. Linking is the process of putting together all the external references (other program files and functions) that are required by the program. The program is now ready for execution.
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.
The Boundary (or Extreme) Cases
How does the algorithm perform at the extremes of the valid cases?
The Unusual Cases
What happens when the input data violates the normal conditions of the problem or represent unusual condition?
The Invalid Cases
How does the algorithm react for data which are patently illegal or completely meaningless? 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)
Introduction to Programming Languages
What is a Programming Language?
Computer Programming is an art of making a computer to do the required operations, by means of issuing sequence of commands to it.
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.
Why Study Programming Languages?
The design of new programming languages and implementation methods have been evolved and improved to meet the change in requirements. Thus, there are many new languages.
The study of more than one programming language helps us:
to master different programming paradigms
to enhance the skills to state different programming concepts
to understand the significance of a particular language implementation
to compare different languages and to choose appropriate language
to improve the ability to learn new languages and to design new languages
Types and Categories of Programming Languages
Types of Programming Languages
There are two major types of programming languages:
Low Level Languages
High Level Languages
Low Level Languages
The term low level refers closeness to the way in which the machine has been built. Low level languages are machine oriented and require extensive knowledge of computer hardware
architecture and its configuration. Low Level languages are further divided in to Machine language and Assembly language.
(a) Machine Language
Machine Language is the only language that is directly understood by the computer. It does not need any translator program. The instructions are called machine instruction (machine code) and it is written as strings of 1's (one) and 0’s (zero). When this sequence of codes is fed in to the computer, it recognizes the code and converts it in to electrical signals.
For example, a program instruction may look like this: 1011000111101
Machine language is considered to be the first generation language. Because of it design, machine language is not an easy language to learn. It is also difficult to debug the program written in this language.
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
(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 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.
High Level Languages
High level languages are the simple languages that use English like instructions and mathematical symbols like +, -, %, /, for its program construction. In high level languages, it is enough to know the logic and required instructions for a given problem, irrespective of the type of computer used.
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).
Advantages of High Level Languages
High level languages are easy to learn and use
Categories of programming languages 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
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.
Artificial Intelligence Languages (AI)
The first step towards the development of AI languages commenced with the evolution of IPL (Information Processing Language) by the Rand Corporation. The major breakthrough occurred, when John McCarthy of MIT designed LISP (List Processing) for the IBM 704. Later, more AI languages like SNOBOL & PROLOG were designed.
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.
What makes a Good Language?
Every language has its strengths and weaknesses.
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.
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.
Cost of use: Cost of use is measured on different languages like:
Cost of program execution: Optimizing compilers, efficient register allocation, design
of efficient run-time support mechanisms are all factors that contribute towards cost of program execution. This is highly critical for large programs that will be executed continuously.
Cost of Program creation, testing & use: This implies design, coding, testing, usage
& maintenance solutions for a problem with minimum investment of programmer time & energy.
Cost of Program Maintenance: The highest cost involved in any program is the total life-cycle
costs including development costs & the cost of maintenance of the program while it is in production use.
Program Development Environments
The environment under which a program is designed, coded, tested & debugged is called Host
Environment. The external environment which supports the execution of a program is termed as Operating or Target Environment. Host and Target environment may be different for a program or
application.
Programming Environments (Host Environment)
It is the environment in which programs are created and tested. It tends to have less influence on language design than the operating environment in which programs are expected to be executed. The production of programs that operate reliably and efficiently is made much simpler by a good programming environment and by a language that allows the use of good programming tools and practices.
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.
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.
Embedded System Environments
An embedded computer system is used to control part of a larger system such as an industrial plant (computerized machineries) or an aircraft. The computer system will be an integral part of the larger system, failure of which would imply failure of the larger system as well.
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
Test your Understanding
1. Represent the following problem in top-down design.
Planning a tour.
2. Give the algorithm, pseudo code and flowchart for the following problem:
Sort a list of numbers in ascending order.
3. Distinguish between testing and debugging. 4. State whether the following is True or False :
a) Assembly language is a second generation language.
5. What is meant by portability of programs? a. Easy to carry from place to place
b. Transportability of resulting program within machine folders c. It can run on any machine
d. The program needs to be compiled in every machine
Answers:
3. Testing is to find errors in programs and debugging is to correct their root causes 4. True, True
Session 3: Introduction to C Programming Language
Learning Objectives
After completing this session, you will be able to:
Explain the Evolution of C Language
Describe the Structure of a C Program
Know about the Compilation Model
Explain the Basic elements of C language
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 and Characteristics of C Language
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.
Prior to C, there are two broad types of languages:
Applications languages: Basic and COBOL, which are portable but inefficient.
Systems languages: Low Level and Assembly language, which are efficient but non-portable.
‘C‘ is developed in such a way that it is efficient and portable. C++, Java, C# conserve C syntax.
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.
Example 3.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.
Example 3.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 )
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.
auto double int Long
break else long Switch
case enum register typedef
char extern return Union
const float short unsigned
continue for signed Void
default goto sizeof volatile
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 3.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.
ANSI C supports two classes of data types:
Primary / Fundamental / Basic / Primitive data types
Primary / Fundamental / Basic / Primitive data types
C uses the following basic data types: o int Æ integer quantity
o char Æ character (stores a single character) o float Æ single precision real (floating point) number o double Ædouble precision real (floating point) number
Typical memory requirements for these data types are given below: The actual number of bytes used in the internal storage for these data types depends on the machine being used. o int Æ 2 bytes
o char Æ 1 byte o float Æ 4 bytes o double Æ 8 bytes
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, o short
o long o signed o 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.
For example, int = 2 bytes, short int may be 1 byte or 2 bytes int = 2 bytes, long int may be 2 bytes or 4 bytes
Range of values represented by data types on 16-bit machine
Type Meaning Size Range
unsigned char Unsigned character
(positive) 8 bits 0 to 255
signed char
char Represents single character. 8 bits -128 to 127 unsigned int
unsigned short int
Represents positive
Type Meaning Size Range Short
signed short short int
signed short int int
represents both positive and
negative integer quantity 16 bits -32,768 to 32,767
unsigned long represents positive long
integer 32 bits 0 to 4,294,967,295
long signed long long int
signed long int
Represents both positive
and negative long integer 32 bits -2,147,483,648 to 2,147,483,647
Float Floating Point Number. 32 bits 3.4 * (10-38) to 3.4 * (10+38)
Double A more accurate
floating-point number than float 64 bits 1.7 * (10
-308
) to 1.7 * (10+308)
long double Increases the size of double. 80 bits 3.4 * (10-4932) to 1.1 * (104932)
void Defines an empty data type
which can then be
associated with some data types. It is useful with pointers.
Derived Data Types
Derived data types are a combination of primitive data types. They are used to represent a collection of data. They are:
Arrays Structures Unions Enumerated Pointers 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.
General form:
var_data_type list variables;
Example 3.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 3.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. There are two types of constants:
Symbolic constants
Constant variables, also called read-only variables.
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.
A symbolic constant is defined as follows: #define MAX 100
Each reference to ‘MAX’ in program will cause the value of 100 to be substituted. This value cannot be changed by the program.
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 3.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
< Less than
<= Less than or equals to
> Greater than
>= Greater than or equals to
== Equals to
!= not equals to
These operators are used to form relational expressions, which evaluates to either true or false. (true – 1, false – 0)
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.
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
Increment and decrement operators
++ may be in the form of pre increment or post increment (++ k: pre increment, k++: post increment)
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)
Conditional operator (ternary operator)
?: used to carry out simple conditional checking
Example: big = (a>b)? a: b
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
These operators are used to access machine at bit level.
Special operators
& Address operator
* Indirection operator
comma Comma operator
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.
It is necessary to be careful of the meaning of expressions such as a - b / c because we may want the effect as either (a - b) / c or a - (b / c).
From high priority to low priority the order for all C operators is given below:
Operator Name Association
( ) [ ] -> . Parentheses, Index, member access operators Left to Right ! – sizeof()
(Typecast) * & Logical NOT, unary minus, indirection, address Right to Left ++ -- Increment and decrement operators. Right to Left
* / % Multiplicative operators. Left to Right
+ - Additive operators. Left to Right
< > <= >= Inequality comparators. Left to Right
== != Equality comparators Left to Right
&& Logical AND. Left tot Right
|| Logical OR. Left to Right
?: Conditional. Right to Left
= op= Assignment. Right to Left
, Comma Left to Right
Example 3.7: Operators
Let a=1, b=2, c=3 (1) a* b%c+1
is equivalent to ((a*b) %c)+1 which is equal to 3 (2) ++a*b – c--
is equivalent to ((++a)*b) - (c--) which is equal to 1
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).
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.
C allows multiple assignment statements using =. 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 3.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,
o float to int assignment causes truncation of the fractional part. o double to float causes round of digits.
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;
Another two terms associated with type casting are:
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 3.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 3.10
float to (int or char) - narrowing (char or int) to float - widening
The following examples show different kinds of expressions:
Example 3.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*/
Example 3.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)
Input and Output Statements
Reading, processing, and printing of data are the three essential functions of a computer program. There are two methods of providing data to the program variables. One method is to assign values to variables through the assignment statements. Another method is to use input functions, which can get data from the keyboard (standard input-stdin).
There are two types of Input and Output (I/O) statements: Unformatted I/O statements and Formatted I/O statements.
Unformatted Input 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 3.13
char ch; ch = getchar();
getche(); - character input from console & echoes the character.
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:
gets(stringvariable); /* string is represented as character array */
Example 3.14
char ch[5]; gets(ch);
Unformatted Output statements
Character Output putchar()
This function displays a single character in the standard output (stdout), monitor.
General Form: putchar(char variable); Example 3.15 char ch; ch = getchar(); putchar(ch); String Output puts()
General Form: puts(str); Example 3.16 char ch[5]; gets(ch); puts(ch);
Formatted I/O Statements
Formatted input refers to an input data that has been arranged in a particular format. C has a special formatting character (%). A character following this defines the format for a value. Some of the format specifiers are given below:
%c – character %d – integer %f, %e, %g – float %s – string %ld – long integer %o – octal %x – hexadecimal %hd – short integer
%[..] – string of specified characters %u – unsigned
General Form:
“%-+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)
Formatted Input Statement scanf()
scanf () function is used to read formatted data items.
General Form:
scanf (“format string”, list of variables);
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.
Example 3.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);
Formatted Output Statement 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 3.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);
sprintf()
sprintf() function is used to output values to a string.
General Form:
sprintf (str, “format string”, list of variables);
Try It Out
Problem Statement:
Write a program to find out value for an expression
Code: #include <stdio.h> main() { int z,x=5,y=-10,a=4,b=2; z = x++ - --y * b / a; printf("The Value of z : %d\n",z); getchar(); }
Refer File Name: <sesh3_1.c> to obtain soft copy of the program code
How It Works:
The program assigns the value and substitute in the expression, then based on the operator precedence, the value get computed and prints on the screen
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.
Test your Understanding
1. Which of the following are valid identifiers? a. Emp_name
b. “total” c. main d. total-marks
2. a = (b = 2) + (c=3); Is the statement valid?
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;
4. What is ternary operator in C?
5. What is the difference between getche() and getch()? 6. If, the scanf() statement contains the following control :
“%d \n %d”
Which of the following set of inputs will successfully read ? a. 4 5
b. 4 5
7. What is the output of the following code? int a , b = printf (“welcome”); printf (“%d “,b);
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. 6. All are valid.
Session 5: Selection and Control Structures
Learning Objectives
After completing this session, you will be able to:
Write a Simple Program
Write program using Conditional statements
Write program using Looping and Iteration
Basic Programming Constructs
The basic programming constructs are sequence, selection, and iteration (looping). In a sequence construct, the instructions are executed in the same order in which they appear in the program. In a selection structure, the control flow can be altered by evaluating conditions. In an iterative structure, a group of instructions is executed repeatedly, until some condition is satisfied.
Statements in C
Simple Statement (expression statement)
An expression terminated by a semicolon (;) is termed to be a simple statement (or expression statement).
Example 5. 1
a=8; c=a+b;
; Æ Null statement
Compound Statements / Blocks
Compound statements are used to group the statements into a single executable unit. It consists of one or more individual statements enclosed within the braces { }.
Example 5. 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.<Delete the arrow brackets while entering actual names and text. Insert more subheadings where required by copying one already done.
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.
The if statement has three basic forms:
Simple if-else Nested if if-else if ladder Simple “if-else” General Form: if (expression) { statements1; } [ else { statements2; } ] statements3;
[ ] is used to represent the optional usage of ‘else’ block.
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
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.
Example 5.3: Program to find maximum of two numbers.
if (a<b)
max = b; else
max = a;
printf(“ max = %d” ,max); 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]
Nested ‘if’ Statement
Body of an ‘if’ statement contains another ‘if’ statement.
General Form: if (expression) { statements1; if (expression) statements-1; } else { statements2; if (expression) statements-2; } Example 5.4
Program to find the maximum of 3 numbers. if (a>b)
if (a>c)
printf(“largest = %d”, a); else
else
if (c>b)
printf (“largest = %d”,c); else
printf (“largest = %d”,b);
‘if… else if’ Ladder Statement 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 5.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”);
Conditional / Ternary / ?: Operator
This operator takes 3 expressions / operands. It is a more efficient form for expressing simple if statements.
General form:
[variable = ]expr1? expr2: expr3; This simply states:
if (expr1 is true) then expr2 else expr3
Where:
o expr2 is evaluated, if the value of expr1 is non-zero (true part). o expr3 is evaluated, if the value of expr1 is zero (false part).
Example 5.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.
Example 5.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.
These three expressions are separated by semicolons.
Example 5.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); }
Nested ‘for’ statement
There are many situations in which a loop statement contains another loop statement. Such loops are called nested loops.
Example 5.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.