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

Problem Solving and C Programming

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 Test your Understanding ............................................................................................................39
Page 2 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Problem Solving and C Programming

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 Functions and Arrays ..................................................................................................................73
Page 3 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

........... Cognizant Technology Solutions..........................................................................................................................................................................................................................................................................................................................77 Test your Understanding ................95 File Operations ..........................79 Storage Classes ................................................................................................88 Try It Out ............................................92 Union of Structures ..........................................................90 Test your Understanding ..............................................................................................................79 Command Line Arguments ...............................................90 Session 14: Structures and Unions / Files and Preprocessor directives ...........................................................................................................................82 Introduction to Structures and Unions ...................................................................................................................................................................................................................................................................... All Rights Reserved C3: Protected ....................................................................108 Learning Objectives ...........87 Structures and Functions ...........................................75 Summary .......................96 Character I/O .....................................106 Session 15: Files and Preprocessor directives / Pointers ...................................................................................................93 Enumeration ............115 Page 4 ©Copyright 2007.....................................................................................................................................................................................................................................................................................................................................................................................................................104 Summary ..................................................................................................................................................................................................................................89 Summary .................................................................................................................108 Random File Operations ..........................77 Session 10: Functions/Structures and Unions.............................................................................................79 Learning Objectives ...................................................................................................102 Try It Out .....92 Unions................................................................................................94 Typedef Statement ..........................84 Structures and Arrays .....................................................................................100 Formatted I/O.............................108 Preprocessor Directives ..........................................................................................98 String I/O..............................................................................................115 Declaration and Initialization...........................................................................................109 Introduction to Pointers ..............................................................................................................................................................................................................................................................................................................................................................................................100 Numeric I/O.............................................................83 Declaration and Initialization...................................................................................................................................................................................92 Learning Objectives ..95 Introduction to Files .................................................................................106 Test your Understanding ..........................................................................................................................................................................................................................101 Block I/O ........................Problem Solving and C Programming Try It Out .........................................................................................................................................................................................................................................

.................................. All Rights Reserved C3: Protected ......................................................Problem Solving and C Programming Pointer Arithmetic ..............................................................................................................133 Summary ..............................................................................................................................................138 References ........................................................................................................................................................................................................136 Syntax Summary ......................................................................................125 Session 17: Pointers .................................................127 Learning Objectives ...........................................................................................................127 Functions and Pointers ...........................................................................123 Summary .........151 Websites ......................................................................................130 Try It Out ......................................................................117 Try It Out ...116 Pointers and Arrays ....136 Test your Understanding ...............................................127 Structures and Pointers ......................................................................................................................................................125 Test your Understanding ............................................................................................................................152 Page 5 ©Copyright 2007........................................................................................129 Dynamic Memory Allocation .................................................................................................................................................................................................................................................................................................................. Cognizant Technology Solutions................................................................................................................................................................................................................................................................................................................................................................151 STUDENT NOTES: .........................151 Books ............................

Problem Solving and C Programming 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 This module does not require any pre-requisites Page 6 ©Copyright 2007. Cognizant Technology Solutions. All Rights Reserved C3: Protected .

It is an act of defining a problem. 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. 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. Cognizant Technology Solutions. Some of the well known strategies are: Divide and Conquer Greedy Method Dynamic Programming Backtracking Branch and Bound Page 7 ©Copyright 2007. prioritizing. determining the cause of 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. 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. identifying. We have to be sure that the past experience does not hinder us in developing new methodology or technique for solving a problem. All Rights Reserved C3: Protected . To understand the problem.Problem Solving and C Programming Session 2: Introduction to Problem Solving and Programming Languages Learning Objectives After completing this session.

It is also known as Program Analysis. headings. or titles are required in the report? 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.Problem Solving and C Programming Program Development Steps The various steps involved in Program Development are: o o o o o o o Defining or Analyzing the problem Design (Algorithm) Coding Documenting the program Compiling and Running the Program Testing and Debugging 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. The output specification is obtained by answering the following questions: o o o o What values will be produced? What is the format of these values? What specific annotation. Tasks in defining a problem: o o o Specifying the input requirements Specifying the output requirements 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 o o o What specific values will be provided as input to the program? What format will the values be? For each input item. what is the valid range of values that it may assume? What restrictions are placed on the use of these values? Specifying the output requirements Describe in detail the output that will be produced. The processing requirement specification is obtained by answering the following questions: o o o What is the method (technique) required in producing the desired output? What calculations are needed? What are the validation checks that need to be applied to the input data? Page 8 ©Copyright 2007. All Rights Reserved C3: Protected . Cognizant Technology Solutions.

until the last module is executed Each module should be of manageable size.Problem Solving and C Programming Example 2. so that the logic flow of the program is easy to follow When the program is executed. Program Design is both a product and a process. consider the following guidelines: A problem is divided it into smaller logical sub-problems. several design methodologies can be applied.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. 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. 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. easier to design Modules may be reused Breaking the problem into parts allows more than one person to work on the solution simultaneously Page 9 ©Copyright 2007. 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.*n Design A design is the path from the problem to a solution in code. the new parts become more focussed and. Factorial of a number can be calculated by the formula n! = 1*2*3*4…. 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. 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. it must be able to move from one module to the next in sequence. All Rights Reserved C3: Protected . Cognizant Technology Solutions. An important approach is Top-Down programming design. therefore. While applying top-down design to a given problem.

produce output. 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. The term “ordered sequence” specifies. Example 2. when carried out for a given set of initial conditions. Programmers make initial attempt to the solution and review it.3: Pseudo Code for finding factorial of a given number Step 1: START Step 2: DECLARE the variables n. to test its correctness. after the completion of each step in the algorithm. The errors identified leads to insertions. i Step 2: SET variable fact =1 and i =1 Page 10 ©Copyright 2007. or modifications to the existing algorithm.2: Algorithm for finding factorial of a given number Step 1: Start Step 2: Initialize factorial to be 1. a novice programmer should not view developing algorithm as a single-step operation Example 2. deletions. the algorithm is essentially correct and ready to be executed. 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. This refining continues until the programmer is satisfied that. All Rights Reserved C3: Protected . The more experience we gain in developing an algorithm. the next step must be unambiguously defined. It is defined as an ordered sequence of well-defined and effective operations which. It is an outline of a program written in English or the user's natural language. However. Cognizant Technology Solutions. the closer our first attempt will be to a correct solution and the less revision will be required. fact.Problem Solving and C Programming Algorithm (Developing a Solution technique) An algorithm is a step-by-step description of the solution to a problem. i to be 1 Step 3: Input a number n Step 4: Check whether the number is 0. and terminate in a finite time. but omits language-specific syntax.

Connector Symbol represents the exit to. It uses different symbols to represent the sequence of operations. 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. All Rights Reserved C3: Protected . Page numbers are usually placed inside for easy reference. another part of the same flow chart.Problem Solving and C Programming Step 3: READ the number n Step 4: IF n = 0 then Step 4. The Document Symbol is used to represent any type of hard copy input or output (i. Typical flowchart symbols are given below: Represents Start. or entry from. Cognizant Technology Solutions. reports). Page 11 ©Copyright 2007. End Represents Input. It serves as a blueprint or a logical diagram of the solution to a problem. Output data Represents Process (actions.e. It is usually used to break a flow line that will be continued elsewhere.2: GOTO Step 9 Step 5: WHILE the condition i<=n is true.1: PRINT factorial = 1 Step 4. required to solve a problem. 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.

All Rights Reserved C3: Protected . Cognizant Technology Solutions.i =1 Read n True If n=0 0 Print 1 False If i<=n False True fact = fact * i i=i+1 Print fact STOP Coding Page 12 ©Copyright 2007. fact.Problem Solving and C Programming Represents control flow Example 2.4: Flow Chart for finding factorial of a given number START Declare the variables n. i Initialize fact =1.

not only to those involved in maintaining or modifying a program. Writing a program is called Coding. The program is now ready for execution. are easily forgotten or confused without suitable documentation. the executable object code is loaded into the computer’s memory and the program instructions are executed. requirements can be tested for its correctness. The translation results in the creation of object code. It is important to design test cases for abnormal input conditions. Cognizant Technology Solutions. statements. 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. Details of particular programs. Linking is done if necessary. Testing Testing is the process of executing a program with the deliberate intent of finding errors. During execution. Linking is the process of putting together all the external references (other program files and functions) that are required by the program. the declarations. which does the translation after examining each instruction for its correctness. flowcharts. After compilation. Program should be tested with all possible input data and control conditions. The logic that has been developed in the algorithm is used to write the program. but also to the programmers themselves. Then. Testing is needed to check whether the expected output matches the actual output.Problem Solving and C Programming An algorithm expressed in programming languages is called Program. algorithm descriptions. or particular pieces of programs. The compiler is system software. All Rights Reserved C3: Protected . Structured walk through is made to verify the design. Documenting the Program Documentation explains how the program works and how to use the program. and comments) Compiling and Executing the Program Compilation is a process of translating a source program into machine understandable form. Testing is done during every phase of program development. which includes things such as reference manuals. and project workbooks Internal documentation. which is part of the source code itself (essentially. Page 13 ©Copyright 2007. Documentation can be of great value. the design (algorithm. flow charts) can be tested for its exactness and efficiency. Initially. Documentation comes in two forms: External documentation.

and Pascal. Each programming language has a unique set of characters. Maintainability and modifiability are essential characteristics of every program. C. Some programmers use the terms “testing” and “debugging” interchangeably. Maintainability of the program is achieved by: Modularizing it Providing proper documentation for it Following standards and conventions (naming conventions. For many programmers. COBOL. The term programming languages usually refers to high-level languages. FORTRAN. All Rights Reserved C3: Protected . Cognizant Technology Solutions. Testing means detecting errors. Ada. Debugging Debugging is a process of correcting the errors. 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. debugging is the hardest part of programming because of improper documentation. debugging occupies as much as 50 percent of the total development time. Debugging means diagnosing and correcting the root causes. Debugging is the process of identifying their root causes. Maintenance Programs require a continuing process of maintenance and modification to keep pace with changing requirements and implementation technologies.Problem Solving and C Programming 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. On some projects. One of the ways to ensure the correctness of the program is by printing out the intermediate results at strategic points of computation. C++. A programming language can be defined as a vocabulary and set of grammatical rules for instructing the computer to perform specific tasks. Page 14 ©Copyright 2007. keywords and the syntax for organizing programming instructions. Programs may have logical errors which cannot be caught during compilation. This is called foolproof programming. but careful programmers distinguish between the two activities. by means of issuing sequence of commands to it. such as BASIC.

Because of it design. (It is already in machine understandable form) Disadvantages It is very difficult to write programs in machine language. a program instruction may look like this: 1011000111101 Machine language is considered to be the first generation language. it recognizes the code and converts it in to electrical signals.Problem Solving and C Programming Why Study Programming Languages? The design of new programming languages and implementation methods have been evolved and improved to meet the change in requirements. All Rights Reserved C3: Protected . When this sequence of codes is fed in to the computer. Advantage The program runs faster because no translation is needed. Thus. (a) Machine Language Machine Language is the only language that is directly understood by the computer. It does not need any translator program. Cognizant Technology Solutions. The instructions are called machine instruction (machine code) and it is written as strings of 1's (one) and 0’s (zero). It is also difficult to debug the program written in this language. machine language is not an easy language to learn. 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. The programmer has to know details of hardware to write program It is difficult to debug the program Page 15 ©Copyright 2007. Low Level languages are further divided in to Machine language and Assembly language. For example.

set of mnemonics (symbolic keywords) are used to represent machine codes. COBOL (Common Business Oriented Language) is mostly suitable for business oriented applications. Mnemonics are usually combination of words like ADD.Problem Solving and C Programming (b) Assembly Language In assembly language. Numerical calculations were the dominant form of application for these early machines. Compiler is a translator program which converts a program in high level language in to machine language. Cognizant Technology Solutions. for its program construction. A program written for one computer might not run in other computer. %. 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. In order to execute the programs written in assembly language. High Level Languages High level languages are the simple languages that use English like instructions and mathematical symbols like +. irrespective of the type of computer used. There are some numerical & mathematical oriented languages like FORTRAN (Formula Translation) and BASIC (Beginners All-purpose Symbolic Instruction Code). a translator program is required to translate it to the machine language. Assembly language is considered to be the second-generation language. /. These early machines were designed to solve numerical problems and were thought of as ELECTRONIC CALCULATORS. Page 16 ©Copyright 2007. SUB and LOAD etc. because there is one-to-one translation between assembly language program and its corresponding machine language program Disadvantages: Assembly languages are machine dependent. Higher level languages are problem-oriented languages because the instructions are suitable for solving a particular problem. All Rights Reserved C3: Protected . In high level languages. This translator program is called Assembler. 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. For example. it is enough to know the logic and required instructions for a given problem. -.

The syntax of a language should be such that programs may be written. but it does not lend itself very well to organize large programs. and the expertise of the programmer. Orthogonality makes a language easy to learn and write programs. Cognizant Technology Solutions. For example. 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. Many systems programming languages such as CPL & BCPL were designed. but it is complex and difficult to learn. the use of assembly language held on for years in the system area long after other application domains started to use higher-level languages. with every combination being meaningful.Problem Solving and C Programming Business Languages Business data processing was an early application domain developed after numerical applications. Systems Languages Because of the need of efficiency. This. The language should provide appropriate data structures. because there are fewer exceptions & special cases to remember. The choice of which language to use depends on the type of computer used. 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. operations. Orthogonality: This refers to the attribute of being able to combine various features of a language in all possible combinations. PASCAL is very good for writing wellstructured and readable programs. control structures and natural syntax for the problem to be solved. Later. which would be a business-oriented language that used English as much as possible for its notation. tested and maintained with ease. Simplicity and Unity: A programming Language provides. in turn. All Rights Reserved C3: Protected . Page 17 ©Copyright 2007. type of program. the US department of Defense sponsored a meeting to develop COMMON BUSINESS LANGUAGE (CBL). when John McCarthy of MIT designed LISP (List Processing) for the IBM 704. led to the formation of a Short Range Committee to develop COBOL. where high level languages also proceed to work effectively. The major landmark here is the development of UNIX. FORTRAN is a particularly good language for processing numerical data. but it is not as flexible as the C programming language. Following are the most important features that would make a programming language efficient and easy to use: Clarity. more AI languages like SNOBOL & PROLOG were designed. though not widely used. both a conceptual framework for thinking about algorithms and a means for expressing these algorithms. C++ embodies powerful object-oriented features. What makes a Good Language? Every language has its strengths and weaknesses. In 1959.

Program Development Environments The environment under which a program is designed. 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. testing & use: This implies design. Programming Environments (Host Environment) It is the environment in which programs are created and tested. 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. 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. All Rights Reserved C3: Protected . The external environment which supports the execution of a program is termed as Operating or Target Environment. efficient register allocation. Each poses different requirement on languages adapted for those environments. Cognizant Technology Solutions. 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. usage & maintenance solutions for a problem with minimum investment of programmer time & energy. Cost of Program creation. A language whose definition is independent of the features of a particular machine forms a useful base for the production of transportable programs.Problem Solving and C Programming Support for abstraction: Even with the most natural programming language for an application. the input data are collected in ‘batches’ on files and are processed in batches by the program. Target Environments Target environments can be classified into 3 categories – Batch Processing Environment. tested & debugged is called Host Environment. For example. 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. Page 18 ©Copyright 2007. coded. Batch-Processing Environments In batch-processing environments. Host and Target environment may be different for a program or application. the backup process on an organization. and Embedded System Environment. testing. Cost of use: Cost of use is measured on different languages like: Cost of program execution: Optimizing compilers. coding. It tends to have less influence on language design than the operating environment in which programs are expected to be executed. This is highly critical for large programs that will be executed continuously. Interactive Environment. design of efficient run-time support mechanisms are all factors that contribute towards cost of program execution.

Cognizant Technology Solutions. o o o Batch processing environment Interactive environment Embedded System environment Test your Understanding 1.Problem Solving and C Programming Interactive Environments In interactive environment. All Rights Reserved C3: Protected . debugging. coding. Top-down program design. word processing systems etc. testing. The computer system will be an integral part of the larger system. An algorithm is a sequence of unambiguous instructions for solving a problem. State whether the following is True or False : a) Assembly language is a second generation language. 3. The environment under which a program is designed. Summary Program development life cycle involves analysis. Distinguish between testing and debugging. Examples include database management systems. Page 19 ©Copyright 2007. 2. Give the algorithm. and maintenance. a program interacts directly with a user at a display console. coded. failure of which would imply failure of the larger system as well. tested & debugged is called Host environment (programming environment) The environment under which a program is executed is called Target environment. algorithm development. b) Programs written in high Level languages needs translation for executing them. Planning a tour. Represent the following problem in top-down design. by alternately sending output to the display & receiving input from the keyboard or mouse. 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. Two major types of programming languages are Low Level Languages and High Level Languages. compiling and running. Target environments can be classified into 3 categories. called Modules. documenting. 4. divides the problem into smaller logical sub problems. A programming language is a vocabulary and set of grammatical rules for instructing a computer to perform specific tasks. pseudo code and flowchart for the following problem: Sort a list of numbers in ascending order.

What is meant by portability of programs? a. All Rights Reserved C3: Protected . Transportability of resulting program within machine folders c. 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. c (it can run on any machine) Page 20 ©Copyright 2007.Problem Solving and C Programming 5. True. Easy to carry from place to place b. True 5. It can run on any machine d. Cognizant Technology Solutions.

Prior to C.Problem Solving and C Programming Session 3: Introduction to C Programming Language Learning Objectives After completing this session. It was evolved from ALGOL. Because of its flexibility and efficiency it is widely used for software development. there are two broad types of languages: Applications languages: Basic and COBOL. In 1970. It was then approved by the International standards Organization (ISO) in 1990. resulting in the construction of efficient programs. 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. Systems languages: Low Level and Assembly language. In 1967. The popularity of C led to the development of different versions of the language that were similar but often incompatible. in 1973. Its features allow the development of well-structured programs. which are efficient but nonportable. C had evolved into what is now known as “traditional C”. The committee approved a version of C in 1989 which is now known as ANSI C. The data types and control structures are directly supported by most computers. Evolution and Characteristics of C Language Evolution of C Language ALGOL was the first computer language to use a block structure. Ken Thompson created a language using many features of BCPL and called it ‘B’. American National Standards Institute (ANSI) appointed a technical committee to define a standard for C. UNIX operating system was coded almost entirely in C. To assure that the C language remains standard. which are portable but inefficient. Both BCPL and B were “typeless” system programming languages. BCPL. and B. All Rights Reserved C3: Protected . During 1970s. ‘B’ was used to create early versions of UNIX operating system at Bell Laboratories. The standard was updated in 1999. C uses many concepts of these languages and new features like data types. C was developed by Dennis Ritchie at Bell Laboratories in 1972. Page 21 ©Copyright 2007. Martin Richards developed a language called BCPL (Basic Combined Programming Language) primarily. for writing system software. Cognizant Technology Solutions.

All Rights Reserved C3: Protected . The following figure depicts the history of languages: Page 22 ©Copyright 2007. Java. C# conserve C syntax. Cognizant Technology Solutions.Problem Solving and C Programming ‘C‘ is developed in such a way that it is efficient and portable. C++.

The prototype of the user-defined functions (function declaration) is specified after the preprocessor directives. This section can have declarations for all the user-defined functions. Output and Processing statements. The preprocessor directives provide instructions to the preprocessor.extensive use of pointers for memory. Every C program must have one main() function. A function is a subroutine that includes one or more statements designed to perform a specific task. C program can be documented using these comment lines. C program can have any number of user-defined functions and they are generally placed immediately after the main() function. to include functions from the system library. These two parts must appear between the opening and the closing braces. to define the symbolic constants and macro. Page 23 ©Copyright 2007. The variables that are used in common by more than one function are called Global Variables and are declared in global declaration section. Cognizant Technology Solutions. called functions. All sections except the main() function may be absent when they are not required. preprocessor directives global declaration section main() { : } user-defined function definitions.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 . The program execution begins at the opening brace and ends at the closing braces. All Rights Reserved C3: Protected . Comments are enclosed within /* and */. The declaration part declares all the variables used in the executable part. array. structures and functions Structure of a C Program A C program can be viewed as a group of building blocks. The closing brace of the main function is the logical end of the program. although they may appear in any order. The executable portion of the main function will have three types of statements: Input. C is a case sensitive language. This function contains two parts: declaration part and executable part. All the statements in the declaration and executable parts end with a semicolon.

printf (“\n Program to find the sum of two numbers\n”). Cognizant Technology Solutions.num2. scanf(“%d%d”. All Rights Reserved C3: Protected . } C Compilation Model The C Compilation model describes the program development process in terms of language. printf(“\n The sum of two numbers is = %d”.&num2). printf(“\n Please enter 2 integer numbers”).1 /* Program to accept 2 integers from the keyboard as input.h> main( ) { int num1. printf (“\n The following data was input: %d & %d ”. It removes comments and empty lines in the program. sum = num1+num2.sum. &num1. sum). Page 24 ©Copyright 2007. calculate and print their sum */ #include <stdio.Problem Solving and C Programming Example 3. 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 #. num2). num1.

Special characters Escape Sequences: Escape sequences are non printable characters.o suffix and on MSDOS files with . ? . which begin with backward slash and followed by one or more special characters.Z o Lowercase a…. . External variable references are resolved here. % . The characters in C are grouped into the following categories: Letters o Uppercase A….defines a symbolic name or constant. Assembler The assembler creates the object code. file with a. #include <math.Problem Solving and C Programming Example 3. Operators and Expression. to create an executable file. numbers and expressions.. C Fundamentals Basic elements of C language constitute Character set.2 #include -. 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).includes contents of a named file.standard library I/O file #define -. #include <stdio. All Rights Reserved C3: Protected . Character Set Character set defines the characters that are used to form words. the link editor combines these functions with main(). Blank spaces etc. Cognizant Technology Solutions.h> -. +.standard library maths file. Identifiers. The frequently used escape sequences are given below: o o o o o o o o Horizontal tab ( \t ) Vertical tab ( \v ) Carriage return (\r ) New line ( \n ) Form feed (\f ) Back Space ( \b ) Back Slash ( \\ ) Null ( \0 ) Page 25 ©Copyright 2007.OBJ indicates object code files.z Digits o o All decimal digits 0…9 =.] Link Editor If a source file references library functions or functions defined in other source files. [On UNIX.h> -. These files are usually called header files.

Problem Solving and C Programming Keywords Keywords have standard. constants. and the type of operation that can be performed on a particular data item. followed by the combinations of alphabets and digits. An Identifier can be of arbitrarily long. predefined meanings in C. the number of bytes to be reserved in memory. No special character is allowed except underscore (_).3 Valid identifiers : Invalid identifiers: sum_2_nos 5subjects basic_pay emp name _amount #ofstudents Data Types Data types are used to indicate the type of value represented or stored in a variable. ANSI C supports 32 keywords. auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static Long Switch typedef Union unsigned Void volatile While Identifiers Identifiers are names given to various programming elements such as variables. These keywords can be used only for their intended purpose and they cannot be used as programmer-defined identifiers. Cognizant Technology Solutions. All keywords must be written in lowercase. and functions. It should start with an alphabet. Keywords serve as basic building blocks for program statements. The following table shows the list of keywords. the range of values that can be represented in memory. All Rights Reserved C3: Protected . ANSI C supports two classes of data types: Primary / Fundamental / Basic / Primitive data types Derived / Compound data types Page 26 ©Copyright 2007. Example 3. Some implementation of C recognizes only the first eight characters and some other recognize first 32 characters.

They are. o o o o 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. Type Qualifiers Data type qualifiers add additional information to the data types. Similarly.535 Page 27 ©Copyright 2007. 8 bits Represents positive integer numbers -128 to 127 16 bits 0 to 65. int = 2 bytes. For example. Cognizant Technology Solutions. long int may be 2 bytes or 4 bytes Range of values represented by data types on 16-bit machine Type unsigned char signed char char unsigned int unsigned short int Meaning Unsigned character (positive) Size 8 bits 0 to 255 Range Represents single character. short int may require less space than an int or it may require the same amount of memory. Here. short int may be 1 byte or 2 bytes int = 2 bytes.Problem Solving and C Programming Primary / Fundamental / Basic / Primitive data types C uses the following basic data types: o o o o int char float double integer quantity character (stores a single character) single precision real (floating point) number double precision real (floating point) number Typical memory requirements for these data types are given below: o o o o int char float double 2 bytes 1 byte 4 bytes 8 bytes The actual number of bytes used in the internal storage for these data types depends on the machine being used. a long int may require the same amount of memory as an int or it may require more memory. never less than int. The basic data types can be augmented by the use of data type qualifiers. All Rights Reserved C3: Protected .

147. 80 bits Defines an empty data type which can then be associated with some data types. The value represented by the identifier may be changed during the execution of the program.768 to 32.4 * (10-38) to 3.967.7 * (10+308) 3.767 represents positive long integer 32 bits 0 to 4.1 * (104932) Increases the size of double.4 * (10-4932) to 1. A more accurate floatingpoint number than float 32 bits 64 bits 3. It is useful with pointers.294.648 to 2. Page 28 ©Copyright 2007. Variable names must be chosen in such a way that it should be a valid identifier satisfying all the basic conditions.7 * (10-308) to 1. Variable names are case sensitive (ex: variable EMPNAME is different from variable empname).147. They are used to represent a collection of data. All Rights Reserved C3: Protected . The variable name can be chosen by the programmer in a meaningful way so as to reflect its function or nature in the program.647 Floating Point Number. Cognizant Technology Solutions.483.483. Derived Data Types Derived data types are a combination of primitive data types.Problem Solving and C Programming Type Short signed short short int signed short int int unsigned long long signed long long int signed long int Float Double long double void Meaning Size Range represents both positive and 16 bits negative integer quantity -32.4 * (10+38) 1. They are: Arrays Structures Unions Enumerated Pointers Variables A variable is an identifier that represents a value.295 Represents both positive and negative long integer 32 bits -2.

Symbolic constants are usually represented in upper case letters. General Form: [data type] variable name = value. There are two types of constants: Symbolic constants Constant variables. Symbolic Constants A symbolic constant is defined in the preprocessor area of the program and is valid throughout the program.14 Page 29 ©Copyright 2007. Cognizant Technology Solutions. Constants A constant in C refers to the fixed values that do not change during the execution of a program. tot = 0. ct=1. Initialization Variables can be initialized in the declaration statement itself or within the program using assignment statement. also called read-only variables. j.4 int i. float x. k. All Rights Reserved C3: Protected . A symbolic constant is defined as follows: #define MAX 100 #define PI 3.0.5 int total=0. The preprocessor directive #define is used to define symbolic constants in a program. ct=1. Example 3. int tot. Example 3. General form: var_data_type list variables. char ch. z.Problem Solving and C Programming 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. float sum = 0. y.

An operator is a symbol that tells the computer to perform mathematical or logical operations.Problem Solving and C Programming Each reference to ‘MAX’ in program will cause the value of 100 to be substituted.14. 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. Keyword ‘const’ is used to declare constant variables. C operators can be classified into a number of categories. All Rights Reserved C3: Protected . or const long a = 50000l. const long a = 50000L. (true – 1. Constant Variables A constant variable is declared and initialized in the variable declaration section of the program and cannot be modified thereafter. const float pi=3. 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) Page 30 ©Copyright 2007. Example 3. which evaluates to either true or false. The type of value stored in the constant must be specified in the declaration. const int a = 0567. Cognizant Technology Solutions. Operators are used in programs to manipulate data. const int a = 0Xa92 (Octal representation – prefix 0) (Hexadecimal representation – prefix 0x or 0X) Operators C supports a rich set of operators. const char ch = ‘a’. This value cannot be changed by the program.6 const int size = 100.

/=.post increment */ /* prints 7 */ -.k: pre increment. Bitwise operators & | << >> Bit wise AND Bit wise OR Left shift Right shift These operators are used to access machine at bit level. Cognizant Technology Solutions. *=.Unary minus Increment and decrement operators ++ may be in the form of pre increment or post increment (++ k: pre increment. i).Problem Solving and C Programming Expressions which use logical operators are evaluated to either true or false. Special operators & Address operator * Indirection operator comma Comma operator sizeof() Size of operator (sizeof(int) = 2 bytes) Page 31 ©Copyright 2007. -=.may be in the form of pre decrement or post decrement (-. printf(“%d”. k--: post increment) Conditional operator (ternary operator) ?: used to carry out simple conditional checking Example: big = (a>b)? a: b In the above statement. All Rights Reserved C3: Protected . k++: post increment) Example: int i=5. %= Compound assignment operators are used whenever. printf(“%d”. i++). ++i). the value of variable a will be assigned to variable big else b will be assigned. +=. printf(“%d”. Assignment operators = Assignment operator which assign a value to an identifier. (a = a+b equals to a+=b) Unary operators + Unary plus . /*prints 6 . left hand side identifier is used in the right hand side expression.pre increment */ /* prints 6 . if condition is evaluated to true.

Logical OR. Operators of the same priority group are evaluated from left to right fashion. ! – sizeof() (Typecast) * & ++ -*/% +< > <= >= == != && || ?: = . Page 32 ©Copyright 2007. Comma Association Left to Right Right to Left Right to Left Left to Right Left to Right Left to Right Left to Right Left tot Right Left to Right Right to Left Right to Left Left to Right Example 3. Cognizant Technology Solutions. unary minus. c=3 (1) a* b%c+1 is equivalent to (2) ++a*b – c-is equivalent to ((++a)*b) . The three types of expressions are Arithmetic expression (uses arithmetic operators). indirection.(b / c). High priority operators are evaluated prior to lower priority ones. Index. Multiplicative operators. op= Name Parentheses.(c--) which is equal to 1 ((a*b) %c)+1 which is equal to 3 Expressions Expression is a combination of operands. Equality comparators Logical AND. operators. The expression a + b – c is evaluated as (a + b) – c. member access operators Logical NOT. It is necessary to be careful of the meaning of expressions such as a . Conditional.b / c because we may want the effect as either (a .7: Operators Let a=1. All Rights Reserved C3: Protected . Assignment. function calls that evaluates to a value. Additive operators. address Increment and decrement operators.Problem Solving and C Programming Order of Precedence All the operators have its own precedence and associativity. b=2. and Logical expression (uses logical operators). From high priority to low priority the order for all C operators is given below: Operator ( ) [ ] -> . Inequality comparators.b) / c or a . Relational expression (uses relational operators).

c = 3. b+c). The left side of the “=” is always a variable. For example. c=3. This is called Typecasting.5. In implicit type conversion. a=b=3. C allows multiple assignment statements using =. d = 3. before assigning the value to it.5 5 -1 Type Casting C provides a mechanism for allowing the programmer to change the default data type of a given expression. All Rights Reserved C3: Protected . but more efficient than: a = 3. Page 33 ©Copyright 2007. Cognizant Technology Solutions. b-c).Problem Solving and C Programming Assignment Statement Assignment statement is used to assign a value to a variable. x + 3 = y. (4) int c.) not a storage location. is not legal because x + 3 is an arithmetic expression (i. c=3. However. 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. b+c. long int to int causes dropping of the excess higher order bits.. the lower data type is automatically converted to the higher data type before the operation evaluation. In C. e = a != b. a=3. b=4. the assignment operator is “=”. (3) int a. C provides two types of type conversions: Implicit and Explicit type conversions. computes the value of y+z and store the result in the variable x.8 (1) a = (b = 2. o o o float to int assignment causes truncation of the fractional part.which is the same as. . float b. c= a>b.. Typecasting allows a variable to behave like a variable of another type. b = 3. double to float causes round of digits.e. the statement x = y + z. whose address specifies where to store the data on the right side. Example 3. c=0 d=0 e=1 a= 3 b=3. (2) a = (b=2. d = a == b. For example: a = b = c = d = 3. For example. if the operands of an expression are of different types.

e.11 int a. /*f=2*/ /*c=3 */ /*d=2 */ /*x=1.Problem Solving and C Programming In explicit type conversion.10 float (char or int) to to (int or char) float . Another two terms associated with type casting are: Narrowing: Converting the higher data type value to lower data type value.7. y = a / 10. float x.8). Example 3.9 float sum. z.5 * 3. b.0 will be stored in sum. because the variable sum is of type float.8) as the integer 5. Then. This method of typecasting is done by prefixing the variable name with the data type enclosed within parenthesis. e = -a % -b. 5. instead of 5. the user has to enforce the compiler to convert one data type to another data type by using typecasting operator.narrowing . /*-2 (Modulus operation retains the sign of the first operand)*/ f = a % -b.0 */ Page 34 ©Copyright 2007. General Form: (data type)variable/expression/value. b=4. d = a % b. All Rights Reserved C3: Protected .0. Widening: Converting the lower data type value to higher data type value. y. x = a / 10.5 * 3. f. d.widening The following examples show different kinds of expressions: Example 3. c. Example 3. a=14.4 (Mixed-mode expression)*/ /*y=1. The typecast (int) tells the C compiler to interpret the result of (1. The original value of the variable is not altered. sum = (int) (1. c = a/b. Cognizant Technology Solutions.

Non zero value is true and Zero is false) c Input and Output Statements Reading. Unformatted Input statements Character Input There are several functions available to input a character from the console. and tab.12 a int a=0. a=b-. getchar () This function accepts a single character from the stream stdin (keyboard buffer). . ch = getchar(). This single character includes alphabets. return. All Rights Reserved C3: Protected . b=0.Problem Solving and C Programming Example 3. and printing of data are the three essential functions of a computer program. One method is to assign values to variables through the assignment statements. getch (). Example 3. a=b++ + c++. c = a && b 0 2 2 5 5 0 1 2 3 2 5 5 b 0 1 2 3 2 2 2 1 (Relational expression evaluated to true) 1 (Logical expression evaluated to true. There are two methods of providing data to the program variables. which can get data from the keyboard (standard input-stdin). digits. c=0. Cognizant Technology Solutions. punctuations. processing. General form: char-variable = getchar(). There are two types of Input and Output (I/O) statements: Unformatted I/O statements and Formatted I/O statements. Another method is to use input functions. a=++b + ++c. Page 35 ©Copyright 2007.character input from console & doesn’t echo the character. a=++b + c++.+ --c.13 char ch. c = a>b.

String Output puts() This function displays the string in the standard output. ch = getchar(). Unformatted Output statements Character Output putchar() This function displays a single character in the standard output (stdout).character input from console & echoes the character. putchar(ch). /* string is represented as character array */ Example 3. General Form: gets(stringvariable).14 char ch[5]. To get a line of text.Problem Solving and C Programming getche(). Page 36 ©Copyright 2007. String Input gets () . Example 3. gets(ch). monitor. Blank space is also considered as a character. Cognizant Technology Solutions. General Form: putchar(char variable). All Rights Reserved C3: Protected .15 char ch. This function accepts a string terminated by a new line character. this function serves the purpose.

General Form: scanf (“format string”. Formatted I/O Statements Formatted input refers to an input data that has been arranged in a particular format. g. A character following this defines the format for a value.] – string of specified characters %u – unsigned General Form: “%-+s0w. Format string specifies the field format in which the data is to be entered. l. Example 3. Page 37 ©Copyright 2007. x.Problem Solving and C Programming General Form: puts(str). f. list of variables). e) Formatted Input Statement scanf() scanf () function is used to read formatted data items. %g – float %s – string %ld – long integer %o – octal %x – hexadecimal %hd – short integer %[. All Rights Reserved C3: Protected . o. Cognizant Technology Solutions. Some of the format specifiers are given below: %c – character %d – integer %f. C has a special formatting character (%). puts(ch).. %e.16 char ch[5]. gets(ch). L) conversion character (d.pmc” Where: + s 0 w p m c left justify print with sign print space with no sign pad with leading zero field width precision conversion character ( h. u.

/*delimiter between two input is = (10=20)*/ scanf (“%2d%5d”. scanf (“%[^\n]s”. the delimiter while reading the values is space. a=12345 & b=10*/ sscanf() sscanf() function to read values from a string. General Form: sscanf (str. str). All Rights Reserved C3: Protected . x). &a. To read a string using ‘%s’. Example 3. a= 12 & b=3456*/ scanf (“%d%d”. /* column width 10. General Form: printf (“format string”. first 4 characters printed. sum).4s”.18 printf (“char=%c. name). &x). &b). /* width & precision can be user defined*/ printf (“name = %10.17 scanf (“%c %d %f”. &i. printf (“sum = %*. Formatted Output Statement printf() printf () function is used to output the values. /*if the input is 12345 & 10. &ch. Format string.ch. w.&a. i. By default. which directs the interpretation of input data.&b). ‘&’ need not be used. /*if the input is 12345 & 10. &a. Delimiter can be user-defined. list of variables).*/ scanf (“%d=%d”. Cognizant Technology Solutions. Format string and variables are separated by comma.2f”. p. a=12 & b=345 if the input is 12 & 3456. int=%3d. Stops when it encounters new line. This functions returns the number of inputs read successfully. floating point=%6. /*accepts all inputs including space.Problem Solving and C Programming List of variables specify the address of memory locations where the data is to be stored. list of variables). This function returns the number of characters printed.*/ Page 38 ©Copyright 2007. Address operator (&) is used before the variables. “format string”.&b). Example 3.*f”. also known as control string contains field specifications.

then based on the operator precedence. float. Which of the following are valid identifiers? a. total-marks Page 39 ©Copyright 2007. General Form: sprintf (str. Cognizant Technology Solutions. Test your Understanding 1. C supports four basic primitive data types: int. getchar(). “total” c.c> to obtain soft copy of the program code How It Works: The program assigns the value and substitute in the expression.z). C has Unformatted and Formatted Input / Output statements. C program is a collection of functions. z = x++ .a=4. double.b=2.--y * b / a.y=-10. printf("The Value of z : %d\n". Emp_name b. All Rights Reserved C3: Protected . char.h> main() { int z. Try It Out Problem Statement: Write a program to find out value for an expression Code: #include <stdio. list of variables).Problem Solving and C Programming sprintf() sprintf() function is used to output values to a string.x=5. } Refer File Name: <sesh3_1. C has a rich set of operators. “format string”. main d. the value get computed and prints on the screen Summary C is a structured programming language.

Cognizant Technology Solutions.c ( “ “ . a = (b = 2) + (c=3). but getch() will not echo the character.5. the scanf() statement contains the following control : “%d \n %d” Which of the following set of inputs will successfully read ? a. . valid 3.are not the valid characters to form an identifier) 2. All are valid.Problem Solving and C Programming 2. If. All Rights Reserved C3: Protected . s = 10. What is the output of the following code? int a . a. s.5 4. 6. 4 5 b. b = printf (“welcome”). Is the statement valid? 3. What is ternary operator in C? 5.0 . x= (int) y. welcome7 Page 40 ©Copyright 2007. s= (int) y + 3. printf (“%d “. x = 7. 5. What is the difference between getche() and getch()? 6. 4. getche() echoes the input character on screen. 4 5 7. ?: is called ternary operator (conditional operator) used to carry out simple decision making. y=7.b). Answers: 1.5. 7. What will be the value of the variables x and s after the following piece of code is executed? float x.

1 a=8. b=10. In a selection structure. and iteration (looping). In an iterative structure. All Rights Reserved C3: Protected . the control flow can be altered by evaluating conditions. y = x * b – k.Problem Solving and C Programming Session 5: Selection and Control Structures Learning Objectives After completing this session. c=a+b. In a sequence construct. Null statement Compound Statements / Blocks Compound statements are used to group the statements into a single executable unit. until some condition is satisfied. It consists of one or more individual statements enclosed within the braces { }. } } { b=2. . 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. } x=a*b. the instructions are executed in the same order in which they appear in the program. Page 41 ©Copyright 2007. } { { a=1. selection. c=a + b. Cognizant Technology Solutions. Example 5. 2 { a=10. c=3. a group of instructions is executed repeatedly. 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.

[ ] is used to represent the optional usage of ‘else’ block. It provides the ability to decide the order of execution. If the expression is evaluated to true (nonzero). The if statement has three basic forms: Simple if-else Nested if if-else if ladder Simple “if-else” General Form: if (expression) { statements1. All Rights Reserved C3: Protected . Programs may require certain logical tests to be carried out at some particular points. allows us to establish decision-making in the programs. input-output statements.<Delete the arrow brackets while entering actual names and text. Depending on the result of the expression the statements are executed. The following are the selection constructs available in C: “ if ” statement Conditional / Ternary operator statement (? :) “switch” statement ‘if’ Statement The if statement. and/or relational expression. and one or more simple expression statements. is executed in a sequential manner. } ] statements3. The tests and subsequent decisions are made by evaluating a given expression as either True (non zero) or False (zero).Problem Solving and C Programming Sequence A program. logical. the statements1 are executed and the control is transferred to the statements (statements3) next to the if construct is executed. Selection Statements Selection statements are used to alter the normal sequential flow of control. Expression can be arithmetic. which consists of declaration statements. } [ else { statements2. An expression involves arithmetic. If the expression is evaluated to false (zero). relational. the Page 42 ©Copyright 2007. Cognizant Technology Solutions. Insert more subheadings where required by copying one already done. and/or logical operators.

c). if (a>b) if (a>c) printf(“largest = %d”. else max = a. } else { statements2. the evaluation of expr2 will not occur [ 1 OR anything is 1] Nested ‘if’ Statement Body of an ‘if’ statement contains another ‘if’ statement. } Example 5.Problem Solving and C Programming statements1 will be skipped and the else part statements (statements2) are executed. true or false is known. General Form: if (expression) { statements1. Short-circuit Evaluation Whenever the expression with the operators && and || are evaluated. Page 43 ©Copyright 2007. if (expression) statements-1. Example 5. If the else part is not specified.4 Program to find the maximum of 3 numbers. else printf (“largest = %d”.max). the evaluation of expr2 will not occur [ 0 AND anything is 0] expr1 || expr2 If expr1 has non-zero value. a). the evaluation process stops as soon as the outcome.3: Program to find maximum of two numbers. All Rights Reserved C3: Protected . if (expression) statements-2. the statements (statements3) next to the if construct is executed. printf(“ max = %d” . Cognizant Technology Solutions. For example: expr1 && expr2 If the value of expr1 is zero. if (a<b) max = b.

else printf (“largest = %d”.5 if (mark >= 75) printf(“Honours\n”). General form: [variable = ]expr1? expr2: This simply states: Page 44 ©Copyright 2007. else if (mark >=60) printf(“First Class\n”).Problem Solving and C Programming else if (c>b) printf (“largest = %d”. Example 5. else if(expression) statements3. Final ‘else’ serves as a default case and is useful in detecting an impossible or error condition. All Rights Reserved C3: Protected expr3. Cognizant Technology Solutions. . else if (mark >=50) printf(“Second Class\n”). The final ‘else’ statement is executed only if none of the previous conditions are satisfied. else statements4.b). else printf(“Fail\n”). ‘if… else if’ Ladder Statement General Form: if (expression) statements1. Conditional / Ternary / ?: Operator This operator takes 3 expressions / operands. It is a more efficient form for expressing simple if statements.c). else if (mark >=45) printf(“Third Class\n”). 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. else if (expression) statements2.

pointer variable. Default case is optional and if specified. break.Problem Solving and C Programming if (expr1 is true) then expr2 else expr3 Where: o o expr2 is evaluated. default statements will be executed. General Form: switch (expression) { case item1: statement 1. must be an integer valued expression. then an execution jump is made to that point. Example 5.6 max = (a>b) ? a : b. expr3 is evaluated. if (a>b) max = a. logical expression. if there is no match for the case labels. else max = b. case item2: statement 2. Page 45 ©Copyright 2007. Otherwise the next cases get evaluated. Cognizant Technology Solutions. array variable. If the variable matches with one of the constants. Switch Statement This is a conditional control statement that allows some particular group of statements to be chosen from several available groups. A case label can not appear more than once and there can only be one default expression. It is a multi-way conditional statement generalizing the ‘ifelse’ statement. Expression may be a constant value. and/or arithmetic expression. Items which represent the case labels must be an integer constant or character constant. variable. break. A switch statement allows a single variable to be compared with several possible case labels. All Rights Reserved C3: Protected . if the value of expr1 is zero (false part). which are represented by constant values. which is similar to the following if-else statement. The break is needed to terminate the switch after the execution of particular choice. case itemn: statement n. } Expression in the switch statement. relational expression. break. if the value of expr1 is non-zero (true part). default : statement.

break. expression2. case ‘-’: c=a-b. General Form: for (expression1. case ‘*’: c=a*b. expression3) { statement / block of statements. If the test condition is True. All Rights Reserved C3: Protected . } Iteration Statements Most of the real world applications require some set of instructions to perform repetitive actions on a stream of data. the control is transferred to the statement. There are several ways to execute loops in C. expression2 is to set a terminating condition. The statements used for looping are: ‘for’. which follows the loop. } Where: expression1 initializes the counter/index variable. Cognizant Technology Solutions. break. break.7 switch (op) { case ‘+’: c=a+b. ‘while’. case ‘/’: c=a/b. ‘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. Page 46 ©Copyright 2007. It is evaluated at the beginning of every iteration. break.Problem Solving and C Programming Example 5. the statements inside the loop are executed. If the test condition is False. The initialization is usually an assignment statement that is used to set the index variable or loop control variable. default: printf (“Invalid operator”).while’. ‘do.

The second loop. c). c).++c) (6) c=2. Page 47 ©Copyright 2007. the inner loop runs completely. c++.) { printf (“%d”.Problem Solving and C Programming expression3 is the loop variant/modifier (increment / decrement). for (j=1. y=4. All Rights Reserved C3: Protected . Different variables must be used to control each loop. the loop controlled by the value of ‘i’ is called the outer loop. Example 5. which is evaluated at the end of every iteration. (3) for (x=0. z=4000. infinite loop infinite loop ((x>3) && (y<9)). ((x>3) && (x<9)).. y=4.) { c+=1. Cognizant Technology Solutions. } In the above example. printf (“c=%d”.9 for (i=1. (4) c=2.c<=20.i++) { printf(“\n i = %d”. z . is called inner loop. These three expressions are separated by semicolons. Example 5. For each & every iteration through the outer loop.i).j). for (.i<=3. } (7) int c=0.j<=3. j++) printf (“\n j = %d”. } Nested ‘for’ statement There are many situations in which a loop statement contains another loop statement. y+=2) z/=10) (2) for (x=0.c=c+2) (5) for (c=2. for (. x++) x++. All statements in the inner loop are within the boundaries of the outer loop. Such loops are called nested loops. controlled by the value of ‘j’. for(.8 (1) for (x=0.c<=20..

If the expression is initially False.while’ statement The do. If the expression evaluates to True. (4) while(1). ++c. At the end of the loop. (6) c=1. (3) while(x) { }. } ‘do . After executing the body of the loop. General Form: while (expression) { Statements. while (c<=10) { printf (“%d”. variable or any expression. the expression is checked again.. the program proceeds to evaluate the body of the loop first. (5) while ( (ch = getche ( )) != ‘q’) putchar(ch). the body of the loop is executed. (2) while(x = x+1){ }.c). If the expression is evaluated Page 48 ©Copyright 2007. otherwise statements after the while block is executed. The body of the loop is executed repeatedly until the expression is False. The braces are needed only if the body contains two or more statements. The body of the loop may have one or more statements. If the result is True.. while is an exit controlled loop statement. Cognizant Technology Solutions.10 Different ways to use while loops (1) while(x--){ }. Example 5. The conditional expression is evaluated at the beginning and the result of the expression decides on the execution of the body of loop. the body of loop is not executed at all. } Expression can be a constant value. General Form: do statement (s). while (expression). All Rights Reserved C3: Protected .Problem Solving and C Programming ‘while’ statement The while is an entry controlled loop statement. the expression in the while statement is evaluated. the body of the loop is executed. On reaching the do statement.

Since the expression is tested at the end of the loop. Continue Statement The continue statement can only appear in the loop statements. When the condition becomes False. } while (d<=10).Problem Solving and C Programming to True. General Form: break. This process continues as long as the expression evaluates to True. Example 5.loop++) { if (loop==50) /* control will come out of the loop.13 for(loop=0. Continue Statements Break Statement The break statement can appear in the switch statement and the loop statements. Page 49 ©Copyright 2007. Example 5.loop<50..loop++) { If (loop==10) break. All Rights Reserved C3: Protected . It is used to terminate the current iteration.loop). */ printf("%d\n". do { printf (“%d\n”. Example 5. General Form: continue. the body of the loop is executed at least once. It skips rest of the statements in the body of the loop and begins the next iteration. Break. the loop will be terminated and control is transferred to the next statement following the do. It causes the execution of the current enclosing switch case or the loop to terminate.12 for(loop=0.11 int d=1. ++d. } Only numbers 0 through 9 are printed.loop<100. the program continues to evaluate the body of the loop once again.d).while. Cognizant Technology Solutions.

45359 main() { int pounds. All Rights Reserved C3: Protected . Cognizant Technology Solutions. Try It Out Problem Statement: Write a program to convert pounds in to equivalent international units starting from 10 pounds to 250 pounds incremental of 10 pounds Code: #include <stdio.h> #define KILOS_PER_POUND . stones. till the pound becomes greater than or equal to 250 pounds Page 50 ©Copyright 2007. uklbs. kilos). pounds. float kilos = pounds * KILOS_PER_POUND. printf(" %d %d %d %f\n".uklbs and kilos and print on the screen. uklbs and kilos. so we have used the for loop. } The numbers 0 through 99 are printed except 50. pounds < 250. Continue this till the termination condition is met i. pounds+=10) { int stones = pounds / 14. lbs INT Kg\n"). int uklbs = pounds % 14. We know the starting point. The conversion has to be done starting from 10 pounds till 250 pounds in the incremental of 10 pounds.e. termination condition and the increment. printf("%d\n".Problem Solving and C Programming continue. For each pounds. for(pounds=10.loop). } getchar(). } Refer File Name: <sesh5_1. apply formula to get the stones. printf(" US lbs UK st.c> to obtain soft copy of the program code How It Works: This program converts pounds in to stones .

Cognizant Technology Solutions. 2. break. case 2 : printf(“2”). that are used to carry out conditional looping. Test your Understanding 1. for. break statement is used to terminate the loop but continue statement skips the current iteration and continues the loop with the next iteration. An if statement may include only simple statements.Problem Solving and C Programming Summary if statement is a condition based decision making statement. Looping allows a program to repeat a section of code any number of times or until some condition occurs. break. break. case 3 : printf(“3”). while. and do-while statements are repetitive control structures available in C . Which of the following statements are true? a. } } Page 51 ©Copyright 2007. All Rights Reserved C3: Protected . What is the output of the following piece of code? main( ) { int i=3. case 1 : printf(“1”). c. if clause can contain another if statement. An if statement must always include an else clause. b. Ternary operator is more efficient form for expressing simple if statements. When will the default case in switch statement be executed? 3. Switch statement is a conditional control statement that allows some particular group of statements to be chosen from several available groups. switch(i) { default : printf(“0”).

Problem Solving and C Programming 4.while will get executed at least once. c 2.. Default case is executed.while statements?What is the output of the following code? while(1) { if (printf (“%d”. What is the difference between a while and do.while is exit controlled loop (condition is checked at the end). printf (“%d”))) break. Cognizant Technology Solutions. } Answers: 1.. whenever evaluated expression does not matches with any of the case labels. else continue. 3. 3 4. 01 Page 52 ©Copyright 2007. The loop statements of do.. While is an entry controlled loop (condition is checked in the beginning) and do. 5. All Rights Reserved C3: Protected .

Page 53 ©Copyright 2007.Problem Solving and C Programming Session 7: Arrays and Strings Learning Objectives After completing this session.. If an array of 5 integers elements is created. set of numbers. Array is a derived data type which is used to store similar data items in contiguous memory locations under a single name. index 1 refers second location. The individual elements are accessed by specifying the subscript.g. you will be able to: Explain the concept of Array and memory organization Write program using Single-dimensional arrays Write program using Multi-dimensional arrays Understand Strings Understand String and Character functions Need for an Array Many applications require the processing of multiple data items that have common characteristics (e. 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.]. All Rights Reserved C3: Protected . Cognizant Technology Solutions. totally 10 contiguous bytes will be allocated in memory. Note: size of an integer is assumed to be 2 bytes Starting address is assumed as 1000 and totally 10 bytes are created. of the same data type. It holds a fixed number of equally sized data elements. Memory Organization of an Array The elements in an array are always stored in consecutive memory locations. set of names). etc. the name of the array refers to the base address of the array. [index 0 refers first location . 1000 1002 1004 1006 1008 Individual memory location is referred by index.

char str[16]="qwerty". starting at sales_amt[0] and ending at sales_amt[9]. which is represents a string of maximum of 16 characters. starting at x[0]. General Form: datatype arrayname[size] . Array declaration reserves space in memory. int matrix[2][2].2 x[0] x[4] str[2] sales_amt [8] to access the 1st element in array to access the 5th element in array to access the 3rd character in the string (character array) to access the 9th sales amount in the array 5 integers. Arrays are defined by appending an integer encapsulated in square brackets at the end of a variable name. Defines an integer array x of at x[4]. Defines a 2*2 matrix (totally 4 elements) of integers. Arrays can be of single dimension or of multi dimensions. Defines a floating point array sales_amt of 10 floating point numbers. Cognizant Technology Solutions. indexing begins at 0 and ends at 1 less than the defined size of an array. All Rights Reserved C3: Protected . and ending Page 54 ©Copyright 2007. Example 7.1 int x[5]. Accessing Array Elements The array elements are accessed by specifying the subscript / index. General Form: arrayname[index or subscript] Example 7. Defines a character array. When addressing an element in an array. float sales_amt[10].Problem Solving and C Programming Declaration and Initialization Array Declaration Arrays are declared with appropriate data type and size. Each additional set of brackets defines an additional dimension to the array (multi dimensional arrays).

the base address can not be changed. b[1] = 45.4}. a[2]=3. ) */ float b[2]={10. Insertion and deletion can be done by moving the array elements to the appropriate places. /*a[0] = 1.4}. /*a[0]=1. partial initialization is allowed.2.Problem Solving and C Programming Array Initialization Array elements can be initialized during declaration or can be initialized in the program. size depends upon the number of values initialized.2. Cognizant Technology Solutions. Zero is initialized for numeric array and Null for character array.2. the uninitialized array elements are initialized to Zero or Null depending on the data type of the array. OR datatype arrayname[ ] = {value(s)}. 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 55 ©Copyright 2007.3. Example 7.5}. /* b[0] = 10.4. retrieving. and processing of array elements. (ex. In partial initialization.45. General Form: datatype arrayname[size] = {value(s)}. All Rights Reserved C3: Protected .34}.2.3. 3rd element can be deleted by moving 4th element to 3rd location. When arrays are initialized during declaration. a[1]=2. In such cases.3 int a[5]={1. array can be declared without specifying the exact size. size of the array equals the number of elements initialized.20 . If initialized. 5th element to 4th location and so on) Array name is a constant pointer (pointer is a variable which holds address of another variable) to the base address of the array. a[3]=4 (if size not specified. a[1] = 2 .34 */ Basic Operation on Arrays Basic operations allowed on arrays are storing. a[3] = 4 and a[4] = 5*/ int a[5]={0}. /*a[4] = 0*/ int a[ ] = {1. a[2] = 3 . /*all the array elements are initialized to zero*/ int a[5]={1. Thus.3.

&a[2]). scanf(“%d”. Two-dimensional array – Declaration Two-dimensional arrays are defined in the same way as one dimensional array.a[0].a[1].6 int a[3]. (2) /*gets value for 1st location*/ gets value for 2nd location*/ gets value for 3rd location*/ scanf(“%d%d%d”. a. a[0]). except that a separate pair of square brackets is required for second dimension. /* prints value of first 3 locations*/ for(i=0.a[2]). Cognizant Technology Solutions. /* gets value for first 3 locations (array name has the base address . &a[0]). All Rights Reserved C3: Protected .i<3. /*prints value of 3rd printf(“%d%d%d”. /*loop statement is used to print the array elements */ Multi-dimensional Array The elements of an array can themselves be arrays.Problem Solving and C Programming Getting the value for Arrays Input statement is used to get the values for an array.pointer)*/ (3) for(i=0. 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.a[1]).5 int a[3]. Multidimensional arrays will also occupy the contiguous memory locations.&a[i]). printf(“%d”. a+1.i++) printf(“%d”. scanf(“%d”. (1) printf(“%d”. (2) (3) /*prints value of 1st location*/ /*prints value of 2nd location*/ location*/ printf(“%d”. a+2). General Form: datatype arrayname [row ][column] Page 56 ©Copyright 2007.i++) scanf(“%d”.a[i]). /* usually loop statement is used to get the array elements*/ Printing out the array elements Example 7. a[2]). &a[1]).i<3. Example 7. (1) scanf(“%d”.

3.6}. creates 8 bytes of contiguous memory locations. n-m locations are unnecessarily wasted No automatic array bounds checking during compilation Page 57 ©Copyright 2007.row 0 & column 1 . /*num[1][2] = 0*/ int num[2][3] = {{1. /*num[0][2] = 0 num[1][1]=num[1][2]=0*/ Example 7.row 0 & column 0 .row 1 & column 1 a[0][1] a[1][0] a[1][1] will be in location 1002 will be in location 1004 will be in location 1006 Two-dimensional array Initialization Two-dimensional arrays can also be initialized in the declaration statement. Example 7.2.2. Assume that array starts at location 1000.5}. All Rights Reserved C3: Protected .3.3}}. int num[2][3] = {1.row 1 & column 0 .5.{1. Memory is allocated in the beginning of the execution.Problem Solving and C Programming Example 7. out of n locations defined.4. the uninitialized array elements are initialized to Zero. = 4 elements).2}.9: 4-dimensional array sales [year ] [month ] [area ] [salesperson] 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. a[0][0] will be in location 1000 .2.8 int num[2][3] = {1. In partial initialization.2.3}. (2*2 Elements are stored in row major order. It is necessary to specify the size of the column in declaration.{4}}. Elements of 1st row are stored first and then the elements of next row. If m elements are needed. 7 int a[2][2]. /*row elements are initialized separately*/ int num[2][3] = {{1. Cognizant Technology Solutions.4.

A character string is stored in an array of character type. to represent the end of string. name[1] = ‘O’. name[3] = ‘D’. of strings] [max no.’u’.10 (1) char c[4]={‘s’.11 char studname[50][15]. The value at str[6] is the null character. Example 7.’\0’). String can be represented as a one-dimensional array of characters. name[2] = ‘O’. } (4) char name[5] = “INDIA” /* Strings are terminated by the null character. name[4] = ‘\0’. one ASCII character per location. The values from str[7] to str[15] are undefined. /*Creates a string. String should always have a NULL character (‘\0’) at the end. of chars in strings]. /* 50 student names each with 15 characters at the maximum */ Page 58 ©Copyright 2007.*/ (3) char name[5].’m’. int main( ) { name[0] = ‘G’. Declaration General Form: char arrayname [no. The value at str[5] is the character ‘y’. (2) char str[16]="qwerty".Problem Solving and C Programming Strings Strings are sequence of characters. return 0. Cognizant Technology Solutions. String constants are always enclosed within double quotes and character constants are enclosed within single quotes. String constants can be assigned to character array variables. there is no built-in data type for strings. 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. In C. All Rights Reserved C3: Protected . Example 7.

name).Problem Solving and C Programming Initialization General Form: char arrayname [ r ] [ c ]={“values”}. Page 59 ©Copyright 2007. String can be read either character-by-character or as an entire string (using %s format specifier). which manipulates the entire string at once. All Rights Reserved C3: Protected . Strings are manipulated either via pointers or via special routines available from the standard string library string. Example 7. int i=0. thus statements of the following form are illegal” name = “GOOD”. assignment not allowed name1 = name + “to c “ concatenation is not allowed two strings cannot be compared with the ‘equal to’ operator String Functions C does not provide any operator.’\0’}.’t’.’\0’}} = {{‘b’.’a’.’t’.”at”} char name[3][5] {‘a’.13 (1) char name[20]. while((name[i] = getchar ()) != ‘\n’ ) i++. name).12 char name[3][5] = {“bata” . if (name1 == name) Or name1 = name.”cat” . Cognizant Technology Solutions.’t’. (2) (3) scanf( “%s“ . [Note: no need to use & operator while reading string using %s] Example 7. {‘c’. 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.’a’.’a’. Illegal operations on Strings C does not allow one array to be assigned to another. printf(“%s” .h.’\0’}.

Returns a pointer to the first occurrence in s1 of any character from s2 Returns the number of characters at the beginning of s1 that match s2. c) strrchr (string. s2) strspn(s1. All Rights Reserved C3: Protected . n) strncpy(string1. Locates the first occurrence of s2 in s1. string2. s2) strcspn(s1.string2. string2) strcmp(string1.s2) strpbrk(s1. c) strstr(s1. Returns the number of characters at the beginning of s1 that do not match s2.string2) Copy string2 into string1 Concatenate string2 onto the end of string1 Lexically compares the two input strings (ASCII comparison) returns 0 if string1 is equal to string2 < 0 if string1 is less than string2 > 0 if string1 is greater than string2 Gives the length of a string Reverse the string and result is stored in same string. n) strupr (string) strlwr (string) atoi (string) atof (string) atol (string) strchr (string. string2) strcat(string1. Cognizant Technology Solutions. Copy first n characters of string2 to string1 Converts string to uppercase Converts a string to lowercase Converts the string to integer number Converts the string to floating point number Converts the string to long integer number Find first occurrence of character c in string. Find last occurrence of character c in string. string2. s2) Page 60 ©Copyright 2007.Problem Solving and C Programming The following is the list of string functions available in string. n) strncmp(string1.h: String Functions strcpy(string1. Functionality strlen (string) strrev (string) strncat(string1. Append n characters from string2 to string1 Compare first n characters of two strings.

fib[0] = 0.h.\r. True if c is a letter. ‘.\f. Cognizant Technology Solutions. The header file. except space) True if c is a lowercase letter True if c is a printable character (all characters including white space) True if c is a punctuation character (.\v. fib[1] = 1. int i.’ ‘) True if c is an uppercase letter True if c is a hexadecimal digit Converts lowercase letter to uppercase Converts uppercase to lowercase Converts the char to ASCII value Functionality Try It Out 1. i < 24. i++) Page 61 ©Copyright 2007.\r. . which can manipulate a single character. Functions int isalnum (c) int isalpha (c) int isascii( c) int iscntrl (c) int isdigit (c) int isgraph (c) int islower (c) int isprint (c) int ispunct (c) int isspace( c) int isupper (c) int isxdigit (c) toupper (x) tolower (x) toascii (x) True if c is alphanumeric. All Rights Reserved C3: Protected .) True if c is a space character (\n.\f.Problem Solving and C Programming Character Functions C provides the following collection of character functions.h> main() { int fib[24]. True if c is ASCII . i++) fib[i] = fib[i-1] + fib[i-2]. Problem Statement: Write a program to develop Fibonacci series using arrays Code: #include <stdio. “. for(i = 2. i < 24. is used for the character functions. ctype.‘.:.\a) True if c is a decimal digit True if c is a graphical character (all characters.\t. True if c is a control character (\n. . for (i = 0.

c> to obtain soft copy of the program code How It Works: This program explains the how to use the two dimensional array. i. fib[i]). i<4. 2. j<5. twod[i][j]).13….5. printf("\n"). getchar(). i++) for(j=0. as we know the first two numbers initialize the first two elements in the array. i++) { for (j=0. Initially array of size 24 is declared. int i. i<4. Cognizant Technology Solutions.c> to obtain soft copy of the program code How It Works: The Fibonacci series is 1.2. j++) twod[i][j] = i*j. } Refer File Name: <sesh7_2.3. All Rights Reserved C3: Protected . Problem Statement: Write a program to demonstrate two dimensional arrays Code: #include <stdio.. j++) printf("%d ". In the for loop start adding the values in the previous two indices of array and store it in the third element Then increment the indices and keep continuing the same process until 24 numbers are added.8.Problem Solving and C Programming printf("%3d %6d\n". This program implemented fibonacci series by using for loop and array.j. } getchar(). Page 62 ©Copyright 2007. Again use the for loop to print the series one by one from the array. for(i=0. for (i=0. j<5.The program computes the series up to 24 numbers. } Refer File Name: <sesh7_1.h> main() { int twod[4][5].

Problem Solving and C Programming

In two dimensional array, two indices will be used, one represent the row and the other one column. Here “i” represents row and the “j’ represents the column Two for loops are used. The outer loop decides the row and the inner loop represents the column Initialise both i and j to 0. For each value of i, find out all the values of column by multiplying the i with j with incremental of j. Store the values in the array Use another for loop to print the values in the two dimensional array in the form of matrix. The program output looks like this: o 00000 o 01234 o 02468 o 036912

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.

Test your Understanding
1. Is it possible to declare an array x containing 50 integer elements followed immediately by 50 floating point numbers? 2. Why array index should always start with 0? 3. How entire array, x[100] with value 0, is initialized in declaration statement? 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?

Page 63 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Problem Solving and C Programming

5. What is the output of the following code? main() { int a[5]={2,3}; printf(""\n %d %d %d"",a[2],a[3],a[4]); }

6. List few library functions for string operations. 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. 3. int x[100] = {0} ( partial initialization) 4. If an entire array is being initialized within the declaration. 5. 0 0 0 6. strlen(), strcmp(), strcat(), strrev(), strcpy()

Page 64 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Problem Solving and C Programming

Session 9: Functions
Learning Objectives
After completing this session, you will be able to: Define functions Understand how to pass arguments to function Understand and Implement Recursive functions Understand how to pass arrays in a function

Need for Functions
Functions are smaller self-contained components which carry out some specific, well defined task. As real world applications become more complex and large, several problems arise. Most common are: Algorithms for solving more complex problems become more difficult and hence difficult to design. Even after designing an algorithm, its implementation becomes more difficult because of the size of the program. As programs become larger, testing, debugging, and maintenance will be a difficult task. 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 C function offers the following advantages. It facilitates top-down modular programming. Modularity brings logical clarity to the programs It avoids the need for redundant code. The repeated instructions can be written as a function, which can then be called whenever it is needed It facilitates reusability – functions created in one program can be accessed in other programs. C programmer can build on what others have already done, instead of starting from scratch C functions can be used to build a customized library of frequently used routines

Page 65 ©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 9.1 int find_big (int, int); arguments */ void swap (int *, int *); variables. */ float add(float, int); /* function ‘add’ returns float value, takes 1 float variable and 1 integer variable */ /* function ‘swap’ does not return any value, takes 2 pointer /* function find_big returns integer value, takes 2 integer

Example 9.2 (1) main() { int a,b; int sum(int, int) ; scanf("%d%d” , &a, &b); printf(“ %d “ , } int sum(int a , int b) { return a+b; } sum(a, b); /* function prototyping. */

Page 66 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Memory for the local variables is allocated only when the function is invoked and de-allocated when the control moves out of the function. If it is declared in the Global declaration section. } main() { fun(). and the operations to be carried out by the function. } Function is defined prior to its reference.The variables that are common to all the functions are declared outside the functions. when the program gets executed and deallocated only at the end of program execution. Function body.) { local variables Declaration. It can be accessed only within that function.. parameters. executable statement 1. Global Variables .arg2 … return-type specifies the name of the function and it must be a valid identifier specifies formal arguments (formal parameters) 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. Cognizant Technology Solutions. there is no need for the function prototype. Function Definition Function definition is used to define the function with appropriate name. executable statement 2.The variables declared inside any function are local to that function. Page 67 ©Copyright 2007. type arg2. So compiler will identify the function name. } Function Header function-name arg1. All Rights Reserved C3: Protected . A function definition has two principle components: Function header (first line). Local Variables . …. it is used by all the functions in the program. Memory for the global variables is allocated. : return expression.Problem Solving and C Programming (2) void fun() { printf(“"prototype not needed “). Functions can be defined at any location in the program. If the function is defined before the ‘main’ program. General form: return-type function-name(type arg1.

3 (1) return. Example 9.5 (1) void display(void) { printf(“this is a function”). } (2) main() { return 0. If it returns a value. the closing braces (}) in the function body acts as a return statement. constant value or any single valued expression. } If the function doesn’t receive any arguments and doesn’t return any data. All Rights Reserved C3: Protected . } Function Name Return Type – find_big – integer Formal arguments – 2 (a. return(a*b). int b) { if ( a > b) return a. does not return any value. it is achieved by the return statement. return(a<b). each containing different expression. b) Page 68 ©Copyright 2007. else return b. General Form: return. Cognizant Technology Solutions.Problem Solving and C Programming return statement is used to transfer the control back to the calling program. then void keyword is used to represent that. (control is transferred returns zero returns the product of a & b returns True (1) or False (0) Example 9. A function may receive any number of values from the called function. There can be multiple return statements.4 Function for finding the biggest of two integers int find_big(int a. to calling program) (2) (3) (4) return 0. Default return type is ‘int’. Example 9. A function may or may not return a value to the calling function. OR return(expression). If there is no return statement. expression can be a variable name.

int b) { if ( a > b) return a. the value returned is stored in the LHS variable name. Example 9. The LHS variable name in the function call is optional. All Rights Reserved C3: Protected . data type. If the function returns value. big). num2. Actual arguments are the parameters passed to the called function.num2)) statement. big. the control is transferred to the called function and the statements in the function are executed. } int find_big(int a. int). followed by a list of parameters enclosed within parentheses. When the function call is encountered. the control is transferred back to the place of function call in the calling function. When the return statement is executed or last statement is execution.Problem Solving and C Programming Function Call Functions are invoked by specifying its name. Cognizant Technology Solutions. /* function prototype. Recursion If a function is having a self-reference. num1 & num2 are actual arguments */ printf(“ The biggest is : %d “. global declaration */ main( ) { int num1. General form: [variable name =] function name(actual arguments). A recursive function must have the following properties: The problem must be written in a recursive form /* a & b are formal arguments */ Page 69 ©Copyright 2007. it is called Recursion. Variable names of the actual arguments and the formal arguments need not be same.6 Program for finding biggest of two integers using the function find_big int find_big(int. &num2). that value is substituted in place of a function call in the calling function.num2). /* function call statement. find_big(num1. scanf(“%d%d”. The number. &num1. } Note: Function can also be called using printf (“The biggest is: %d”. else return b. If a function is returning a value. and the order of the actual arguments and formal arguments should match. It is a process by which a function calls itself. big=find_big(num1.

} If n = 4. else return(k*fact(k-1). along with the value returned.&n). which in turn return the value to its calling function.7 main() { int n. printf(“Factorial = %d“.fact(n)). In fourth call. { if (k<=1) return 1. Cognizant Technology Solutions. call 3 = 2 * fact(1) call 2 = 3 * fact(2) . control is transferred back to the called function. The parameter values are substituted and the function is executed. When the return statement is encountered. Function will be evaluated in Last In First Out manner (Stack) Nesting of Functions Functions may be nested. Depending on its definition. All Rights Reserved C3: Protected . Passing Arguments A function is referenced by its name and providing appropriate values for the arguments.Problem Solving and C Programming There must be a base criteria (terminating condition) for which the function doesn’t call itself Example 9. the condition evaluates to 1 and returns 1 to the calling part (call 3). which in turn call function2. the control is immediately transferred to the function. then call 1 = 4 * fact(3). } fact(int k). printf(“Enter an integer\n”). functions may be classified as: Functions with no arguments & no return value Functions with no arguments but return value Functions with arguments but no return value Functions with arguments and return value Page 70 ©Copyright 2007. which may call function3. The main function may call function1. scanf(“%d“. fact(int). On seeing the name of the function in calling statement.

Page 71 ©Copyright 2007. scanf(“%d%c”.b).i++) printf(“%c“. printf(“\t\t Hello World\n””) border(). &a.sum).8 No Arguments and no return value main() { border(). } border() { int i. printf(“\nSum = %d”. for(i=1. integers\n”). printf(“\t\t Hello World\n””) border(n.c). Cognizant Technology Solutions.i<=80. } add() { int a.&b).int y) { return a+b .s). &n. return(a+b). { int sum. } border(int m.c).a. printf(“\n”).i<=m.&a.9 With arguments and no return value return value main() { int n. return. sum=add(a. printf(“\nSum = %d”. char c. char s) { int i. sum=add(). All Rights Reserved C3: Protected .b. } { int sum.Problem Solving and C Programming Example 9. border(n. } No arguments but return value main() Example 9. printf(“\n”). for(i=1.b. scanf(“%d%d”.&c). return. printf(“Enter2 With main() arguments and printf(“Enter the size of border & style\n”). } } } scanf(“%d%d”. add(int x.i++) printf(“-“).&b).sum).

changes in the formal arguments are reflected in actual arguments. Actual and formal arguments refer to the different memory locations and the value of actual argument is copied into the formal argument. The value of the actual argument will remain same. } Call by Reference In this approach. a.Problem Solving and C Programming Passing arguments to a Function: There are two approaches to pass the information to a function via arguments. The actual and formal arguments refer to the same memory location. a=10. This approach is of practical importance while passing arrays to functions and returning back more than one value to the calling function. Example 9. Note: Actual arguments are address of the ordinary variable. any changes made to the formal argument are not reflected in their corresponding actual arguments. } void swap(int c. b. a x a is actual argument and x is formal argument. swap(a. So. Formal arguments should be a pointer variable or array. b=20. Cognizant Technology Solutions. d = temp. pointer variable or array name.10: Program that illustrates call by value mechanism main() { int a. /* passing the values of a and b to c and d of swap function */ printf(“%d %d”. c = d. the addresses of actual arguments are passed to the function call and the formal arguments will receive the address. int d) /*Function used to swap the values of variables c and d*/ { int temp. Passing arrays to functions is call by reference by default. So. b). The values of the actual arguments are copied in to the respective formal arguments. All Rights Reserved C3: Protected . /* prints 10 20 */ Page 72 ©Copyright 2007. They are: Call by Value Call by Reference Call by Value Arguments are usually passed by value in C function calls. temp = c. b).

i. max_value = val[0]. /* passing the addresses of a and b to c and d of swap function */ printf(“%d %d”. max. To pass an array to a function. b=20. All Rights Reserved C3: Protected . } main() { int values[5]. &b). for( i = 0. i. b). Array name is interpreted as base address of the array and the address is given to the formal argument. Formal argument can be an array or pointer variable. i < 5. it is enough to give the name of the array as argument. a=10. swap(&a. Cognizant Technology Solutions. int *d) { int temp. b. return max_value.12 int { int max_value. *d = temp. Example 9. ++i ) if ( val[i] > max_value ) max_value = val[i]. temp = *c. which points to an array. } /* reference is made */ /* prints 20 10 */ Functions and Arrays It is possible to pass an entire array to a function. maximum( int val[] ) /*size of the array need not be mentioned */ Page 73 ©Copyright 2007.11: Program that illustrates call by reference mechanism main() { int a. Example 9. } void swap(int *c.Problem Solving and C Programming a x a is actual argument and x is formal argument. printf("Enter 5 numbers\n"). *c = *d. a.

Problem Solving and C Programming

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 ); } Passing Multidimensional Arrays Multi dimensional arrays can also be passed in the same manner as single dimensional array, but care must be taken in representing the formal arguments. Example 9.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 74 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Problem Solving and C Programming

Try It Out 1. Problem Statement:
Write a program to print out first 10 numbers in descending order using recursive function

Code:
#include <stdio.h> void recurse(int i); void main(void) { recurse(0); getchar(); } void recurse(int i) { if (i<10) { recurse(i+1); printf("%d ",i); } } Refer File Name: <sesh9_1.c> to obtain soft copy of the program code

How It Works:
This program explains about how to write recursive function The main program calls the recurse function with value 0 as argument In the recurse function, the value is increment and the recurse function is called again. This time it passes 1 as argument. Again in the next step value will be incremented and the recurse function is called. This continues till the value passed is less than 10. Once it is equal to 10, it start printing the value of i. First it will print the value of 10, then it returns from the function and again prints the value as 9 and returns back. This continues till all the function call is completed. Hence the 10 numbers will be printed in descending order.

Page 75 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Problem Solving and C Programming

2. Problem Statement:
Write a program to have functioning returning a value

Code:
/* function that returns value*/ #include <stdio.h> #include <stdlib.h> int getval(void); int main() { int weight; weight=getval(); printf("Entered value is %d\n",weight); getchar(); return(0); } int getval(void) { char input[20]; int x; printf("some integer:"); gets(input); x=atoi(input); return(x); } Refer File Name: <sesh9_2.c> to obtain soft copy of the program code

How It Works:
The main program calls the getval() function. In getval() function, prompts the user to enter some number. It reads the input value and converts to integer form . Then returns the integer value. The main program then prints the value on the screen.

Page 76 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

What is function prototyping? 2. fn(i).i). What is relationship between the actual parameters and its formal parameters? 3. All Rights Reserved C3: Protected . C functions should be considered with three aspects: i) function definition. Functions facilitates reusability and brings logical clarity to the programs. What is the difference between call by reference and call by value? 5. ii) function call. Cognizant Technology Solutions. a). } printf(“%d” . A function calling itself is called recursion. The command line arguments. What is the output of the following code? main() { int a =4. iii) function prototyping Arguments can be passed to a function via call by reference method or by call by value method.Problem Solving and C Programming Summary Functions are smaller self-contained components which carry out some specific. well defined task. C supports four storage class specifiers (auto. } 4. } Page 77 ©Copyright 2007. a). printf("%d". Test your Understanding 1. Arrays can be passed to a function by simply specifying its name. extern and register) to define scope and life time for the variable. argc and argv are used to pass arguments to main() function. { int a = 3. What is the output of the following code? main() { int i=10. } fn(int i) { return ++i. static. printf(“ %d “ .

2. Function prototyping is like a function declaration statement which informs the compiler about the function (its name. 3 4 4. Page 78 ©Copyright 2007. a. int *p(char *a[]) 7. int *p(char *a) c. 3. There must be a one-to-one correspondence between the actual and formal parameters. In call by reference.Problem Solving and C Programming 6. 10 6. a) p is a function which receives a character pointer and returns an integer value b) p is a function which receives a character pointer and returns an integer pointer c) p is a pointer (function pointer) which can point to any function with character argument and integer return value. b. What the following declaration statements imply? a. it is needed only when the function is called prior to its definition. 5. int (*p)(char a) d. int p(char *a) b. Corresponding parameters must be of same type. d) p is a function whose argument is an array of pointers. How main() function is called with parameters? Answers: 1. return data type). In C. only the values of the actual parameters are copied in to corresponding formal parameters. Using command line arguments. type of its arguments. address of the actual parameters are passed to corresponding formal parameters but in call by value. All Rights Reserved C3: Protected . 7. Cognizant Technology Solutions.

it may be accessed anywhere in the current source code file. its scope begins when the variable is defined and ends when it hits the terminating.Problem Solving and C Programming Session 10: Functions/Structures and Unions Learning Objectives After completing this session. Scope The scope of the variable (where it can be used). All Rights Reserved C3: Protected . you will be able to: Use different storage classes in a program Use command line arguments Explain the concept of structures and unions Explain how to declare and initialise Structure Perform operations on structures Perform operation on structures and arrays Perform operation on Structures and functions Storage Classes Variables in C can be characterized by their data type and storage classes. All other types of variables are local variables. Life Time Life time refers to the permanence of a variable – How long the variable will retain its value in memory. The storage-class-specifier can be any one of the following: auto static register extern Page 79 ©Copyright 2007. This means.. Cognizant Technology Solutions. This is called block scope. it has file scope... General Form: storage-class-specifier type-specifier variable-names. is determined by where it is defined. If it is defined outside of all the blocks. Data type refers to the type of information represented by a variable and storage classes define its life time and scope. This is normally called a global variable and is normally defined at the top of the source code. If a variable is defined in a block (encapsulated with {and}).

then its scope is confined to that function. Example 10. Internal variables are those declared inside a function (or block). Because of this property. prints 5 prints 6 Page 80 ©Copyright 2007. They retain the values throughout the life of the program. { int a =6 . they are also called local or internal variables. Static variables are stored in memory. Once allocated. internal static variables retain values between function calls. it is cleared and its memory destroyed.Problem Solving and C Programming Automatic variables (Auto storage class) Automatic variables are local (visible) to the block in which they are declared. When the execution of the block is completed. it will retain the value between function calls. } One important feature of automatic variables is that their value cannot be changed by whatever happens in some other function in the program. memory will be de-allocated after the completion of the program execution. a). If not initialized in the declaration. A variable local to the main function will be normally alive throughout the whole program. } printf(“ %d “ . Static variables (static storage class) Static variables are also local (visible) to the block in which the variable is declared. the nested variables are unique auto variables. a). by default it is an auto variable. with identical names. Local variables of different functions/blocks may have the same name. A static variable may be either internal (local) or external (global). although it is active only in main(). their initial value will be unpredictable (garbage value). Whenever the control again comes to the same block new memory location will be allocated to those variables. a situation similar to function nested auto variables. If not initialized in the declaration statement. They are local or private to the function in which they are declared. So.Thus. In the case recursive functions. If no storage class is specified. printf (“%d “ . It retains its value till the control remains in that block. it is automatically initialized to zero. Cognizant Technology Solutions. If the variable is declared within a function. 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 . All Rights Reserved C3: Protected .1 main() { int a = 5 .

External variables (extern storage class) External variables are not confined to a single function. Access to variables outside of their file scope can also be made by using linkage. the variable is initialized to zero. printf(“ x = %d\n”. x = x +1. It retains its value till the control remains in that block.Problem Solving and C Programming Example 10. Linkage is done by placing the keyword extern prior to a variable declaration. They are referred to as global variables. All Rights Reserved C3: Protected . Since the registers are less in numbers. } Output: x = 1 x = 2 x = 3 x = 4 Register variables (register storage class) It is possible to inform the compiler that a variable should be kept in one of the registers. Cognizant Technology Solutions. Since registers are faster than memory. careful selection must be made for their use. instead of keeping it in the memory. External variables can be accessed from any function and the changes done by one function will be reflected through out the entire scope. for (i=1.2 main() { int i. Their scope extends from the point of definition through the remainder of the program. we must distinguish between: External Variable Definition External Variable Declaration Page 81 ©Copyright 2007. When using external variables. they will be automatically converted into non register variables (automatic variable).i<=5. If the declaration of register variable exceeds the availability. keeping the frequently accessed variables like a loop control variable in a register will increase the execution speed. If not initialized in the declaration. This allows a variable that is defined in another source code file to be accessed. Register variables are local (Visible) to the block in which they declared.i++) incre().x). } incre() { static int x = 0.

just to say that the variable is declared somewhere else in the same program or other programs. printf(“ %d “ . a C program can be executed either by selecting an icon from a graphical user interface or by entering a command in a command window (DOS or UNIX command window). it is initialized to zero. /* external variable declaration. External variable declaration can not have initialization. } int b = 20.3 int a = 5 . /* external variable definition (No need to use extern keyword) */ main() { extern int b. It is usually easier to write programs that are run by entering a command in a command window. When a command is entered in a command window. fun(). 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. it is executed by a command-line interpreter. a). The operation of a command interpreter is quite complex. External variables are useful when working with multiple source files.Problem Solving and C Programming If not initialized in the declaration. b). invalid /* /* prints 10 */ prints 20 */ Command Line Arguments Depending on the operating system and programming environment. The first word is treated as the name of a program. Example 10. The interpreter searches for the program and starts it executing with the command words passed as arguments. */ void fun(). Cognizant Technology Solutions. Page 82 ©Copyright 2007. printf(“ %d “ . interpreter breaks up a command into words separated by spaces. but as a first approximation. extern int a = 10. All Rights Reserved C3: Protected . } void fun() { a = 10 .

Cognizant Technology Solutions. which are command line strings. an employee is represented with the following attributes: employee code (string / integer). } When the following command is given in the command prompt. 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. i < argc. All Rights Reserved C3: Protected . c cpp java The following result is displayed Introduction to Structures and Unions Structures and Unions are the main constructs available in C by which programmers can define new data type.Problem Solving and C Programming main ( int argc. printf(“\n Total Number of Arguments = %d”.i . C:\tc\bin> CMLPGM c cpp java arguments) Number of Arguments = 4 Argument number 0 = CMLPGM Argument number 1 = c Argument number 2 = cpp Argument number 3 = java (CMLPGM program name. char* argv[]) { int i. The components are called Members. i++) printf(“\nArgument number %d = %s”. employee name (string). Example 10.argc). char *argv[]) { : } Where: argc provides a count of the number of command line argument argv is an array of character pointer of undefined size that can be thought of as an array of pointer to strings. salary (float). For example.4 main( int argc. Page 83 ©Copyright 2007. department code (string). argv[i]). A structure is an aggregation of components that can be treated as a single variable. for( i = 0.

.. a separate instance of structure will be created with the name specified and memory will be allocated for that.. Here... type variable-name. tag name is optional.. Example 10. }..5 1) struct employee { int code.. Structure-variables can be declared separately by specifying: struct tag_name new-structure-variable... variable-name....Problem Solving and C Programming Declaration and Initialization 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.... Individual members will be given a separate memory location.. int dept_code. Cognizant Technology Solutions..... : : type variable-name. float salary.. variable-name. Page 84 ©Copyright 2007. type variable-name.... General form: struct tag_name { type variable-name. All Rights Reserved C3: Protected . variable-name. Structure definition and declaration of structure variables can be combined together. emp2. variable-name.. } .. “struct” keyword is used to define structures. struct employee emp1. char name[20]... When declaring structure variables.... no extra structures can be created. Note: If tag name is not specified in the declaration.....

”Dina”. “Raja”. struct stud stud1={101. emp2. char name[20]. 1.Problem Solving and C Programming 2) struct employee { int code. static char[20] empname = “AAAA”. Page 85 ©Copyright 2007. 90. illegal. Initialization Structure variables can be initialized at the time of declaration. then the expression “s. float avg. The format used is quite similar to initializing an array. the member variables are automatically initialized to zero or Null depending on the data type of the member variable. int semester. Example 10. int dept_code. stud2={102. Cognizant Technology Solutions. }.”(dot). No storage class can be specified for structure members. } emp1.m” refers to the value of the member ‘m’ within the structure ‘s’.78}. If it is partially initialized.0 Individual structure members can be initialized only via structure variable. All Rights Reserved C3: Protected . the ‘avg’ will be initialized to 0.6 struct { int rollnum. 1}. (tag name is optional here) char name[20]. If the structure variable is declared before the main function in the global declaration section. } Accessing the members Members of the structure can be accessed by using the member access operator “. float salary. struct employee { int empno = 101 . illegal. uninitialized members are assigned zero or Null. If ‘s’ is a structure variable with a member named ‘m’. stud For the structure variable ‘stud2’.

This is because. Assignment operation is allowed. While comparing structure variables. Example 10. date Page 86 ©Copyright 2007. int month. Note: Member structure must be defined prior to its use. float basic. even though the values stored in the member variables are same. structures can contain members that themselves are structures. }.salary emp2. the values in slack bytes are also compared.name emp1.8 struct emp { int empno. sizeof() operator can be used to find the size of the structure.Problem Solving and C Programming General Form: struct_vble . int year. the assignment expression a = b is valid. For example.sizeof(emp1)). This can be a powerful method to create complex data types. which is always not same for different structure variables. } emp1. char name[20].7 emp1. printf (“Size = %d”. slack bytes are added in-between two member variables and these slack bytes have garbage value. if ‘a’ and ‘b’ are two structure variables of the same structure type. All Rights Reserved C3: Protected .dept_code emp1. Cognizant Technology Solutions. It causes each member of ‘a’ to be assigned the value of the corresponding member of ‘b’. Size = 26 Nested Structure Just as arrays of arrays.code emp1.code emp2.9 struct { int day. Example 10. member-field-name Example 10.name Operations on Structures Two structure variables cannot be compared for equality.

Example 10. struct date doj. }emp1.11: Arrays within structures struct student-mark { int rollnumber. char name[15].avg student[50].emp2. Accessing values: student. }. Example 10. char name[20]. int semester.10 Array of structures struct stud { int rollnum. Cognizant Technology Solutions.semester student [1].name student [1].year Structures and Arrays A structure can be a array of structure and the members of structures can be arrays. int avg. struct stud Accessing values: student [1]. float salary. int dept_code.sub_mark[1] Page 87 ©Copyright 2007. then we can do so by writing: emp1.doj.rollnum student [1]. char name [20]. In this example.Problem Solving and C Programming struct employee { int code.sub_marks[0] }. All Rights Reserved C3: Protected . if we want to access the year of joining of an employee of emp1. }student. int sub_marks[5]. student.

Problem Solving and C Programming Structures and Functions Structures can be passed to a function via call by value and call by reference methods. main( ) { void display(struct emp). display(emp1). “AAAA”} . printf(“ %s “ .12 struct emp { int empno. } Entire structure can be passed to a function using call by reference method. We can use pointer to structures. emp1->empno). }. But changes will not be reflected back. void main( ) { void change(struct emp *). change(&emp1). struct emp emp1 = { 101 . it is passed using call by value method. /* prints 102 */ Page 88 ©Copyright 2007. Example 10. printf(“%d” . All Rights Reserved C3: Protected . struct emp emp1 = { 101 . } void display(struct emp emp2) { printf(“ %d “ .empname). Cognizant Technology Solutions. char empname[10]. “AAAA”} . All the members are copied into corresponding formal arguments. emp2.empno). or we can pass address of the structure variable using & operator. }. When the structure variable (which not a pointer) is passed as an argument to a function.13 struct emp { int empno. Example 10. emp2. char empname[10].

student1.Problem Solving and C Programming } void display(struct emp *emp2) { emp2->empno=102.name. } student1.marks).2f \n". float b) { } function definition Try It Out Problem Statement: Write a program to access the members of structure Code: #include <stdio. } Page 89 ©Copyright 2007. All Rights Reserved C3: Protected . int main ( ) { struct student student3. Function should be declared and defined as: struct tag_name fun_name( struct tag_name struct_vble_name. …) Example 10. wage is a structure variable of sal structure. Cognizant Technology Solutions. strcpy(student1. getchar()."Tom").marks = 99. printf (" Marks are %.9. int a. student2. emp1 is a structure variable of employee structure. float marks. } Function can return a structure type struct_name = fun_name (struct_vble_name). x. printf (" Name is %s \n". student2. student2.14 emp1 = emp_pay (wage.h> struct student { char name[20]. y).name). struct employee emp_pay (struct sal pay.

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.c> to obtain soft copy of the program code How It Works: Declare student structure comprising of name and marks. What distinguishes an array from a structure? 2.Problem Solving and C Programming Refer File Name: <sesh10_1. struct { int a. int *p. Summary Structure is a derived data type used to store heterogeneous data items under a single unit. Structure can be passed to a function by both call by value approach and call by reference approach. Structures can be nested and can also have self reference. only one member is accessible at a time. In unions. Test your Understanding 1. Cognizant Technology Solutions. typedef statement is used to define new data types which are compatible with existing ones. ) operator. What is a self referential structure and where can it be used? 3. enum keyword is used to define enumerations. Structure members can be accessed by structure variables using dot ( . Consider the following structure. How can the content pointed by member pointer p be accessed via structure variable p1? Page 90 ©Copyright 2007. All Rights Reserved C3: Protected . Print the values of the structure. }*p1. In the main program assign values to both member of structure.

What will be the result when the following code is executed? struct stud_type { int rollno. Cognizant Technology Solutions. }ex. 4. struct stud_type s1. int age. Self referential structures will contain a member that is a pointer to the parent structure type. sizeof (ex)).Problem Solving and C Programming 4. All Rights Reserved C3: Protected . 3. 2. union person { char surname[10]. The elements of an array are always of the same type. printf(“Size = %d”. *p1->p. whereas the members of a structure can be of different types. char name[15]. Size = 19 Page 91 ©Copyright 2007. }. Answers: 1. It is very useful in applications that involve linked data structures.

variable-name.. and block file I/O operations Unions Union... the tag name.Problem Solving and C Programming Session 14: Structures and Unions / Files and Preprocessor directives Learning Objectives After completing this session. keyword ‘union’.. union-variable.it creates the type. along with the keyword ‘union’. Cognizant Technology Solutions... you will be able to: Explain how to declare and initialise Unions Perform operations on unions How to use typedef statement How to declare and use enumeration data type Explain the concept of file and its types Perform basic file operations Perform formatted. . like a structure........ Unions follow the same syntax as structures.. type variable-name. Page 92 ©Copyright 2007... General Form: union tag_name { type variable-name. variable-name. In the declaration.. type variable-name... : : type variable-name. unformatted. All Rights Reserved C3: Protected . }union-variable.. the compiler allocates a piece of storage that can accommodate the largest of the specified members... can be used to declare variables of the union type. The programmer is responsible for interpreting the stored values correctly.. No other member can be initialized. Declaration The declaration can be thought of as a template . For each variable... The tag name........... but no storage is allocated. Union differs from structure in storage and in initialization.... and the members of the union are given.. Initialization Union can be initialized only with a value for the first union member. variable-name. is a derived data type. variable-name...

Problem Solving and C Programming Example 14. char c. /* m will be initialized with 100 */ Accessing the member of union The notation used to access a member of a union is identical to that used to access member of a structure. }. Example 14. }.) is used to access the members.2 { int code. char name[20].1 union item { int m. Union of Structures Structures and unions can be members of structures and unions. only one member variable can be accessed at a time. int age. char name[15]. int dept_code. static union item product = {100}. union { char surname[10]. float avg. All Rights Reserved C3: Protected . Thus. Cognizant Technology Solutions. person Union of Structures struct employee_type Page 93 ©Copyright 2007. struct stud_type }ex. struct employee_type e1. s1. }. struct stud_type { int rollno. float x. and as a different variable of a different type on another occasion. The dot operator (. float salary. Union permits a section of memory to be treated as a variable of one type on one occasion.

next value is calculated as previous plus one. Enumerated variables can be declared as follows: storage-class enum tag var1 . As structures. …… 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.e1. similar to structures or a union. but not both. We can also override the 0 start value by assigning some other value. the user can use either e1 or s1. That is. backspace = `\b'. General Form: enum tag { member1 .3 enum escapes { bell = `\a'. newline = `\n'. All Rights Reserved C3: Protected . These constants represent values that can be assigned to corresponding enumeration variables. e1 = getch(). green } Page 94 ©Copyright 2007. return = `\r'} main() { enum escapes e1. } Enumeration variables can be processed in the same manner as other integer variables. to share common memory. vtab = `\v'. if (e1 == newline) printf("newline"). at the same time. blue = 5 . green takes the value 6.Problem Solving and C Programming In the above example. definition and variable declaration can be combined. enum colors { red = 1 . e1 and s1. first enumerated name has index value 0. var2 . tab = `\t’. Cognizant Technology Solutions. Example 14. member2 . The member names must differ from one another. “enum” keyword is used to declare enumerated variables. …………… var n. though they have signed integer values. the union allows the structure variables. Here. Its members are constants that are written as identifiers.salary Enumeration Enumeration is a derived data type. The elements of this union of structures are accessed using dot operator as follows: ex. As with arrays.

struct n1 . Similarly. The input data can be stored on disks and the program may access the data from disks for processing. numbers n1. numbers is the new name given to integer data type and it can be used to declare integer variables.4 typedef numbers int. 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. typedef is mostly useful with structures and unions. All Rights Reserved C3: Protected . n2 . no need to use struct keyword. Then structure variables can be declared as follows. Cognizant Technology Solutions. Streams and Files Page 95 ©Copyright 2007. supplying data through the keyboard during the execution or displaying the output on the screen is not convenient. A file is a place on the disk where a group of related data is stored. Example 14. n2 are the employee is the name given to the structure of the above type. files are needed.Problem Solving and C Programming Typedef Statement The ‘typedef’ allows users to define new data types that are equivalent to existing data types. General Form typedef datatype new-type. }employee. In C. Introduction to Files When a large volume of data is involved.5 typedef { int empno. the results may be stored on disks. For such applications. employee emp1. It is used to give new names to existing data types. integer variables. char empname[10]. emp2. Example 14.

Spaces cannot appear before a newline character. It is simply a long series of 0’s and 1’s. the file position points to the beginning of the file unless the file is opened for an append operation .h. Exiting from the main function causes all open files to be closed. When a file is opened. When a file is closed. ‘FILE’ is a structure that holds the description of a file and is defined in stdio. on some systems. In C. This allows a common method of sending and receiving data amongst the various types of devices available. there are three available streams: Standard input (stdin) is the stream where a program gets its input data Standard output (stdout) is the stream where a program writes its output data. Conversions may occur on text streams during input and output. a text stream removes these spaces even though implementation defines it. A text stream. no more actions can be taken on it until it is opened again. 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. All Rights Reserved C3: Protected . may be able to handle lines of up to 254 characters long (including the terminating new line character).in which case the position points to the end of the file.Problem Solving and C Programming Streams facilitate a way to create a level of abstraction between the program and an input/output device. Each line has zero or more characters and is terminated by a new line character. the tab character. More generally. Standard error (stderr) is another output stream typically used by programs to output error messages. Text streams are composed of a set of lines. Cognizant Technology Solutions. The file position indicates where the next operation (read/write) will occur. There are two types of streams: text and binary. The point of I/O within a file is determined by the file position. Binary streams are composed of only 0’s and 1’s. When a program begins. and the new-line character. But in the binary stream there will be one-to-one mapping because no conversion exists. Basic File operations are: Opening a File Reading from and/or writing into a File Closing the File Page 96 ©Copyright 2007. and all characters will be transferred as such. File Operations Files are associated with streams and must be open in order to use it. Text streams consist of printable characters.

"format string". details. variable list). Where: The ‘fp’ is a file pointer or file handler. (Extensions can be specified like test. The ‘name’ is to represent filename and it is a string of characters. fscanf() and fprintf() ) disconnect the file from the task using fclose() General form: FILE *fp. fscanf(fp. All Rights Reserved C3: Protected .dat etc) The ‘mode’ argument in the fopen() specifies. fclose(fp ). The ‘mode’ can be any of the following: r read text mode 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) rb read binary mode 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) r+ read and write text mode 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) Page 97 ©Copyright 2007. “mode”). variable list). fprintf(fp. It is a string enclosed within double quotes.c.Problem Solving and C Programming The logic is. the purpose/positioning of opening the file. "format string". fp = fopen(“name”. the code must: define a local ‘pointer’ of type FILE ( called file pointer ) ‘open’ the file and associate it with the file pointer via fopen() perform the I/O operations using file I/O functions ( ex. Cognizant Technology Solutions.

all the files opened are closed when the program is terminated. 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.Problem Solving and C Programming 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+ If the file does not exist and it is opened with read mode (r). All Rights Reserved C3: Protected . fclose() returns zero for successful close and returns EOF (end of file) when error is encountered in closing a file. Writing in to a file To write into a file. or fflush(). If the file is opened in the update mode (+). the file must be opened in ‘w’ mode The function putc() is used to write a byte to a file. By default. fopen() returns the file pointer position for successful open and returns NULL. all write operations occur at the end of the file regardless of the current file position. output cannot be directly followed by input and input cannot be directly followed by output without an intervening fseek(). if the file does not open or the file does not exist. because files can be reopened only if they are closed. Page 98 ©Copyright 2007. The Standard I/O provides variety of functions to handle files. rewind(). one character (byte) can be written to or read from a file at a time. If the file is opened with append mode (a). the file open fails and it will return NULL to file pointer. fsetpos(). It is good to close all the files opened with fopen(). Cognizant Technology Solutions.

monitor as a file.”w”)) !=NULL) { while ((c=getchar()) != EOF) putc(c. keyboard as a file. If an error occurs. If an error occurs. Cognizant Technology Solutions.”r”)) !=NULL) { while ((c=getc(fp)) != EOF) Page 99 ©Copyright 2007. The fptr may be stdin. if ((fp=fopen(“sample. which represents a standard input device. char c. This function writes the character ch into a file pointed by the file pointer fptr.dat”. This may be a macro version of fgetc. the character is returned. the error indicator for the stream is set and EOF is returned.7: main() { Program to read a character data from a text file FILE *fp. Example 14. On success. fclose(fp). } Reading from a file The function getc() is used to read a byte from a file.6: Program to create a text file (character file) main() { FILE *fp. On success. After the reading a character. All Rights Reserved C3: Protected . If the end-of-file is encountered. the pointer is moved to the next position. which is true if end of file is reached. This fptr may be stdout.fp). Example 14. This function reads a character from the file and it is returned to the program defined character variable. The EOF is end of file status flag. EOF is returned and the end-of-file indicator is set. General Form: ch =getc (fptr). } else printf(“Error in opening a file”). otherwise false. the character is returned.dat”.fptr).Problem Solving and C Programming General Form: putc(ch. the error indicator for the stream is set and EOF is returned. if ((fp=fopen(“sample. char c. which represents standard output device.

EOF is returned. All Rights Reserved C3: Protected . whichever comes first. } else printf(“Error in opening a file”). On success. A null character is appended to the end of the string. integers can be written to. Writing integer in to a file The function used is putw(). Cognizant Technology Solutions.n. Reading a string from a file The function used is fgets(). On success.fptr). a file at a time. Reads a line from the specified stream and stores it into the string pointed to by str. a nonnegative value is returned. Writing a string in to a file The function used is fputs(). On error. General Form: fputs (str. If the end-of-file occurs before any characters have been read. string can be written to.Problem Solving and C Programming putchar(c). Numeric I/O Using numeric I/O. a pointer to the string is returned. General Form: putw (i. fclose(fp). General Form: fgets(str. a nonnegative value is returned. the string remains unchanged. or the endof-file is reached. the newline character is read. Page 100 ©Copyright 2007. On success. This function writes an integer to a file. fptr). or read from. EOF is returned. On error. or read from. On error. } String I/O Using string I/O. It stops when (n-1) characters are read. Writes a string to the specified stream till the last character is read but does not include the null character. a null pointer is returned. a file at a time. The newline character is copied to the string. fptr).

On success. or the next incompatible character. whose addresses are given in addresses-list.This function will read the formatted data from the file pointed by fptr. carriage return. EOF is returned. Page 101 ©Copyright 2007. Writing formatted data to a file The function fprintf() is used. All Rights Reserved C3: Protected . or the width field is satisfied. new line. Each character in the format string is copied to the stream except for conversion characters which specify a format specifier. Other characters in the format string specify characters that must be matched from the input. format-string. the function stops scanning and returns. If an error occurred. A white space character may match with any white space character such as space. -1 is returned. If an input failure occurs. Formatted I/O The formatted I/O functions can handle a group of data in a single call. Cognizant Technology Solutions. according to the format specifier specified in format string. as specified by the format specifiers in format-string and stores in the variables. variable-list). the number of input fields converted and stored is returned. in a left to right fashion. Reading formatted data from the file The function used is fscanf(). The fscanf() function takes input in a manner that is specified by the format argument and stores each input field into the corresponding arguments. Reads an integer from the file and assigns it to the program defined numeric variable at the LHS. If the input does not match. On success. but are not stored in any of the following arguments. General Form: fprintf ( fptr. General Form: fscanf( fptr. tab. 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. in a left to right fashion. addresses-list). Reading an input field (designated with a conversion specifier) ends when an incompatible character is met. The fprintf() function takes the format string specified by the format argument and applies each following argument to the format specifiers in the string.Problem Solving and C Programming Reading integer from a file The function used is getw(). General Form: i = getw( fptr). vertical tab. or form feed. format-string. This function will write the values stored in the variables into a file pointed by fptr. the number of characters printed is returned.

Cognizant Technology Solutions. The data handled by block input/output function will be in ‘raw data format’ (i.name .Transfers a specified number of bytes beginning at a specified location in memory to a file. i++. The function writes data from the array pointed to by ptr to the given stream. std[i]. std1[i].age). std1[i]. fprintf(fpt . std[i]. bytes of data).age). std1[i]. &std[i]. } } Block I/O Block I/O is used to read or write a specified number of bytes. int age. &std[i]. std[i]. struct { int no.no .name . age )\n\n"). std1[10]. }std[10].dat" .no .age). i<5 . %s %d " . All Rights Reserved C3: Protected .Problem Solving and C Programming Example 14.name . It writes ‘n’ blocks of size Page 102 ©Copyright 2007. "r").e.i++) { scanf("%d %s %d " .8: Program using fscanf() and fprintf() main() { FILE *fpt.age). Writing in to a file The function used is fwrite(). for(i=0.no . while(!feof(fpt)) { fscanf(fpt . } fclose(fpt). std1[i]. &std1[i].dat" . fpt = fopen("details. "w").name printf("%d %s %d \n" .&std1[i]. "%d . Used to write a structure or an array of structures to an output file. fpt = fopen("details. clrscr(). printf("\n\n enter the details (no . name .no . printf("\n\n reading from file \n\n"). "%d %s %d " . char name[10]. int i. std[i].

for(i=0 . printf(" \n\n printing the values "). fptr). fread(&stud1 . Where: ptr size n fp pointer to the data block (source) size of each block (number of bytes to be written) number of blocks to be written file pointer (destination) Reading from a file The function used is fread(). On success the number of elements read is returned. &stud[i].age). int age . fp). On error or end-of-file. fptr=fopen("ex. fptr). }stud[10] . i<5 . On error the total number of elements successfully written (which may be zero) is returned. Reads data from the given stream into the variable pointed to by ptr. 5 . 5 . fwrite(&stud . int i .Problem Solving and C Programming ‘size’. It reads ‘n’ number of elements of size ‘size’.dat" . n. fptr = fopen("ex. The total number of bytes read is (size*n). General Form fread (&str. sizeof(stud[0]) . Page 103 ©Copyright 2007.9: Program using Block I/O main() { FILE *fptr. "r" ). fp). size. sizeof(stud1[0]) . General Form fwrite (ptr. stud1[10]. i++) scanf("%s %d ". All Rights Reserved C3: Protected . fclose(fptr). struct tag { char name[10]. On success the number of elements written is returned. "w" ). The total number of bytes written is (size*n). the total number of elements successfully read (which may be zero) is returned.dat" . size. Cognizant Technology Solutions.name . clrscr().stud[i]. n. Where: &str size n fp destination memory address size of each block (number of bytes to be read) number of blocks to be read file pointer (source) Example 14.

// is in the current line and // if so. // this will be the file I want to read main(int argc. All Rights Reserved C3: Protected .h> #include <stdio. myString). // close the file I opened earlier getchar(). // open the file for reading only while (fgets(myString. // start at 0 lines counted so far inFile = fopen(argv[1]. inFile) != NULL) // keep reading lines { // until I've seen them all count++. Read the first line of the file and increment the line count Page 104 ©Copyright 2007.Print the line number and the line. } Refer File Name: <sesh14_1.count.char *argv[]) { char myString[256]. "name") != NULL) // check to see if 'drawline' printf("Line %d] %s". } Try It Out 1.h> */ FILE * inFile. i<5 .name . print it } fclose(inFile).age). Problem Statement: Write a program to find a word in a file. Code: /* findword.h> /* #include <stdlib. In the main program. // after this command. Cognizant Technology Solutions. // I will use this to count the lines of the file count = 0.Problem Solving and C Programming for(i=0 . count will equal the current line number if (strstr(myString. 255. stud1[i]. // This is where I read the lines of the file int count.c */ #include <string. "r").c> to obtain soft copy of the program code How It Works: Run the program by passing file that needs to searched as command line arguments. read the input argument. Open the input file. stud1[i]. i++) printf("\n %s \t %d " .

"int: ". In the main program declare a variable of union datatype. value. return 0. Code: //Output both value in a union #include <stdio.c> to obtain soft copy of the program code How It Works: Declare a union having two members. value. int main() { union number value.h> union number { int x.y ). Continue till all the lines in the file are processed. value. All Rights Reserved C3: Protected . "double:\n".y = 100. } Refer File Name: <sesh14_2.0. "int: ".x. "Put a value in the integer member". if found print the line number and the full string. "and print both members.". one integer and the other double. Close the file and exit the program 2.".x. value. Problem Statement: Write a program to print both members of union. getchar(). value. "double:\n". "Put a value in the floating member". }. double y.y ).x = 100.Problem Solving and C Programming compare the search key word say ”name” . printf( "%s\n%s\n%s%d\n%s%f\n". Again read the next line in the file and do the same process. value. Page 105 ©Copyright 2007. "and print both members. printf( "%s\n%s\n%s%d\n%s%f\n\n". Cognizant Technology Solutions.

What are the three files automatically associated with every C program? 2.Problem Solving and C Programming First assign the value of x as 100 and print both the members. string I/O. and what value does it usually have? 4. What is the output of the following code? int main() { while(i<10) { fprintf(stdout. Input. Preprocessor directives are identified by # symbol. x will print as 100 and y as 0 Next assign the value of y as 100 and print both the members. All Rights Reserved C3: Protected . Preproccessing is done before compilation. Test your Understanding 1. What is EOF. What does the following statement specifies? fseek( fptr . fclose() functions are used for opening and closing of files."hello-out"). formatted I/O and block I/O. 2) Page 106 ©Copyright 2007. Cognizant Technology Solutions. Preprocessor directives perform i) macro substitution. and rewind() functions. x will print as 0 and y as 100 Summary Files are used to store bulk of related information in secondary storage. Direct access of a file is supported by fseek(). Output operations on files can be of character I/O. } 3. ftell(). ii) file inclusion and iii) conditional compilation. } return 0. i++. fopen(). sleep(1). 2L . Files can be classified as system oriented and stream oriented files.

EOF is a constant returned by many I/O functions to indicate that the end of an input file has been reached. All Rights Reserved C3: Protected . printf(“%d”. stdout. a). What is the output of the following code? #define a 10 foo( ) { #undef a # define a 50 } main( ) { printf(“%d. trying to move file pointer in the forward direction from the end of file. 3. 5. } Answers: 1. Cognizant Technology Solutions. 4.. It will print hello-out in the monitor 10 times.Problem Solving and C Programming 5.a ). Its value on most computers is -1. stdin. stderr 2. foo( ). 50 50 Page 107 ©Copyright 2007. No significance.”.

General Form: fseek( fptr. then the value is a value usable by the fseek() function to return the file position to the current position. If it is a binary stream. then the value is the number of bytes from the beginning of the file. ftell() and rewind(). you will be able to: Access files in both sequential and random order Define pre-processor directives Perform pre-processor operations Perform conditional compilation How to declare and initialise Pointers Understand Pointer Arithmetic Perform operations on Pointers and Arrays Random File Operations The functions discussed earlier are to be used for reading and writing data sequentially. fseek() This function sets the file position to the given offset (specified in long integer format). All Rights Reserved C3: Protected .Problem Solving and C Programming Session 15: Files and Preprocessor directives / Pointers Learning Objectives After completing this session. ftell() This function takes a file pointer and returns a long int. offset. the current file position is returned. This can be achieved by using the functions fseek(). The argument from_where can be: SEEK_SET Seeks from the beginning of the file. which corresponds to the current file pointer position. General Form: n = ftell(fptr). the value -1L is returned and error number (errno) is set. from_where) The argument offset signifies the number of bytes to seek from the given ‘from_where’ position. Page 108 ©Copyright 2007. On success. If it is a text stream. On error. it may be necessary to access some part of the file directly. Cognizant Technology Solutions. 0 1 SEEK_CUR Seeks from the current position. In some applications.

fseek (fp. fseek (fp. Example 15. or carriage return. Embed files within the current file Conditionally compile sections of the current file Generate diagnostic messages Remove the blank lines in the program. All Rights Reserved C3: Protected . 2 On a text stream. Remove comments from the source file. horizontal tab. Preprocessor directives are lines included in the code that are not program statements but directives for the preprocessor. Move the file pointer to the beginning. Preprocessor Directives One of C's most useful features is its preprocessor. change the line number of the next line of source and change the file name of the current file. fseek (fp. Cognizant Technology Solutions. 1). 2). 10L. The preprocessor is executed before the actual compilation of code begins. fseek (fp. 0L. -10L.1 fseek (fp. form feed. vertical tab. The white space allowed on a preprocessor directive may be the space. A token is a series of characters delimited by white space. Move the file pointer to the end of file. The error and end-of-file indicators are reset. On success. 1). 2). from_where should be SEEK_SET and offset should be either zero or a value returned from ftell(). These lines are always preceded by a pound sign (#). 0). Move after 10 bytes from the beginning. zero is returned. fseek (fp. rewind() This function sets the file position to the beginning of the file of the given stream. 10L. On error. The preprocessed source program file must be a valid C program. The error indicator is NOT reset. -10L. Page 109 ©Copyright 2007. General Form: rewind(fptr).Problem Solving and C Programming SEEK_END Seeks from the end of the file. therefore the preprocessor digests all these directives before any executable code is generated for the statements. 0). Preprocessing is a step that takes place before compilation that lets you to: Replace preprocessor tokens in the current file with specified replacement tokens. Move after 10 bytes from the current Move backward 10 bytes from the current Move backward 10 bytes from the EOF. a nonzero value is returned. The end-of-file indicator is reset. 0L.

#line Supplies a line number for compiler messages. #if Conditionally includes or suppresses portions of source code. #pragma Specifies implementation-defined instructions to the compiler. Conditionally includes source text if a macro name is not defined. preprocessor directives can appear anywhere in a program. The # token must appear as a first character. Conditionally includes source text if the previous #if. The preprocessor deletes the \ (and the following new-line character) and splices the physical source lines into continuous logical lines.) is expected at the end of a preprocessor directive. #undef Removes a preprocessor macro definition. Defines a preprocessor macro. #ifdef #ifndef Conditionally includes source text if a macro name is defined. the preprocessor interprets the \ and the new-line character as a continuation marker. or #elif test fails. #ifdef. No semicolon (. Ends conditional text. All Rights Reserved C3: Protected . Preprocessor Directives Name Action # #define #elif #else #endif #error Null directive specifying that no action be performed. Page 110 ©Copyright 2007. #ifndef. If the \ character appears as the last character in the preprocessor line. #ifdef.Problem Solving and C Programming Preprocessor directives begin with the # token followed by a preprocessor keyword. depending on the result of a constant expression. Conditionally includes source text if the previous #if. #include Inserts text from another source file. Cognizant Technology Solutions. Defines text for a compile-time error message. #ifndef. The # is not part of the directive name and can be separated from the name with white spaces. Except for some #pragma directives. or #elif test fails. A preprocessor directive ends at the new-line character unless the last character of the line is the \ (backslash) character.

or until the end of the program source is reached. The preprocessor replaces subsequent occurrences of that identifier with its assigned value until the identifier is undefined with the #undef preprocessor directive. Preprocessing will be done before compilation. Cognizant Technology Solutions. Therefore.2 #include <stdio. File Inclusion The #include directive allows external files to be added in to our source file. 2) Macro substitution and 3) Conditional Compilation.h> #include “stdio.Problem Solving and C Programming Preprocessing Operations: Pre processing operations are mainly classifieds into 1) File Inclusion. Page 111 ©Copyright 2007. standard header files are usually included in angle-brackets. which is then syntactically and semantically analyzed and translated. and then linked as necessary with other programs and libraries. the file is searched first in the current working directory. Example 15.h” Preprocessor Macros: #define preprocessor directive is used to define a macro that assigns a value to an identifier. and then processed by the compiler. In case that it is not there. the file is searched in the directories where the compiler is configured to look for the standard header files. If the file name is enclosed between angle-brackets <>. the compiler searches the file in the default directories where it is configured to look for the standard header files. All Rights Reserved C3: Protected . 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. while other user specificed header files are included using quotes. In the second case where the file name is specified between double-quotes. compilation process operates on the preprocessor output. There are two basic types of macro definitions that you can use to assign a value to an identifer: Object-like Macros (Symbolic constants) Replaces a single identifier with a specified token or constant value. whichever comes first.

. } Page 112 ©Copyright 2007. When the preprocessor encounters that identifier in the program source. Symbolic Constants The preprocessing directives #define and #undef allow the definition of identifiers which hold a certain value. #define General Form: #define symbolicvaraiablename value Example 15.3 #define SIZE 10 #define NAME letters */ “xyz” /* good practice is to use upper case #undef: General Form: #undef variablename Example 15. These identifiers can simply be constants or a macro function. All Rights Reserved C3: Protected . the defined function is inserted in place of the identifier along with any corresponding arguments. Cognizant Technology Solutions.Problem Solving and C Programming Function-like Macros Associates a user-defined function and argument list to an identifier.4 #undef SIZE Macros: General Form: #define macroname(argument list) macrodefn Example: #define sqarea(a) ((a)*(a)) main() { areaofsquare=sqarea(a). ….

. All Rights Reserved C3: Protected . */ (2) */ ((a)*(a)) Conditional Compilation Directives: A preprocessor conditional compilation directive causes the preprocessor to conditionally suppress the compilation of portions of source code.Problem Solving and C Programming Arguments in the macro definition are enclosed with parenthesis to avoid miscalculation. areaofsquare=3+4*3+4. addition=(2)+(3). /* /* areaofsquare = (a) * (a). /* areaofsquare=sqa(3+4). zero or one #else directive. General Form: #if constant_expression #else #endif OR #if constant_expression #elif constant_expression #endif Page 113 ©Copyright 2007. These directives test a constant expression or an identifier to determine which tokens the preprocessor should pass on to the compiler and which tokens should be bypassed during preprocessing.3). Continuation character for macro definition is \. and one matching #endif directive.5 #define sqarea(a) #define sqa(b) b*b #define add(a. There is no need for semicolon after the macro definition. } (1) (2) miscalculation because of no parentheses two semicolons in macro expansion. #ifdef. main() { areaofsquare=sqarea(a).b) ((a)+(b)). The directives are: #if #ifdef #ifndef #else #elif #endif The directives #ifdef and #ifndef allow conditional compiling of certain lines of code based on whether or not an identifier has been defined. Example 15. there are zero or more #elif directives. addition=add(2. /* areaofsquare=sqarea(3). */ areaofsquare = (3) *(3). All the matching directives are considered to be at the same nesting level. */ (1) */ areaofsquare=(3+4)*(3+4). Cognizant Technology Solutions. and #ifndef directive. For each #if. /* areaofsquare=sqarea(3+4).

*/ Page 114 ©Copyright 2007. Example 15.y) x##y main() { …. …. */ Example 15.8 #define name(x.7 #define name(x) #x main() { …. If there is a matching #else. …. printf(name(xyz)). If the value is 0 (false). change the value of that variable to 1 after undefining it. and the constant_expression evaluated to 0 (false). or #endif. Example 15. If there is a matching #elif. #if define(NUMBER) #undef NUMBER #define NUMBER 1 #endif # and ## operators # causes the argument to be converted as a string enclosed within quotes. #elif..somca)). then the lines between the #else and the #endif are compiled. If so. then the compiler skips the lines until the next #else. printf(name(ssn. } ## concatenation operator /* printf(“xyz”). } /* printf(“ssnsomca”).6 Check whether a variable is defined. and the preceding #if evaluated to false. All Rights Reserved C3: Protected .Problem Solving and C Programming The compiler only compiles the code after the #if expression if the constant_expression evaluates to a non-zero value (true). Cognizant Technology Solutions.. 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 nonzero value (true).

5 – value. as they have a number of useful applications. C provides two operators.9 int x. & and *. *px. It is a unary operator that returns the address of its operand. printf(“ Address of a = %u”. & address operator. * Indirection or de-referencing operator. The type-specifiers determine that what kind of variable the pointer variable points to. Whenever a variable is declared. a). Example 15.Problem Solving and C Programming Introduction to Pointers Pointer is a variable that contain the memory address of another variable. memory is allocated for the variable according to the data type specified. int a = 5 . Variables contain the values and pointer variables contain the address of variables that has the value. Pointers are one of the powerful and frequently used features of C. &a). Referencing a value through a pointer is called Indirection. 1000 – assumed as the address of a 1000 printf(“ Value = %d”. It returns the value of the variable to which its operand points. Cognizant Technology Solutions. All Rights Reserved C3: Protected . Declaration General Form: data-type *pointer-name. x = 5 . x 5 1000 px 1000 3000 variables values addresses Page 115 ©Copyright 2007. prints the value 5 prints the address 1000 Declaration and Initialization A pointer variable is declared with an asterisk before the variable name. * and & are inverse of each other. 2 bytes of memory is allocated for variable ‘a’ a 5 a – variable. Variable directly references the value and Pointer variable indirectly references the value. for pointer implementation. px = &x.

A pointer variable can be assigned the value of another pointer variable. invalid . q = p. Two pointer variables can be compared. One pointer can be subtracted from another pointer variable provided both are pointing to same array. px). . All Rights Reserved C3: Protected . b = &a. printf(” address of x = %d “ . *p = &a . Example 15. Pointer variable can not be multiplied or divided by a constant. printf (“ address pointed by pointer = %u”. q = a. hold only the address of the variable of same data type. printf (“address of the pointer = %u”. Cognizant Technology Solutions. valid valid. &px).10 Now execute the following printf statements and observe the results.both p and q is pointing to the memory location of variable a invalid – ordinary variables cannot hold address. *px).Problem Solving and C Programming Example 15. No other constant can be initialized to a pointer variable. Page 116 ©Copyright 2007. printf (“content pointed by pointer = %d”.11 Valid and Invalid pointer assignments int a .cannot assign value to the pointer variable Pointer Arithmetic Pointer Addition or subtraction is done in accordance with the associated data type. int char float long int adds 2 for every increment adds 1 for every increment adds 4 for every increment adds 4 for every increment All the operations can be done on the value pointed by the pointer. prints 5 prints 1000 prints 1000 prints 3000 prints 5 Initialization Pointer variables should be initialized to 0. The following operations can be performed on pointer variables: A pointer variable can be assigned the address of an ordinary variable or it can be a null pointer. The following are the illegal operations on pointers variables: Two pointer variables can not be added. Null or an address. Pointer variable of a particular data type can. x). *q = NULL. &x). printf(“ x = %d “ . An integer quantity can be added to or subtracted from a pointer variable. b .

Compiler treats the subscript as a relative offset from the beginning of the array. so writing array subscripting expressions using pointer notation can save compile time. Array subscripting notation is converted to pointer notation during compilation. let ptr = 1000 (location of i) ptr = 1002 (+2 for integers) increments the value of i by 1 ++*ptr or (*ptr)++ Example 15. *pv is the same as v[0]. *(pv+1) is the same as v[1].12: Pointer arithmetic int * ptr . p2 points to same array) Pointers and Arrays Arrays Array is used to store the similar data items in contiguous memory locations under single name. Array elements are accessed using pointer variable. ptr ++. ptr= &i.13: Pointer operations Legal operations p1 > p2 p1==p2 Illegal operations p1/p2 p1*p2 p1+p2 p1/5 p1+2 p1-p2 (if p1. All Rights Reserved C3: Protected . Array addressing is in the form of relative addressing. Cognizant Technology Solutions.Problem Solving and C Programming Example 15. and so on. conventional array is declared and pointer variable can be made to point to the starting location of the array. if v is an array. C treats the name of the array as if it is a pointer to the first element. i=5. Thus. Page 117 ©Copyright 2007. Exact location of the elements can be accessed directly by assigning the starting location of the array to the pointer variable. Pointers Pointer addressing is in the form of absolute addressing. Pointer pointing to an array Initialization To initialize a pointer variable. The pointer variable is incremented to find the next element.

Accessing address Example 15. 4. Example 15. Example 15. &a[0] = 1000 &a[1] = 1002 &a[2] = 1004 &a[3] = 1006 &a[4] = 1008 Accessing value Example 15. All Rights Reserved C3: Protected . Cognizant Technology Solutions. Page 118 ©Copyright 2007.15 printf (“%d “.2.16 printf (“%u “. a[0] = 1 a[1] = 2 a[2] = 3 a[3] = 4 a[4] = 5 ptr + 0 = 1000 ptr + 1 = 1002 ptr + 2 = 1004 ptr + 3 = 1006 ptr + 4 = 1008 *(ptr+0) *(ptr+1) *(ptr+2) *(ptr+3) *(ptr+4) = 1 = 2 = 3 = 4 = 5 Assume that array starts at location 1000 Pointers and Multi Dimensional Arrays As the internal representation of a multi dimensional array is also linear. similar to ptr = &a[0].17 int a[2][2] = {1.*(ptr+i)). General Form: ptr_vble = &array_name [starting index1]…[starting indexn].3. The way in which the pointer variable used. *ptr .*ptr). printf (“%d “. OR pointer_variable = array_name.4} . OR ptr_vble = array_name.14 int a[5] = {1. (ptr+i)). displays address of a(i) displays the a[i] value displays the a[0] value displays the a[i] value .2. Assume that the array starts at location 1000 &a[0][0] = 1000 &a[0][1] = 1002 &a[1][0] = 1004 &a[1][1] = 1006 a[0][0] = 1 a[0][1] = 2 a[1][0] = 3 a[1][1] = 4 ptr+0 = 1000 ptr+1 = 1002 ptr+2 = 1004 ptr+3 = 1006 *(ptr+0) = 1 *(ptr+1) = 2 *(ptr+2) = 3 *(ptr+3) = 4 *ptr .5} ptr = a .Problem Solving and C Programming General Form: pointer_variable = &array_name [starting index]. i .3. ptr = &a[0][0] .*(a+i)). varies according to the dimension. printf (“%d “. a pointer variable can point to an array of any dimension.

printf (“%d “. int a[3][2] can be represented by a pointer as follows: int (*p)[2] p is a pointer points to a set of one dimensional array. Cognizant Technology Solutions. (*(ptr + i) +j) is a pointer to jth element in ith row *(*(ptr+i) + j)) refers to the content available in ith row.j++) printf(“\t%d”.*(a + i)[ j ].Problem Solving and C Programming If the pointer to the array is accessed with 2 subscripts. int a[2][3]={1. For example. printf (“%d “. All Rights Reserved C3: Protected . multi dimensional arrays can be represented by pointer in the following two ways: Pointer to a group of arrays Array of pointers Pointer to a group of arrays A two dimensional array. Here.19 main() { int i.4.actually a pointer to the first element in i th row. Page 119 ©Copyright 2007. is a collection of one dimensional array. jth column Accessing value Example 15. each with 2 elements.j<3. So.j) value Example 15.5. Therefore.j) value displays the x(i. a twodimensional array is defined as a pointer to a group of one dimensional array and in the same way three dimensional arrays can be represented by a pointer to a group of two dimensional arrays.j) value displays the x(i. refers to the entire row .i<2.18 printf (“%d “. for (i=0. int *pa=&a[0][0]. j. for example. The following representations are used when a pointer is pointing to a 2D array: ptr+i *(ptr+i) is a pointer to ith row. displays the x(i. Note: First dimension need not be specified but the second dimension has to be specified. a single pointer is used and it needs to know how many columns are there in a row.*(*(pa+i)+j)).2.3.*(a[ i ] + j). (p+0) + 1 (p+1) + 0 if it is used to represent 0th row and 1st column if it is used to represent 1st row and 0th column and results in p+1.i++) { for (j=0.6}.*(*(ptr + i) +j). it results in a problem.

4} . } } Output: 1 4 2 5 3 6 Array of Pointers Multi dimensional array can also be expressed in terms of an array of pointers. we have 2 pointers ptr[0]. only one indirection is enough to represent a particular element. it refers to the address of the 0th element. All Rights Reserved C3: Protected . We can declare a character pointer as follows: char *p = NULL.20 int a[2][2] = {1. Cognizant Technology Solutions. ptr[0] = a[0]. int a[2][2] can be represented as int *ptr[2] Here. Thus.21 (1) (2) *p[3] (*p)[3] declares p as an array of 3 pointers declares p as a pointer to a set of one dimensional array of 3 elements Pointers and Strings Character pointer is a pointer. Example 15. Once the pointer is declared. When an array is referenced by its name. p = name. Page 120 ©Copyright 2007. if we have a character array declared as: char name[30] = {“Data Structures”}.3. which can hold the address of a character variable. Suppose.2.Problem Solving and C Programming printf(“\n”). the address of the array is assigned to this pointer. *ptr[2] . /* 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 ptr[0] + 0 ptr[0] + 1 ptr[1] + 0 ptr[1] + 1 = 1000 = 1002 = 1004 = 1006 *(ptr[0] + 0) *(ptr[0] + 1) *(ptr[1] + 0) *(ptr[1] + 1) = = = = 1 2 3 4 ( & a[1][0]) */ Example 15. ptr[1] and each pointer can point to a particular row .

char names[3][10] = { “abcde”. When a pointer variable is referred with the indirection operator. It declares 4 Page 121 ©Copyright 2007. 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. Pointer automatically gets incremented to the next location. “ABCD”} . a set of initial values can be specified as part of the array declaration. Array of character pointers : char *name[10].1. Instead of making each row a fixed number of characters. *p). printf(“String output = %s”. make it a pointer to a string of varying length. An array of character pointers offers a convenient method for storing strings. Cognizant Technology Solutions.Problem Solving and C Programming The statement assigns the address of the 0th element to p. “xyz”}. This array occupies 30 bytes and the row length is fixed.3} . it refers the content of the address pointed by the pointer variable.2. “ABC” . valid invalid Thus. If the elements of array are string pointers. Character-type pointer variable can be assigned an entire string as a part of its variable declaration. Each pointer is used to represent a particular string. *p). Conventional array declaration: char name[10][10]. char *p = “string” . “AB” . The above statement allocates variable length block of memory and occupies only 14 bytes. Ragged Arrays Consider the following array declaration. char *name[4] = { “A” . int *p = {0. An advantage is that a fixed block of memory need not be reserved in advance. All Rights Reserved C3: Protected . “rstu”. Now issue the following printf statements and check the output: printf(“Character output = %c\n”. string can be represented by either as a one-dimensional character array or a character pointer. which will print the string till it encounters a ‘\0’ character.

Wise to avoid such assignments */ Variable ‘a’ is a constant variable.24 int a. Pointer variable ‘pa’ can take any other address and value of ‘a’ can be changed using pointer even though it is constant variable. Thus. /* suspicious pointer conversion. The value cannot be modified. pointer ‘ps’ is stored in 2 bytes and ‘ps’ contains the address of the string that requires 4 bytes. Arrays of this type are referred as Ragged arrays (used only in the initialization of string arrays). In the above example. *(name + 1) will access the string AB * (name + 2) will access the string ABC *(*(name + i) +j) refers the jth character in ith string *(*(name+3)+3) refers D in the string “ABCD” Memory organization – String Pointers Example 15. (2) char s[ ] = “xyz”.23 const int a=10. All Rights Reserved C3: Protected . int *pa = &a. Example 15. Pointers variables that are declared ‘const’ must be initialized when they are declared. Constant pointer to constant data always points to the same memory location and the data at that memory location cannot be modified. substantial saving in memory. int *const pa = &a.Problem Solving and C Programming pointers each pointing to a string. The following example explains the pointer variable to a constant variable: Example 15. Pointer to a constant The address of a constant variable can be assigned to a pointer variable. A pointer variable can take the address of a non-constant data and constant data. Page 122 ©Copyright 2007. Constant Pointer The pointer variable can be a constant. 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. string ‘s’ is stored in 4 bytes.22 (1) char *ps = “xyz”. Cognizant Technology Solutions.

All Rights Reserved C3: Protected . *(float *) pab = 105. const int * const pb = &b.Problem Solving and C Programming Example 15. *(int *) pab =100. pab=&b. ++*pnum. long *pnum = NULL. The generic pointer can be made to point any data type. num1. num2. long num2 = 0. getchar(). pab=&a. Generic Pointer (void Pointer / Pointer to void) The type void * is used to declare generic pointers. when dereferencing the content using void pointer. ++num2. Problem Statement: Write a program to change the value of variable through pointer Code: //Change value of variable through pointer #include <stdio. Try It Out 1. pnum = &num2. *pnum.26 int a.h> int main(void) { long num1 = 0. pnum = &num1. Page 123 ©Copyright 2007. void *pab. printf ("\nnum1 = %ld num2 = %ld *pnum = %ld *pnum + num2 = %ld\n".25 int b. *pnum = 2. float b. But it is needed. Type casting is not needed during address assignment. *pnum + num2). Cognizant Technology Solutions. Example 15. in order to know the size and value of the data item. num2 += *pnum.55.

now the value of num2 is 1.num2. Cognizant Technology Solutions.c> to obtain soft copy of the program code How It Works: This program gives a hands-on on usage of pointer. Then num2 equals the num2 _ value at pnum i. int j.Problem Solving and C Programming return 0.h> main(){ int *a[5]. } Refer File Name: <sesh15_1. Address in array Value\n").i2=3.a[j]). Print all the values num1. Then the value of num1 is 2. Initialize num1 and num2 to 0 Assign the address of num1 to pointer pnum.i3=2.i5=0. a[0]=&i1. First two integer variable num1 and num2 and a pointer to an integer are declared. %16u %d\n".j<5. a[3]=&i4. #include <stdio.j++) { printf("%16u a[j]. a[4]=&i5. } printf("using pointer\n"). int i1=4. Then assign the value of 2 to pnum. Increment the value of num2. All Rights Reserved C3: Protected . 1+2 = 3(value of num2) Assign the address of num2 to pnum and do increment of value at pnum. printf("Address for(j=0.i4=1. a[1]=&i2.a[j]. Now the value at pnum is 4 and num2 is 4. a[2]=&i3.value at pnum 2. Problem Statement: Write a program to use array of pointers Code: //In the pointer array. the array elements is the pointer.e. int *b. Page 124 ©Copyright 2007.

c> to obtain soft copy of the program code How It Works: This program explains the usage of array of pointers. Cognizant Technology Solutions. 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.j++) { printf("value of elements %d %16lu\n". What is the use of generic pointers? Page 125 ©Copyright 2007. for( j=0. b++. free() function is used to de-allocate the memory. Pointer can point to an array of any dimensions.*b. & operator is used to refer the address of a variable and * operator is used for dereferencing the pointer. Address of the memory location can be assigned to ordinary variables c. calloc() functions are used to allocate memory dynamically. Declare five integer variable and and store their address in the array. } Refer File Name: <sesh15_2. Summary Pointer is a variable which can hold the address of another variable.Problem Solving and C Programming b = a. } getchar().*b. Then print the value in the array by using array indices and using pointers. State whether the following are true or false a. All Rights Reserved C3: Protected .b).j<5. See the difference. malloc(). Pointer variable can only contain an address b. Size of the pointer variable is equivalent to the size of the data item it points. Test your Understanding 1. Each element of array is an pointer which holds the address of an integer varaiable. Pointer can refer to the content of the memory location by & operator d. 2. Declare an array of integer pointers.

Given the following declaration: int a. Answers: 1. 5. What is the output of the following code? main() { int n[25]. Differentiate malloc() . Since c points to b. Since b points to a. malloc(). because values cannot be assigned to pointers. All Rights Reserved C3: Protected . b = (int *)**c.Problem Solving and C Programming 3. What is the output of the following code? main( ) { char *str1=”abcd”.%d". printf(“%d %d %d”. 300 4. sizeof(str1). **c=5. 2 5 5 6.sizeof(str2). } 6. The third statement castes **c. n[0]=100. 3. What is the output of the following statements? a=4. *(n+24)+*(n+0) ). Generic pointers (void pointers) can point to data items of any type. char str2[]=”abcd”. into type int *. Cognizant Technology Solutions. The result is meaningless. 5. *b = &a . this is same as assigning 5 to the location pointed to by b. printf("\n%d. The first statement assigns 4 to a. false. which is value of a. n[24]=200. false. assign the value to a. calloc(). calloc() will both allocate the memory dynamically. false 2. 100. but the difference is calloc() will return a contiguous memory location and initializes it to 0. sizeof(“abcd”)). *n. True. The second statement assigns 5 to the location pointed to by the location pointed to by c. Page 126 ©Copyright 2007. } 4. **c = &b. this statement is equivalent to assigning 5 to a.

*p) . } /* q is a pointer which will point to the memory location pointed by p */ Example 17. p = assign() . All Rights Reserved C3: Protected . /* function prototype */ void change(int *). Example 17.function returning an integer pointer */ int *assign() Page 127 ©Copyright 2007. change(p). } void change(int *q) { *q = 10.1: Passing pointers as argument main() { int a =5 . you will be able to: How to use Pointers with functions How to use Pointers with structures How to implement Dynamic memory allocation in creating a linked lists. Cognizant Technology Solutions. p =&a.2: Function returning pointer main() { int *p . Functions and Pointers Pointers can be passed to a function as arguments and a function can also return a pointer to the calling program.Problem Solving and C Programming Session 17: Pointers Learning Objectives After completing this session. printf(‘’ %d ‘’ . a). int *assign() . } /* will print 20 */ /* function prototype . /* pointer p is passed to a function – call by reference */ /* prints 10 */ printf(“ %d “ . *p.

x + y). *q = 20 . int *y) { if (*x > *y) return (x). All Rights Reserved C3: Protected . of a is returned */ /* addr. of b is returned */ /* address of the variable a or b will be stored in p */ Page 128 ©Copyright 2007. rather than an entire array. So. to a function using pointers. makes the pointer to point to the function add() Note: function name specifies the starting address. return q .*p). p = big (&a.Problem Solving and C Programming { int a .. } Pointer to this function is declared as. main() { int a=10. &b). *p.3: Function receiving pointers and returning pointer int *big (int * . p = add. else return (y). } It is possible to pass a portion of an array.) Suppose we have a function as. Function Pointer Function will also have a memory address like other variables. } Example 17. printf (“%d”. void add(int x. General Form: return-type (* function_pointer_name)(argument list. 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. ‘p’ is a pointer which can point to a function having two integer arguments and returning an integer value. void (*p)(int x. which will speeds up the execution. int y). *q = &a. /* addr. int y) { printf(“Value = %d”. Cognizant Technology Solutions. b=20. } int *big (int *x . int *).

}.20 /*invokes the function display */ Example 17. It will be useful when an entire structure is passed to a function via call by reference.67}. To make ‘ptr’ to point to the structure ‘student’. *ptr . which can hold an address of a variable of the type ‘student’. will call the function add() with parameters 10. Cognizant Technology Solutions. /* calling the function by function pointer */ } void abc() { printf(“function”). abc(). char name[20].Problem Solving and C Programming (*p)(10.”raja”. All Rights Reserved C3: Protected . In this declaration. 95. ‘ptr’ is a pointer type variable. struct stud student={101. Page 129 ©Copyright 2007.20). } Output: functionfunction Structures and Pointers Structure variable can be declared as pointers.5 main() { void abc(). float avg. (*func_ptr) (). Example 17. we can write as ptr = &student. 1.6 struct stud { int rollnum. func_ptr = display. int semester.4 int display(). (*abc)(). int (*func_ptr) (). Example 17. Pointer declaration to a structure is as follows: struct student *ptr.

free() These functions provides the ability to reserve as much memory as may required during program execution.Problem Solving and C Programming Accessing a member through pointer variable The notation for referring a member field of a structure pointed by a pointer is as follows: (*pointer). 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. p = (int *) malloc ( 10 * sizeof(int)) .8 struct employee { char name[20]. calloc () . Page 130 ©Copyright 2007. ptr->rollnum. and then release this memory when it is no longer required. Dynamic Memory Allocation Conventional arrays are static in nature. float salary. because size has to be mentioned in the declaration statement itself and fixed block of memory is reserved during the compilation. It is used to build various kinds of linked data structures. Self-Referential structures A structure containing a member that is a pointer to the same structure type is called selfreferential structures. ptr->name. C supports dynamic memory allocation through the following functions: malloc(). memberfieldname (OR) pointer -> memberfieldname Example 17. char gender. ptr->avg).7 printf(“ %d \t %s \t %d \t %f “. Example 17. All Rights Reserved C3: Protected . int *p. Thus. ptr->semester. Cognizant Technology Solutions. struct employee *empptr.

c[i] = (int *)malloc( 3 * sizeof(int)). This can be used to allocate space for arrays and structures. j++) printf("\t%d". printf("\n enter the values of second matrix"). A one dimensional dynamic array can be declared using pointers as follows: int *p.j. for(i=0 .Problem Solving and C Programming The above program constructs will return memory block of 20 bytes. for(i=0. } Page 131 ©Copyright 2007. /* memory is allocated to individual pointers */ b[i] = (int *)malloc( 3 * sizeof(int)). i<3. a[i]+j). j<3. j<3. All Rights Reserved C3: Protected . b[i]+j). j++) *(c[i]+j) = *(a[i]+j) + *(b[i]+j). int i. i++) { a[i] = (int *)malloc( 3 * sizeof(int)). i++ for(j=0.9: Program for adding two matrices using array of pointers void main() { int *a[3] . i<3. i<3. *b[3] . which can hold 10 integers. j++) scanf("%d". for(i=0. } printf(" \n enter the values of matrix 1 \n"). Cognizant Technology Solutions. j++) scanf("%d". i++) for(j=0. i++) for(j=0. *c[3]. *(c[i]+j)). p = (int *) calloc (10. This will return 10 continuous memory blocks of 2 bytes each and initializes them to 0. i<3. free() will take a void pointer. for(i=0. for(i=0. i<3. Example 17. The starting address is pointed by the pointer ‘p’. free(p) will release the memory pointed by a pointer variable ‘p’. i++) for(j=0. j<3. j<3. sizeof(int)).

there is no restriction imposed by the compiler as to how many levels we can go about in using a pointer. video memory. beyond 3 levels. it makes the program difficult to understand and may cause the illegal memory references *p1 addr. For example. Example 17. Cognizant Technology Solutions. it will provide enhanced performance Pass by reference is possible only through the usage of pointers. p2=&p1. However.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.ptr2 x=100. represents 2 dimensional array In the above declaration p is a pointer variable.**p2. it will make the code highly complex and un-maintainable. we can refer to any part of the hardware like keyboard. As such. it cause memory leakages If not used properly. p1=&x. which holds the address of another integer pointer. All Rights Reserved C3: Protected . printer. Page 132 ©Copyright 2007. etc directly As working with pointers is like working with memory. 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) Limitations If the allocated memory is not freed properly.*p1.10 addr.ptr1 value int x. To access the value we can use either **p2 or Advantages It gives direct control over memory and thus we can play around with memory by all possible means. int **p. The following declaration is perfectly valid: int *****p.

Problem Statement: Write a program to access structure using pointers Code: #include <stdio.face = "Ace". Print the values of card structure in three different forms. char *suit. }. ( *cardPtr ).suit = "Spades".suit ). aCard. Page 133 ©Copyright 2007. All Rights Reserved C3: Protected . Cognizant Technology Solutions. cardPtr->face.h> struct card { char *face. aCard.face. printf( "%s%s%s\n%s%s%s\n%s%s%s\n". In the main program.face. ( *cardPtr ).suit. getchar(). aCard. int main() { struct card aCard. aCard.c> to obtain soft copy of the program code How It Works: Declare a structure card having face and suit as two pointers to char. All will print the same. declare a variable using card structure and pointer variable pointing to card structure. } Refer File Name: <sesh17_1. return 0. struct card *cardPtr.Problem Solving and C Programming Try It Out 1. " of ". " of ". cardPtr = &aCard. cardPtr->suit. " of ". Assign the values of face and suit of card structure.

All Rights Reserved C3: Protected . if(p==NULL){ p=(struct node *)malloc(sizeof(struct node)). Problem Statement: Write a program to insert values in a linked list Code: # include <stdio. while (temp-> link != p) temp = temp-> link.h> struct node { int data. } p-> data = n.h> # include <stdlib. exit(0). if(temp -> link == NULL){ printf("Error\n"). } else { temp = p. printf("The data values in the list are\n"). } temp = temp-> link. Cognizant Technology Solutions. temp-> data = n. p-> link = p. int n){ struct node *temp. if(p==NULL) { printf("Error\n"). }. } void printlist ( struct node *p ) { struct node *temp.Problem Solving and C Programming 2. temp = p. struct node *link. } return (p). struct node *insert(struct node *p. if(p!= NULL) Page 134 ©Copyright 2007. temp-> link = (struct node *)malloc(sizeof(struct node)). temp-> link = p. exit(0).

Problem Solving and C Programming { do { printf("%d\t". Call a function insert() and pass the start pointer and the value 1 as argument to the function. } void main() { int n. 3 ). All Rights Reserved C3: Protected . printf("The created list is\n"). struct node *start = NULL . 1 ). Then allocate memory and assign data as 2 and link pointing to the same pointer p. start = insert ( start.c> to obtain soft copy of the program code How It Works: Declare a structure node with data as the one of the member and the link as the other member which is a pointer to same structure which will hold the address of next node.temp->data). getchar(). so it goes to the else part and traverse the linked list till the last node. In the main program.as it is first time. again insert() function is called with the returned pointer from previous call and the value as 2. Now the start pointer is not NULL. } while (temp!= p). Then returns back the pointer. } else printf("The list is empty\n"). start = insert ( start. start = insert ( start. int x. In the insert function. } Refer File Name: <sesh17_2. temp=temp->link. Then returns the pointer back. In the main program. Cognizant Technology Solutions. the start pointer will be NULL. so it will allocate memory and assign the value of data as 1 and the link pointing to the same pointer p. declare a pointer variable start pointing to struct node and initialize to NULL. start = insert ( start. Page 135 ©Copyright 2007. 4 ). 2). printlist ( start ).

& 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. calloc() functions are used to allocate memory dynamically. *(n+24)+*(n+0) ). 2. Now four data’s has been inserted in to the linked list. Cognizant Technology Solutions. 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. State whether the following are true or false a. n[24]=200. using do while loop traverse through the linked list and print all the values. Test your Understanding 1. *b = &a . Page 136 ©Copyright 2007. n[0]=100. free() function is used to de-allocate the memory. malloc(). In the main program call the printlist() function to print all the data in the linked list. What is the output of the following code? main() { int n[25]. What is the output of the following statements? a=4. *n. All Rights Reserved C3: Protected . } 4. What is the use of generic pointers? 3.Problem Solving and C Programming Same is continued for next two insert function call. printf("\n%d. b = (int *)**c. Pointer variable can only contain an address b. Size of the pointer variable is equivalent to the size of the data item it points.%d". In the printlist() function. Summary Pointer is a variable which can hold the address of another variable. **c = &b. Given the following declaration: int a. Pointer can refer to the content of the memory location by & operator d. Address of the memory location can be assigned to ordinary variables c. **c=5.

The second statement assigns 5 to the location pointed to by the location pointed to by c. this statement is equivalent to assigning 5 to a. All Rights Reserved C3: Protected . sizeof(“abcd”)). char str2[]=”abcd”. but the difference is calloc() will return a contiguous memory location and initializes it to 0. into type int *. malloc(). 5. assign the value to a. calloc(). The first statement assigns 4 to a. which is value of a. 100.sizeof(str2). Since b points to a. Since c points to b. } 6. 2 5 5 6. Generic pointers (void pointers) can point to data items of any type. because values cannot be assigned to pointers. 300 4. Answers: 1. this is same as assigning 5 to the location pointed to by b. sizeof(str1). false 2. 3. Cognizant Technology Solutions. Differentiate malloc() . false. True. What is the output of the following code? main( ) { char *str1=”abcd”. calloc() will both allocate the memory dynamically. The third statement castes **c. Page 137 ©Copyright 2007. false.Problem Solving and C Programming 5. printf(“%d %d %d”. The result is meaningless.

#define max(A. Cognizant Technology Solutions.: : : ) type name main() { declarations statements } type fnc(arg1.Problem Solving and C Programming Syntax Summary Program Structure/Functions type fnc(type1. } /* */ main(int argc. #endif #ifdef. #elif. char *argv[]) exit(arg) C Preprocessor #include <filename> #include "filename" #define #define name(var) #undef name # ## #if. #else.B) ((A)>(B) ? (A) : (B)) undefine quoted string in replace concatenate args and rescan conditional execution is name defined.: : : ) { declarations statements return value. not defined? defined(name) \ function declarations external variable declarations main routine local variable declarations function definition local variable declarations comments main with args terminate execution Page 138 ©Copyright 2007. #ifndef name defined? line continuation char include library file include user file name text replacement text text replacement macro Example. All Rights Reserved C3: Protected .

float enumeration constant constant (unchanging) value declare external variable register variable local to source file no value structure create name by data type t size of an object (type is size_t) size of a data type (type is size_t) Initialization initialize variable initialize array initialize char string Constants long (suffix) float (suffix) exponential form octal (prefix zero) hexadecimal (prefix zero-ex) character constant (char. Cognizant Technology Solutions. \t.Problem Solving and C Programming Data Types/Declarations character (1 byte) integer float (single precision) float (double precision) short (16 bit integer) long (32 bit integer) positive and negative only positive pointer to int. \" "abc: : : de" type name=value type name[]={value1. ‘\xhh’ \n. \?. octal.: : : } char name[]="string" char int float double short long signed unsigned *int. ‘\ooo’. \. tab. cr. \r. All Rights Reserved C3: Protected . \b \\. hex) newline. *float enum const extern register static void struct typedef typename sizeof object sizeof(type name) Page 139 ©Copyright 2007. backspace special characters string constant (ends with \0) L or l F or f e 0 0x or 0X ‘a’.

minus. -. address of object cast expression to type size of an object multiply. &name (type) expr sizeof *. >> >. /. Arrays & Structures declare pointer to type declare function returning pointer to type type declare pointer to function returning type type generic pointer type null pointer object pointed to by pointer address of object name array multi-dim array Structures struct tag { declarations }.x and p->x are the same union member : b Operators (grouped by precedence) structure member operator structure pointer increment. modulus (remainder) add. Cognizant Technology Solutions. !.member pointer -> member Ex. decrement plus. <<. != & ^ | && structure template declaration of members type *name *f() (*pf)() void * NULL *pointer &name name[dim] name[dim1][dim2]…. struct tag name name. All Rights Reserved C3: Protected . <.member pointer->member ++. % +. logical not. subtract left. multiple type structure bit field with b bits Page 140 ©Copyright 2007. <= ==.Problem Solving and C Programming Pointers. -+. right shift [bit ops] comparisons comparisons bitwise and bitwise exclusive or bitwise or (incl) logical and name. create structure member of structure from template member of pointed to structure single value. ~ *pointer. divide. >=. bitwise not indirection via pointer. (*p).

h> <time. {} break continue goto label label: return expr while statement for statement do statement switch statement if (expr) statement else if (expr) statement else statement while (expr) statement for (expr 1.h> <stdarg.Problem Solving and C Programming logical or conditional expression assignment operators expression evaluation separator || expr1 ? expr2 : expr3 +=.h> <ctype. all others group left to right.h> <limits. Unary operators. while.h> <stddef.h> <locale.h> Page 141 ©Copyright 2007. expr2. do.h> <stdio. …… .h> <float. conditional expression and assignment operators group right to left. for go to Label Return value from function Flow Constructions if statement .h> <setjmp.h> <math. Cognizant Technology Solutions.h> <signal. All Rights Reserved C3: Protected . do. switch (expr) { case const1: statement1 break.h> <string. *=. default: statement } ANSI Standard Libraries <assert.h> <errno.h> <stdlib. Flow of Control Statement terminator Block delimiters Exit from switch. -=. case const2: statement2 break. for Next iteration of while. expr3) statement do statement while(expr ).

c) strrchr(cs. Cognizant Technology Solutions.n) strchr(cs. digit Checks whether c is a Space. cr. newline. letter.ct.ct) strncpy(s.ct.ct. All Rights Reserved C3: Protected .ct.c.n) strcat(s.ct) strncmp(cs.n) memchr(cs. vtab Checks whether c is a upper case letter Checks whether c is a hexadecimal digit Convert c to lower case Convert c to upper case String Operations <string.ct. form feed.h> Functions isalnum(c) isalpha(c) iscntrl(c) isdigit(c) isgraph(c) islower(c) isprint(c) ispunct(c) isspace(c) isupper(c) isxdigit(c) tolower(c) toupper(c) Functionalities Checks whether c is alphanumeric Checks whether c is alphabetic Checks whether c is a control character Checks whether c is a decimal digit Checks whether c is a printing character (not incl space) Checks whether c is a lower case letter Checks whether c is a printing character (incl space) Checks whether c is a printing char except space. ct are constant strings Functions strlen(s) strcpy(s.Problem Solving and C Programming Character Class Tests <ctype.n) strcmp(cs. t are strings and cs.n) memmove(s.ct) strncat(s.ct.c.n) Functionalities Returns the length of s Copies ct to s Copies up to n chars to s Concatenate ct after s Concatenate up to n chars Compares cs to ct Compares only first n chars Pointer to first c in cs Pointer to last c in cs Copy n chars from ct to s Copy n chars from ct to s (may overlap) Compare n chars of cs with ct Pointer to first c in first n chars of cs Put c into first n chars of cs Page 142 ©Copyright 2007.n) memcmp(cs.h> Consider s.c) memcpy(s.n) memset(s. tab.

Problem Solving and C Programming

Input/Output <stdio.h> Standard I/O Standard input stream Standard output stream Standard error stream End of file Get a character Print a character Print formatted data Print to string s Read formatted data Read from string s Read line to string s (< max chars) Print string s File I/O Declare file pointer Pointer to named file Get a character Write a character Write to file Read from file Close file Non-zero if error Non-zero if EOF Read line to string s (< max chars) Write string s FILE *fp fopen("name","mode") Where modes: r (read), w (write), a (append) getc(fp) putc(chr ,fp) fprintf(fp,"format",arg 1,: : : ) fscanf(fp,"format",arg 1,: : : ) fclose(fp) ferror(fp) feof(fp) fgets(s,max,fp) fputs(s,fp) stdin stdout stderr EOF getchar() putchar(chr ) printf("format ",arg 1,..) sprintf(s,"format ",arg 1,… ) scanf("format ",&name1,… ) sscanf(s,"format ",&name1,…. ) gets(s,max) puts(s)

Page 143 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Problem Solving and C Programming

Codes for Formatted I/O: + Space 0 w p m h c

"%-+ 0w:pmc" left justify print with sign print space if no sign pad with leading zeros min field width precision conversion character: short, l long, L long double conversion character: d,i integer u unsigned c single char s char string f double e,E exponential o octal x,X hexadecimal p pointer n number of chars written g,G same as f or e,E depending on exponent

Standard Utility Functions <stdlib.h> Function Type Absolute value of int n Absolute value of long n Quotient and remainder of ints n,d Quotient and remainder of longs n,d Pseudo-random integer [0,RAND_MAX] Set random seed to n Terminate program execution Pass string s to system for execution abs(n) labs(n) div(n,d) returns structure with div_t.quot and div_t.rem ldiv(n,d) returns structure with ldiv_t.quot and ldiv_t.rem rand() srand(n) exit(status) system(s) Functions

Page 144 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Problem Solving and C Programming

Conversions Function Type Convert string s to double Convert string s to integer Convert string s to long Convert prefix of s to double Convert prefix of s (base b) to long Convert prefix of s (base b) to unsigned long Storage Allocation Function Type Allocate storage Change size of object Deal locate space Mathematical Functions <math.h> Arguments and returned values are double Function Type Trig functions Inverse trig functions a Arctan (y/x) Hyperbolic trig functions Exponentials and logs Exponentials and logs (2 power) Division and remainder Powers Rounding Functions sin(x), cos(x), tan(x) sin(x), acos(x), atan(x) atan2(y,x) sinh(x), cosh(x), tanh(x) exp(x), log(x), log10(x) ldexp(x,n), frexp(x,*e) modf(x,*ip), fmod(x,y) pow(x,y), sqrt(x) ceil(x), floor(x), fabs(x) Functions malloc(size), calloc(nobj,size) realloc(pts,size) free(ptr) atof(s) atoi(s) atol(s) strtod(s,endp) strtol(s,endp,b) strtoul(s,endp,b) Functions

Page 145 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Result will always have a decimal point. Note: when using the * with the width and/or precision specifier. E. f. After the % character come the following in this order: [flags] [width] Control the conversion (optional). [.sign. Default is to just show the . Defines the number of characters to print (optional). i. e. space Causes a positive value to display a space for the sign.precision] Defines the amount of precision to print for a number type (optional). Page 146 ©Copyright 2007. f. g. Overrides the space flag. This is useful only with a width specifier. Precision overrides this flag. If a * is used in place of the width specifer. g. For d. If the value is not large enough to fill the width. e. Flags: + Value is left justified (default is right justified). If the value overflows the width of the field. and G leading zeros are used to pad the field width instead of spaces. # Alternate form: Conversion Character Result o X or x E. [modifier] [type] Overrides the size (type) of the argument (optional). All Rights Reserved C3: Protected . the width argument comes first. Cognizant Technology Solutions. The type of conversion to be applied (required). Nonzero value will have 0x or 0X prefixed to it. then the next argument (which must be an int type) specifies the width of the field. then the precision argument. Forces the sign (+ or -) to always be shown. then the field is expanded to fit the value.Problem Solving and C Programming Conversion Specifier for ‘printf’ statement A conversion specifier begins with the % character. then the rest of the field is padded with spaces (unless the 0 flag is specified). or G G or g 0 Precision is increased to make the first digit a zero. Trailing zeros will not be removed. then the value to be converted. x. u. Overrides the 0 flag. o. Width: The width of the field is specified here with a decimal value. X. Negative values still show the sign.

n Specifies that the pointer points to a short int.n Modifier: A modifier changes the way a conversion specifier type is interpreted. Cognizant Technology Solutions.Problem Solving and C Programming Precision: The precision begins with a dot (. or . e. E. . All Rights Reserved C3: Protected . g. For s type all characters in string are print up to but not including the null character. Value is first converted to a long double. 6 for f. G Specifies that the pointer points to a long int. x. u. f. If a * is used. E types no decimal point character or digits are printed.precision] (none) Default precision values: Result 1 for d. i. o. X types the default precision value is used unless the value is zero in which case no characters are printed. d. x. . u. x. The precision can be given as a decimal value or as an asterisk (*). i. Page 147 ©Copyright 2007. o. Specifies the number of digits after the decimal point. e. [. Note: when using the * with the width and/or precision specifier. x. For s type specifies the maximum number of characters to print. [modifier] h h l l L [type] Effect d. For g or G types specifies the number of significant digits to print. For f. For f. For d. u. i. the width argument comes first. i. i. then the precision argument. Precision does not affect the c type. x. For g or G types the precision is assumed to be 1. E types specifies the number of digits after the decimal point. u. o. then the next argument (which is of an int type) specifies the precision. e.0 For d. X types then at least n digits are printed (padding with zeros if necessary).) to distinguish itself from the width specifier. X types. The minimum number of digits to appear. X Value is first converted to a short int or unsigned short i nt. o. X Value is first converted to a long int or unsigned long int . then the value to be converted. u. n e. o. E types. For g or G types all significant digits are shown.

All Rights Reserved C3: Protected .Problem Solving and C Programming Conversion specifier type: The conversion specifier specifies what type the argument is to be treated as.dddeñdd where there is one digit printed before the decimal (zero only if the value is zero). Type unsigned int printed in decimal. The argument must be a pointer to an int. Type double printed as type e or E if the exponent is less than -4 or greater than or equal to the precision. e. c. E. Decimal point character appears only if there is a nonzero decimal digit. D. G c s p n % Conversion specifier for ‘fscanf()’ An input field is specified with a conversion specifier which begins with the % character. No characters are printed. b. [type] The type of conversion to be applied (required). E Type signed int. If type is E then the exponent is printed with a capital E. Type double printed as [-]ddd. Defines the maximum number of characters to read (optional). Prints the value of a pointer (the memory location it holds). Type unsigned int printed in octal.ddd. Single character is printed. Type char. Otherwise printed as type f. [type] d. Output Type unsigned int printed in hexadecimal as dddd using a. String is printed according to precision (no precision prints entire string). Page 148 ©Copyright 2007. i o u x X f e. Cognizant Technology Solutions. Trailing zeros are removed. A % sign is printed. Stores the number of characters printed thus far in the int. f. [modifier] Overrides the size (type) of the argument (optional). Type unsigned int printed in hexadecimal as dddd using A. B. The exponent contains at least two digits. d. Type pointer to array. F. C. g. Type double printed as [-]d. After the % character come the following in this order: [*] [width] Assignment suppressor (optional).

then it is base 8 (octal).e. The characters 0x or 0X may be optionally prefixed to the value. Type unsigned int. Digits 0 through 9 or A through Z or a through z. x The argument is a short int or unsigned short int. u. If the first character is a digit from 1 to 9. Type unsigned int. Conversion specifier type: The conversion specifier specifies what type the argument is. Type signed int. [type] d i Input Type signed int represented in base 10.Problem Solving and C Programming Assignment suppressor: Causes the input field to be scanned but not stored in a variable. f. X e. The input must be in base 8 (octal). then it is base 10. s Type character array. If the first digit is a zero and the second digit is a digit from 1 to 7. Cognizant Technology Solutions. Modifier: A modifier changes the way a conversion specifier type is interpreted. Type float. new line. [modifier] h h l l l L [type] Effect d. The input must be in base 16 (hexadecimal). o u x. f. d. or form feed). then what was read thus far is converted and stored in the variable. u. Begins with an optional sign. i. The argument is a double. The base (radix) is dependent on the first two characters. Then one or more digits. o. It also controls what a valid convertible character is (what kind of characters it can read so it can convert to something compatible). If the first digit is a zero and the second character is an x or X. Finally ended with an optional signed exponent value g. E. it reaches a nonconvertible character). Digits 0 through 9 and the sign (+ or -). carriage return.< /td> n Specifies that the pointer points to a short int. Type unsigned int. n e. i. If the input is smaller than the width specifier (i. g Specifies that the pointer points to a long int. tab. The argument is a long double. The array must be large enough to hold the sequence plus a null character appended to the end. vertical tab. then it is base 16 (hexadecimal). followed by an optional decimal-point and decimal value. x The argument is a long int or unsigned long int . o. g e. All Rights Reserved C3: Protected . Digits 0 through 7 only. The input must be in base 10 (decimal). Width: The maximum width of the field is specified here with a decimal value. Inputs a sequence of non-white space characters (space. Page 149 ©Copyright 2007. f. Digits 0 through 9 only. G designated with an e or E.

Allows input of only those character encapsulated in the brackets (the scan set). No null character is appended to the array. Allows a search set of characters. a dash. then the scan set is inverted and allows any ASCII character except those specified between the brackets. c p n % Page 150 ©Copyright 2007.. and an ending character a range of characters can be included in the scan set.Problem Solving and C Programming [type] [. If the first character is a carrot (^).] Input Type character array. Cognizant Technology Solutions. then 1 is assumed. On some systems a range can be specified with the dash character (-). Inputs a memory address in the same fashion of the %p type produced by the printf function. A null character is appended to the end of the array. Pointer to a pointer. Requires a matching % sign from the input. All Rights Reserved C3: Protected . If no width field is specified. By specifying the beginning character. Type character array.. Stores the number of characters read thus far in the int. Inputs the number of characters specified in the width field. The argument must be a pointer to an int. No characters are read from the input stream.

Cognizant Technology Solutions.com/refcards/c/c-refcard-letter.Dromey.se/c/bwk-tutor.Problem Solving and C Programming References Websites http://refcards.lysator. “How to solve it by Computer”.html http://www. Eastern Economy Edition Al Kelley. Prentice Hall Byron Gottfried.edu/webmonkeys/book/c_guide/ Books Deitel & Deitel.html#introduction http://www. “A Book on C”. “Programming in C”. “C How to Program”. All Rights Reserved C3: Protected . Tata McGraw Hill R.G. Fourth Edition.pdf http://cm. Third Edition.bell-labs. Ira Pohl.com/cm/cs/who/dmr/chist.uiuc.liu. Pearson Education Asia Page 151 ©Copyright 2007.acm.

All Rights Reserved C3: Protected .Problem Solving and C Programming STUDENT NOTES: Page 152 ©Copyright 2007. Cognizant Technology Solutions.

Sign up to vote on this title
UsefulNot useful

Master Your Semester with Scribd & The New York Times

Special offer for students: Only $4.99/month.

Master Your Semester with a Special Offer from Scribd & The New York Times

Cancel anytime.