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

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

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

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. All Rights Reserved C3: Protected . Cognizant Technology Solutions.

We have to be sure that the past experience does not hinder us in developing new methodology or technique for solving a problem. 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. determining the cause of the problem. Some of the well known strategies are: Divide and Conquer Greedy Method Dynamic Programming Backtracking Branch and Bound Page 7 ©Copyright 2007. It is an act of defining a problem. All Rights Reserved C3: Protected . Different strategies appear to be good for different problems. prioritizing. identifying.Problem Solving and C Programming Session 2: Introduction to Problem Solving and Programming Languages Learning Objectives After completing this session. There is no universal method for solving a given problem. and selecting alternatives for a solution and implementing a solution. 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. A problem can be solved successfully only after making an effort to understand the problem. The important aspect to be considered in problem-solving is the ability to view a problem from a variety of angles. Cognizant Technology Solutions.

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. 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. 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. It is also known as Program Analysis. 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. All Rights Reserved C3: Protected . 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. Cognizant Technology Solutions.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. headings. Defining a problem helps us to understand the problem clear. 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.

Problem Solving and C Programming Example 2.1 Find the factorial of a given number Input: Positive valued integer number Output: Factorial of that number Process: Solution technique which transforms input into output. until the last module is executed Each module should be of manageable size. therefore. An important approach is Top-Down programming design. All Rights Reserved C3: Protected . so that the logic flow of the program is easy to follow When the program is executed. 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. 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. several design methodologies can be applied. it must be able to move from one module to the next in sequence. Factorial of a number can be calculated by the formula n! = 1*2*3*4…. Program Design is both a product and a process. the new parts become more focussed and. 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.*n Design A design is the path from the problem to a solution in code. 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. consider the following guidelines: A problem is divided it into smaller logical sub-problems. called Modules Each module should be independent and should have a single task to do Each module can have only one entry point and one exit point. While applying top-down design to a given problem. 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. Cognizant Technology Solutions.

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

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

fact. All Rights Reserved C3: Protected .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. i Initialize fact =1. Cognizant Technology Solutions.4: Flow Chart for finding factorial of a given number START Declare the variables n.Problem Solving and C Programming Represents control flow Example 2.

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

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

it recognizes the code and converts it in to electrical signals. machine language is not an easy language to learn. Cognizant Technology Solutions. Because of it design. All Rights Reserved C3: Protected . a program instruction may look like this: 1011000111101 Machine language is considered to be the first generation language. Low level languages are machine oriented and require extensive knowledge of computer hardware architecture and its configuration.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. Advantage The program runs faster because no translation is needed. It does not need any translator program. It is also difficult to debug the program written in this language. 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. 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. The instructions are called machine instruction (machine code) and it is written as strings of 1's (one) and 0’s (zero). there are many new languages. Thus. (It is already in machine understandable form) Disadvantages It is very difficult to write programs in machine language. When this sequence of codes is fed in to the computer. (a) Machine Language Machine Language is the only language that is directly understood by the computer.

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

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

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

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

Problem Solving and C Programming 5. c (it can run on any machine) Page 20 ©Copyright 2007. It can run on any machine d. True 5. True. All Rights Reserved C3: Protected . What is meant by portability of programs? a. Testing is to find errors in programs and debugging is to correct their root causes 4. Transportability of resulting program within machine folders c. The program needs to be compiled in every machine Answers: 3. Easy to carry from place to place b. Cognizant Technology Solutions.

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

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

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

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

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

Some implementation of C recognizes only the first eight characters and some other recognize first 32 characters. 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. the range of values that can be represented in memory. All keywords must be written in lowercase. All Rights Reserved C3: Protected . and functions. Keywords serve as basic building blocks for program statements. No special character is allowed except underscore (_). constants. the number of bytes to be reserved in memory. predefined meanings in C. An Identifier can be of arbitrarily long.Problem Solving and C Programming Keywords Keywords have standard.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. Cognizant Technology Solutions. The following table shows the list of keywords. ANSI C supports two classes of data types: Primary / Fundamental / Basic / Primitive data types Derived / Compound data types Page 26 ©Copyright 2007. and the type of operation that can be performed on a particular data item. It should start with an alphabet. Example 3. followed by the combinations of alphabets and digits.

535 Page 27 ©Copyright 2007. Similarly. a long int may require the same amount of memory as an int or it may require more memory. short int may require less space than an int or it may require the same amount of memory.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. Cognizant Technology Solutions. Here. 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. The basic data types can be augmented by the use of data type qualifiers. short int may be 1 byte or 2 bytes int = 2 bytes. For example. 8 bits Represents positive integer numbers -128 to 127 16 bits 0 to 65. never less than int. They are. All Rights Reserved C3: Protected . 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. Type Qualifiers Data type qualifiers add additional information to the data types. int = 2 bytes.

Variable names must be chosen in such a way that it should be a valid identifier satisfying all the basic conditions.647 Floating Point Number.4 * (10-38) to 3.7 * (10-308) to 1. All Rights Reserved C3: Protected . Cognizant Technology Solutions. They are used to represent a collection of data.4 * (10-4932) to 1.147.295 Represents both positive and negative long integer 32 bits -2.4 * (10+38) 1.483.768 to 32.483. Variable names are case sensitive (ex: variable EMPNAME is different from variable empname).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. The variable name can be chosen by the programmer in a meaningful way so as to reflect its function or nature in the program.648 to 2.767 represents positive long integer 32 bits 0 to 4.1 * (104932) Increases the size of double.7 * (10+308) 3.294. 80 bits Defines an empty data type which can then be associated with some data types. Page 28 ©Copyright 2007. It is useful with pointers. Derived Data Types Derived data types are a combination of primitive data types. They are: Arrays Structures Unions Enumerated Pointers Variables A variable is an identifier that represents a value.967. The value represented by the identifier may be changed during the execution of the program. A more accurate floatingpoint number than float 32 bits 64 bits 3.147.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Cognizant Technology Solutions. 1000 1002 1004 1006 1008 Individual memory location is referred by index. set of numbers. 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. Array is a derived data type which is used to store similar data items in contiguous memory locations under a single name. If an array of 5 integers elements is created. index 1 refers second location. Page 53 ©Copyright 2007. totally 10 contiguous bytes will be allocated in memory. All Rights Reserved C3: Protected . set of names). Note: size of an integer is assumed to be 2 bytes Starting address is assumed as 1000 and totally 10 bytes are created.g. It holds a fixed number of equally sized data elements.Problem Solving and C Programming Session 7: Arrays and Strings Learning Objectives After completing this session. etc. The individual elements are accessed by specifying the subscript. of the same data type.]. Address of an array element is calculated as below: Address of ith location = base address + (size of the individual data element * index i ) Address of 0th element = 1000 + (2 * 0) = 1000 Address of 1st element = 1000 + (2 * 1) = 1002 … In C. the name of the array refers to the base address of the array.. [index 0 refers first location . Memory Organization of an Array The elements in an array are always stored in consecutive memory locations.

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

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

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

3}}. Assume that array starts at location 1000. Cognizant Technology Solutions.{1.Problem Solving and C Programming Example 7.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.5. In partial initialization.2.row 0 & column 0 .6}. = 4 elements). (2*2 Elements are stored in row major order. If m elements are needed. /*num[0][2] = 0 num[1][1]=num[1][2]=0*/ Example 7. the uninitialized array elements are initialized to Zero.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. All Rights Reserved C3: Protected . out of n locations defined. int num[2][3] = {1.8 int num[2][3] = {1. Example 7.3. n-m locations are unnecessarily wasted No automatic array bounds checking during compilation Page 57 ©Copyright 2007.4.2}.4.{4}}.row 1 & column 0 . /*num[1][2] = 0*/ int num[2][3] = {{1.3. It is necessary to specify the size of the column in declaration. Elements of 1st row are stored first and then the elements of next row. 7 int a[2][2].2.2.3}. creates 8 bytes of contiguous memory locations.5}. Memory is allocated in the beginning of the execution. /*row elements are initialized separately*/ int num[2][3] = {{1.row 0 & column 1 . a[0][0] will be in location 1000 .2.

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

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

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.h: String Functions strcpy(string1. s2) strcspn(s1. string2) strcat(string1. s2) strspn(s1. s2) Page 60 ©Copyright 2007. c) strstr(s1. Functionality strlen (string) strrev (string) strncat(string1. string2) strcmp(string1. c) strrchr (string. n) strncmp(string1. 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.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.string2. All Rights Reserved C3: Protected . Append n characters from string2 to string1 Compare first n characters of two strings. n) strncpy(string1.Problem Solving and C Programming The following is the list of string functions available in string. string2.s2) strpbrk(s1. Returns the number of characters at the beginning of s1 that do not match s2. n) strupr (string) strlwr (string) atoi (string) atof (string) atol (string) strchr (string. string2. Find last occurrence of character c in string. Cognizant Technology Solutions. Locates the first occurrence of s2 in s1.

All Rights Reserved C3: Protected .\r. for (i = 0. for(i = 2. fib[0] = 0. True if c is a control character (\n.) True if c is a space character (\n.’ ‘) 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. Cognizant Technology Solutions. fib[1] = 1.\a) True if c is a decimal digit True if c is a graphical character (all characters. i++) fib[i] = fib[i-1] + fib[i-2]. int i. i < 24.h> main() { int fib[24]. Problem Statement: Write a program to develop Fibonacci series using arrays Code: #include <stdio.\t.‘. i < 24. i++) Page 61 ©Copyright 2007. “.h. True if c is ASCII .\v. 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 (. 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. . ‘.\f. is used for the character functions. True if c is a letter.:. The header file.Problem Solving and C Programming Character Functions C provides the following collection of character functions.\f.\r. which can manipulate a single character. ctype. .

Problem Solving and C Programming printf("%3d %6d\n". } Refer File Name: <sesh7_2. i++) for(j=0.c> to obtain soft copy of the program code How It Works: The Fibonacci series is 1. j++) printf("%d ". This program implemented fibonacci series by using for loop and array. fib[i]). 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. int i. 2. twod[i][j]). j++) twod[i][j] = i*j. for(i=0.h> main() { int twod[4][5].. printf("\n"). Page 62 ©Copyright 2007. getchar().3. i++) { for (j=0. j<5.5.8. for (i=0. Initially array of size 24 is declared.c> to obtain soft copy of the program code How It Works: This program explains the how to use the two dimensional array.2.13….The program computes the series up to 24 numbers. as we know the first two numbers initialize the first two elements in the array. } Refer File Name: <sesh7_1. i<4.j. All Rights Reserved C3: Protected . Cognizant Technology Solutions. i<4. j<5. Again use the for loop to print the series one by one from the array. i. } getchar(). Problem Statement: Write a program to demonstrate two dimensional arrays Code: #include <stdio.

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

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

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

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

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

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

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

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

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

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

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

If it is defined outside of all the blocks. General Form: storage-class-specifier type-specifier variable-names. Cognizant Technology Solutions. it has file scope. 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.Problem Solving and C Programming Session 10: Functions/Structures and Unions Learning Objectives After completing this session. This is called block scope. The storage-class-specifier can be any one of the following: auto static register extern Page 79 ©Copyright 2007. If a variable is defined in a block (encapsulated with {and}). This means. All Rights Reserved C3: Protected . it may be accessed anywhere in the current source code file.. All other types of variables are local variables.. its scope begins when the variable is defined and ends when it hits the terminating. Data type refers to the type of information represented by a variable and storage classes define its life time and scope.. Scope The scope of the variable (where it can be used). is determined by where it is defined. Life Time Life time refers to the permanence of a variable – How long the variable will retain its value in memory. This is normally called a global variable and is normally defined at the top of the source code.

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

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

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

for( i = 0. salary (float). } When the following command is given in the command prompt. Structure Structure is a derived data type used to represent heterogeneous data items. Cognizant Technology Solutions. char* argv[]) { int i. Example 10. 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.argc). Structures and unions provide a way to group together logically related data items. For example.Problem Solving and C Programming main ( int argc. 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. which are command line strings. Page 83 ©Copyright 2007. All Rights Reserved C3: Protected . argv[i]).i . department code (string). A structure is an aggregation of components that can be treated as a single variable. i++) printf(“\nArgument number %d = %s”.4 main( int argc. The components are called Members. i < argc. printf(“\n Total Number of Arguments = %d”. 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. an employee is represented with the following attributes: employee code (string / integer). employee name (string).

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

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

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

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

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

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

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

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

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

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

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

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

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

It is a string enclosed within double quotes. details. fclose(fp ).Problem Solving and C Programming The logic is. 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. 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. fscanf() and fprintf() ) disconnect the file from the task using fclose() General form: FILE *fp.dat etc) The ‘mode’ argument in the fopen() specifies. "format string". "format string". fp = fopen(“name”. fprintf(fp. variable list). “mode”). fscanf(fp. All Rights Reserved C3: Protected . The ‘name’ is to represent filename and it is a string of characters. Cognizant Technology Solutions. Where: The ‘fp’ is a file pointer or file handler. variable list). (Extensions can be specified like test.c. the purpose/positioning of opening the file.

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

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

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

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

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

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

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

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

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

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

The argument from_where can be: SEEK_SET Seeks from the beginning of the file. On success. All Rights Reserved C3: Protected . 0 1 SEEK_CUR Seeks from the current position.Problem Solving and C Programming Session 15: Files and Preprocessor directives / Pointers Learning Objectives After completing this session. it may be necessary to access some part of the file directly. which corresponds to the current file pointer position. General Form: n = ftell(fptr). Page 108 ©Copyright 2007. ftell() and rewind(). General Form: fseek( fptr. In some applications. This can be achieved by using the functions fseek(). then the value is the number of bytes from the beginning of the file. the value -1L is returned and error number (errno) is set. If it is a text stream. On error. offset. then the value is a value usable by the fseek() function to return the file position to the current position. the current file position is returned. Cognizant Technology Solutions. from_where) The argument offset signifies the number of bytes to seek from the given ‘from_where’ position. ftell() This function takes a file pointer and returns a long int. If it is a binary stream. fseek() This function sets the file position to the given offset (specified in long integer format). 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.

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

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

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

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

and #ifndef directive. zero or one #else directive. 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. /* areaofsquare=sqarea(3). #ifdef. General Form: #if constant_expression #else #endif OR #if constant_expression #elif constant_expression #endif Page 113 ©Copyright 2007.Problem Solving and C Programming Arguments in the macro definition are enclosed with parenthesis to avoid miscalculation.. */ (1) */ areaofsquare=(3+4)*(3+4). All Rights Reserved C3: Protected . /* areaofsquare=sqa(3+4). main() { areaofsquare=sqarea(a). There is no need for semicolon after the macro definition.5 #define sqarea(a) #define sqa(b) b*b #define add(a. 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. there are zero or more #elif directives. All the matching directives are considered to be at the same nesting level. areaofsquare=3+4*3+4. /* areaofsquare=sqarea(3+4). } (1) (2) miscalculation because of no parentheses two semicolons in macro expansion. */ (2) */ ((a)*(a)) Conditional Compilation Directives: A preprocessor conditional compilation directive causes the preprocessor to conditionally suppress the compilation of portions of source code.b) ((a)+(b)). For each #if. Cognizant Technology Solutions. */ areaofsquare = (3) *(3). addition=(2)+(3). Continuation character for macro definition is \. /* /* areaofsquare = (a) * (a). and one matching #endif directive. addition=add(2.3).

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

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

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

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

4.Problem Solving and C Programming General Form: pointer_variable = &array_name [starting index]. *ptr . (ptr+i)).17 int a[2][2] = {1. printf (“%d “. Example 15.2. Page 118 ©Copyright 2007.5} ptr = a .*(a+i)).*(ptr+i)).16 printf (“%u “. General Form: ptr_vble = &array_name [starting index1]…[starting indexn]. displays address of a(i) displays the a[i] value displays the a[0] value displays the a[i] value .3.15 printf (“%d “.14 int a[5] = {1. ptr = &a[0][0] .2. a pointer variable can point to an array of any dimension. All Rights Reserved C3: Protected . OR ptr_vble = array_name. Cognizant Technology Solutions.3. The way in which the pointer variable used.*ptr).4} . OR pointer_variable = array_name. 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]. Example 15. varies according to the dimension. printf (“%d “. Accessing address Example 15. &a[0] = 1000 &a[1] = 1002 &a[2] = 1004 &a[3] = 1006 &a[4] = 1008 Accessing value Example 15. i . 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 .

int a[2][3]={1. jth column Accessing value Example 15.*(*(ptr + i) +j). The following representations are used when a pointer is pointing to a 2D array: ptr+i *(ptr+i) is a pointer to ith row. printf (“%d “. All Rights Reserved C3: Protected .actually a pointer to the first element in i th row.*(a[ i ] + j). for (i=0. For example. 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. printf (“%d “.j) value displays the x(i. (*(ptr + i) +j) is a pointer to jth element in ith row *(*(ptr+i) + j)) refers to the content available in ith row.3.j) value displays the x(i.4.j) value Example 15. Note: First dimension need not be specified but the second dimension has to be specified. refers to the entire row .18 printf (“%d “.Problem Solving and C Programming If the pointer to the array is accessed with 2 subscripts.*(*(pa+i)+j)). Here. (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. So. Page 119 ©Copyright 2007. it results in a problem. j. each with 2 elements.19 main() { int i. is a collection of one dimensional array.j++) printf(“\t%d”. 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. Cognizant Technology Solutions.5. int *pa=&a[0][0].j<3. displays the x(i.*(a + i)[ j ].i++) { for (j=0.6}.i<2.2. a single pointer is used and it needs to know how many columns are there in a row. for example. Therefore. 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.

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

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

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

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

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

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

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

/* pointer p is passed to a function – call by reference */ /* prints 10 */ printf(“ %d “ . int *assign() . All Rights Reserved C3: Protected . Functions and Pointers Pointers can be passed to a function as arguments and a function can also return a pointer to the calling program. p =&a. p = assign() . } /* will print 20 */ /* function prototype . /* function prototype */ void change(int *).Problem Solving and C Programming Session 17: Pointers Learning Objectives After completing this session. Example 17. *p) . 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. a). } void change(int *q) { *q = 10. Cognizant Technology Solutions. printf(‘’ %d ‘’ .function returning an integer pointer */ int *assign() Page 127 ©Copyright 2007.2: Function returning pointer main() { int *p . *p.1: Passing pointers as argument main() { int a =5 . change(p). } /* q is a pointer which will point to the memory location pointed by p */ Example 17.

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

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

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

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

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

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

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

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

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

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

} /* */ main(int argc.: : : ) type name main() { declarations statements } type fnc(arg1. #else.Problem Solving and C Programming Syntax Summary Program Structure/Functions type fnc(type1. 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. #define max(A.B) ((A)>(B) ? (A) : (B)) undefine quoted string in replace concatenate args and rescan conditional execution is name defined. All Rights Reserved C3: Protected . char *argv[]) exit(arg) C Preprocessor #include <filename> #include "filename" #define #define name(var) #undef name # ## #if. Cognizant Technology Solutions.: : : ) { declarations statements return value. #endif #ifdef. #elif. #ifndef name defined? line continuation char include library file include user file name text replacement text text replacement macro Example.

‘\xhh’ \n. All Rights Reserved C3: Protected . \. \b \\. backspace special characters string constant (ends with \0) L or l F or f e 0 0x or 0X ‘a’. Cognizant Technology Solutions. hex) newline. \?.: : : } char name[]="string" char int float double short long signed unsigned *int. \r. \" "abc: : : de" type name=value type name[]={value1. 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. ‘\ooo’.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. tab. octal. \t. cr. *float enum const extern register static void struct typedef typename sizeof object sizeof(type name) Page 139 ©Copyright 2007.

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

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

newline.n) strcat(s.ct.Problem Solving and C Programming Character Class Tests <ctype.ct) strncmp(cs. Cognizant Technology Solutions. digit Checks whether c is a Space.n) memcmp(cs. form feed.ct. t are strings and cs.n) memset(s. All Rights Reserved C3: Protected . letter.ct.n) memchr(cs.n) strchr(cs.ct.c. ct are constant strings Functions strlen(s) strcpy(s.h> Consider s.n) memmove(s. 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. tab.ct) strncat(s.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.ct.n) strcmp(cs.ct) strncpy(s.c.c) strrchr(cs.c) memcpy(s. cr.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.

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

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

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

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

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

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

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

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

Sign up to vote on this title
UsefulNot useful