Problem Solving and C Programming_-_Handout_v2[1].1

September 18, 2017 | Author: Marsha Wong | Category: Computer Program, C (Programming Language), Programming Language, Subroutine, Computer Programming
Share Embed Donate


Short Description

Problem solving and C programming...

Description

Handout: Problem Solving and C Programming Version: PSC/Handout/0307/2.1 Date: 05-03-07

Cognizant 500 Glen Pointe Center West Teaneck, NJ 07666 Ph: 201-801-0233 www.cognizant.com

Problem Solving and C Programming

TABLE OF CONTENTS

Introduction ................................................................................................................................6 About this Document..................................................................................................................6 Target Audience.........................................................................................................................6 Objectives ..................................................................................................................................6 Pre-requisite ..............................................................................................................................6 Session 1: 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 2: 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 Summary .................................................................................................................................39 Test your Understanding..........................................................................................................39 Page 2 ©Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected

Problem Solving and C Programming Session 4: Selection and Control Structures ..........................................................................41 Learning Objectives .................................................................................................................41 Basic Programming Constructs................................................................................................41 Sequence.................................................................................................................................41 Selection Statements ...............................................................................................................42 ‘if’ Statement ............................................................................................................................42 Conditional / Ternary / ?: Operator...........................................................................................44 Switch Statement .....................................................................................................................45 Iteration Statements.................................................................................................................46 ‘for’ statements.........................................................................................................................46 ‘while’ statement ......................................................................................................................47 ‘do - while’ statement ...............................................................................................................48 Break, Continue Statements ....................................................................................................49 Summary .................................................................................................................................50 Test your Understanding..........................................................................................................50 Session 6: Arrays and Strings ..................................................................................................52 Learning Objectives .................................................................................................................52 Need for an Array.....................................................................................................................52 Memory Organization of an Array ............................................................................................52 Declaration and Initialization ....................................................................................................53 Basic Operation on Arrays .......................................................................................................54 Multi-dimensional Array............................................................................................................55 Strings......................................................................................................................................57 String Functions .......................................................................................................................59 Character Functions.................................................................................................................60 Summary .................................................................................................................................60 Test your Understanding..........................................................................................................61 Session 8: Pointers....................................................................................................................62 Learning Objectives .................................................................................................................62 Introduction ..............................................................................................................................62 Declaration and Initialization ....................................................................................................62 Pointer Arithmetic.....................................................................................................................64 Pointers and Arrays .................................................................................................................65 Dynamic Memory Allocation.....................................................................................................71 Summary .................................................................................................................................73 Test your Understanding..........................................................................................................73

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

Problem Solving and C Programming Session 10: Functions...............................................................................................................75 Learning Objectives .................................................................................................................75 Need for Functions...................................................................................................................75 Function Prototype...................................................................................................................76 Function Definition ...................................................................................................................77 Function Call ............................................................................................................................79 Passing Arguments..................................................................................................................80 Functions and Arrays ...............................................................................................................83 Functions and Pointers ............................................................................................................85 Storage Classes.......................................................................................................................87 Command Line Arguments ......................................................................................................90 Summary .................................................................................................................................91 Test your Understanding..........................................................................................................92 Session 12: Structures and Unions..........................................................................................94 Learning Objectives .................................................................................................................94 Introduction ..............................................................................................................................94 Declaration and Initialization ....................................................................................................94 Structures and Arrays ..............................................................................................................98 Structures and Pointers............................................................................................................98 Structures and Functions .......................................................................................................100 Unions....................................................................................................................................101 Union of Structures ................................................................................................................102 Enumeration ..........................................................................................................................103 Typedef Statement.................................................................................................................104 Summary ...............................................................................................................................105 Test your Understanding........................................................................................................105 Session 14: Files and Preprocessors.....................................................................................107 Learning Objectives ...............................................................................................................107 Introduction ............................................................................................................................107 File Operations.......................................................................................................................108 Character I/O .........................................................................................................................110 String I/O................................................................................................................................112 Numeric I/O............................................................................................................................112 Formatted I/O.........................................................................................................................113 Block I/O ................................................................................................................................114 Random File Operations ........................................................................................................116 Preprocessor Directives .........................................................................................................117

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

Problem Solving and C Programming Summary ...............................................................................................................................123 Test your Understanding........................................................................................................123 Syntax Summary......................................................................................................................125 References ...............................................................................................................................138 Websites ................................................................................................................................138 Books.....................................................................................................................................138 STUDENT NOTES ....................................................................................................................139

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

Problem Solving and C Programming

Introduction

About this Document This document provides the following topics: 

Problem solving concepts



An introduction to C programming language



Basic concepts of C programming language

Target Audience In-Campus Trainees

Objectives 

Explain the concepts of problem solving



Explain the concepts of C programming language



Write effective programs using C programming language

Pre-requisite This module does not require any pre-requisites

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

Problem Solving and C Programming

Session 1: Introduction to Problem Solving and Programming Languages

Learning Objectives After completing this chapter, you will be able to: 

Explain the basic concepts of problem solving



List the steps involved in program development



List the advantages of top-down programming



Describe programming languages, their types, and features

Problem Solving Aspect Problem solving is a creative process. It is an act of defining a problem, determining the cause of the problem, identifying, prioritizing, and selecting alternatives for a solution and implementing a solution.

A problem can be solved successfully only after making an effort to understand the problem. To understand the problem, the following questions help: 

What do we know about the problem?



What is the information that we have to process in order the find the solution?



What does the solution look like?



What sort of special cases exist?



How can we recognize that we have found the solution?

It is important to see if there are any similarities between the current problem and other problems that have already been solved. We have to be sure that the past experience does not hinder us in developing new methodology or technique for solving a problem. The important aspect to be considered in problem-solving is the ability to view a problem from a variety of angles.

There is no universal method for solving a given problem. Different strategies appear to be good for different problems. Some of the well known strategies are: 

Divide and Conquer



Greedy Method



Dynamic Programming



Backtracking



Branch and Bound

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

Problem Solving and C Programming

Program Development Steps The various steps involved in Program Development are: 

Defining or Analyzing the problem



Design (Algorithm)



Coding



Documenting the program



Compiling and Running the Program



Testing and Debugging



Maintenance

Analyzing or Defining the Problem The problem is defined by doing a preliminary investigation. Defining a problem helps us to understand the problem clear. It is also known as Program Analysis. Tasks in defining a problem: 

Specifying the input requirements



Specifying the output requirements



Specifying the processing requirements

Specifying the input requirements Determine the inputs required and source of the data. The input specification is obtained by answering the following questions: 

What specific values will be provided as input to the program?



What format will the values be?



For each input item, what is the valid range of values that it may assume?



What restrictions are placed on the use of these values?

Specifying the output requirements Describe in detail the output that will be produced. The output specification is obtained by answering the following questions: 

What values will be produced?



What is the format of these values?



What specific annotation, headings, or titles are required in the report?



What is the amount of output that will be produced?

Specifying the Processing Requirements Determine the processing requirements for converting the input data to output. The processing requirement specification is obtained by answering the following questions: 

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

Problem Solving and C Programming

Example 1.1 Find the factorial of a given number Input: Positive valued integer number Output: Factorial of that number Process: Solution technique which transforms input into output. Factorial of a number can be calculated by the formula n! = 1*2*3*4….*n Design A design is the path from the problem to a solution in code. Program Design is both a product and a process. The process results in a theoretical framework for describing the effects and consequences of a program as they are related to its development and implementation. A well designed program is more likely to be: 

Easier to read and understand later



Less of bugs and errors



Easier to extend to add new features



Easier to program in the first place

Modular Design Once the problem is defined clearly, several design methodologies can be applied. An important approach is Top-Down programming design. It is a structured design technique which breaks up the problem into a set of sub-problems called Modules and creates a hierarchical structure of modules. While applying top-down design to a given problem, consider the following guidelines: 

A problem is divided it into smaller logical sub-problems, called Modules



Each module should be independent and should have a single task to do



Each module can have only one entry point and one exit point, so that the logic flow of the program is easy to follow



When the program is executed, it must be able to move from one module to the next in sequence, until the last module is executed



Each module should be of manageable size, in order to make the design and testing easier

Top-down design has the following advantages: 

Breaking up the problem into parts helps us to clarify what is to be done



At each step of refinement, the new parts become more focussed and, therefore, easier to design



Modules may be reused



Breaking the problem into parts allows more than one person to work on the solution simultaneously

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

Problem Solving and C Programming Algorithm (Developing a Solution technique) An algorithm is a step-by-step description of the solution to a problem. It is defined as an ordered sequence of well-defined and effective operations which, when carried out for a given set of initial conditions, produce output, and terminate in a finite time. The term “ordered sequence” specifies, after the completion of each step in the algorithm, the next step must be unambiguously defined. An algorithm must be: 

Definite



Finite



Precise and Effective



Implementation independent ( only for problem not for programming languages)

Developing Algorithms Algorithm development process is a trial-and-error process. Programmers make initial attempt to the solution and review it, to test its correctness. The errors identified leads to insertions, deletions, or modifications to the existing algorithm. This refining continues until the programmer is satisfied that, the algorithm is essentially correct and ready to be executed. The more experience we gain in developing an algorithm, the closer our first attempt will be to a correct solution and the less revision will be required. However, a novice programmer should not view developing algorithm as a single-step operation. Example 1.2: Algorithm for finding factorial of a given number Step 1: Start Step 2: Initialize factorial to be 1, i to be 1 Step 3: Input a number n Step 4: Check whether the number is 0. If so report factorial is 1 and goto step 9 Step 5: Repeat step 6 through step 7 n times Step 6: Calculate factorial = factorial * i Step 7: Increment i by 1 Step 8: Report the calculated factorial value Step 9: Stop Pseudo Code Pseudo code is an informal high-level description of an algorithm that uses the structural conventions of programming languages, but omits language-specific syntax. It is an outline of a program written in English or the user's natural language. Example 1.3: Pseudo Code for finding factorial of a given number Step 1: START Step 2: DECLARE the variables n, fact, i Step 2: SET variable fact =1 and i =1 Step 3: READ the number n Step 4: IF n = 0 then

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

Problem Solving and C Programming Step 4.1: PRINT factorial = 1 Step 4.2: GOTO Step 9 Step 5: WHILE the condition ip; 4. Size = 19

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

Problem Solving and C Programming

Session 14: Files and Preprocessors

Learning Objectives This session will enable you to: 

Explain the concept of file and its types



Know the basic file operations



Perform formatted, unformatted and block file I/O operations



Access files in both sequential and random order



Make use of pre-processor directives

Introduction When a large volume of data is involved, supplying data through the keyboard during the execution or displaying the output on the screen is not convenient. The input data can be stored on disks and the program may access the data from disks for processing. Similarly, the results may be stored on disks. For such applications, files are needed. A file is a place on the disk where a group of related data is stored. In C, file manipulations may be done in two ways: 

Low-level I/O using system calls



High-level I/O using functions from standard I/O library

The files accessed through the library functions are called Stream Oriented files and the files accessed with system calls are known as System Oriented files.

Streams and Files Streams facilitate a way to create a level of abstraction between the program and an input/output device. This allows a common method of sending and receiving data amongst the various types of devices available. There are two types of streams: text and binary. Text streams are composed of a set of lines. Each line has zero or more characters and is terminated by a new line character. Text streams consist of printable characters, the tab character, and the new-line character. Conversions may occur on text streams during input and output. Spaces cannot appear before a newline character, a text stream removes these spaces even though implementation defines it. A text stream, on some systems, may be able to handle lines of up to 254 characters long (including the terminating new line character). Binary streams are composed of only 0’s and 1’s. It is simply a long series of 0’s and 1’s. More generally, there need not be a one-to-one mapping between characters in the original file and the characters read from or written to a text stream. But in the binary stream there will be one-to-one mapping because no conversion exists, and all characters will be transferred as such.

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

Problem Solving and C Programming When a program begins, 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.



Standard error (stderr) is another output stream typically used by programs to output error messages.

File Operations Files are associated with streams and must be open in order to use it. The point of I/O within a file is determined by the file position. When a file is opened, the file position points to the beginning of the file unless the file is opened for an append operation - in which case the position points to the end of the file. The file position indicates where the next operation (read/write) will occur. When a file is closed, no more actions can be taken on it until it is opened again. Exiting from the main function causes all open files to be closed. In C, ‘FILE’ is a structure that holds the description of a file and is defined in stdio.h.

Basic File operations are: 

Opening a File



Reading from and/or writing into a File



Closing the File

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. fscanf() and fprintf() )



disconnect the file from the task using fclose()

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

Problem Solving and C Programming General form: FILE *fp; fp = fopen(“name”, “mode”); fscanf(fp, "format string", variable list); fprintf(fp, "format string", variable list); fclose(fp ); Where: 

The ‘fp’ is a file pointer or file handler.



The ‘name’ is to represent filename and it is a string of characters. (Extensions can be specified like test.c, details.dat etc)



The ‘mode’ argument in the fopen() specifies, the purpose/positioning of opening the file. It is a string enclosed within double quotes.

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)

r+b or read and write binary mode rb+ w+b or read and write binary mode (truncates file to zero length if it already exists or creates new wb+ file) a+b or read and write binary mode (opens or creates file and sets file pointer to the end-of-file) ab+

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

Problem Solving and C Programming If the file does not exist and it is opened with read mode (r), the file open fails and it will return NULL to file pointer. If the file is opened with append mode (a), regardless of the current file position.

all write operations occur at the end of the file

If the file is opened in the update mode (+), output cannot be directly followed by input and input cannot be directly followed by output without an intervening fseek(), fsetpos(), rewind(), or fflush().

fopen() returns the file pointer position for successful open and returns NULL, if the file does not open or the file does not exist.

fclose() returns zero for successful close and returns EOF (end of file) when error is encountered in closing a file. By default, all the files opened are closed when the program is terminated. It is good to close all the files opened with fopen(), because files can be reopened only if they are closed.

The Standard I/O provides variety of functions to handle files. It supports the following ways of reading from and writing into file: 

Character I/O



String I/O



Formatted I/O



Block I/O



Integer I/O

Character I/O Using character I/O, one character (byte) can be written to or read from a file at a time.

Writing in to a file To write into a file, the file must be opened in ‘w’ mode The function putc() is used to write a byte to a file. General Form: putc(ch,fptr); This function writes the character ch into a file pointed by the file pointer fptr. This fptr may be stdout, which represents standard output device, monitor as a file. On success, the character is returned. If an error occurs, the error indicator for the stream is set and EOF is returned.

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

Problem Solving and C Programming Example 14.1: Program to create a text file (character file) main() { FILE *fp; char c; if ((fp=fopen(“sample.dat”,”w”)) !=NULL) { while ((c=getchar()) != EOF) putc(c,fp); fclose(fp); } else printf(“Error in opening a file”); }

Reading from a file The function getc() is used to read a byte from a file. This may be a macro version of fgetc. General Form: ch =getc (fptr); This function reads a character from the file and it is returned to the program defined character variable. After the reading a character, the pointer is moved to the next position. The fptr may be stdin, which represents a standard input device, keyboard as a file. On success, the character is returned. If the end-of-file is encountered, EOF is returned and the end-of-file indicator is set. If an error occurs, the error indicator for the stream is set and EOF is returned. The EOF is end of file status flag, which is true if end of file is reached, otherwise false.

Example 14.2: Program to read a character data from a text file main() { FILE *fp; char c; if ((fp=fopen(“sample.dat”,”r”)) !=NULL) { while ((c=getc(fp)) != EOF) putchar(c); fclose(fp); } else printf(“Error in opening a file”); }

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

Problem Solving and C Programming String I/O Using string I/O, string can be written to, or read from, a file at a time.

Writing a string in to a file The function used is fputs(). Writes a string to the specified stream till the last character is read but does not include the null character. On success, a nonnegative value is returned. On error, EOF is returned.

General Form: fputs (str, fptr);

Reading a string from a file The function used is fgets(). Reads a line from the specified stream and stores it into the string pointed to by str. It stops when (n-1) characters are read, the newline character is read, or the endof-file is reached, whichever comes first. The newline character is copied to the string. A null character is appended to the end of the string. On success, a pointer to the string is returned. On error, a null pointer is returned. If the end-of-file occurs before any characters have been read, the string remains unchanged.

General Form: fgets(str,n,fptr);

Numeric I/O Using numeric I/O, integers can be written to, or read from, a file at a time. Writing integer in to a file The function used is putw(). This function writes an integer to a file. On success, a nonnegative value is returned. On error, EOF is returned. General Form: putw (i, fptr);

Reading integer from a file The function used is getw(). Reads an integer from the file and assigns it to the program defined numeric variable at the LHS. General Form: i = getw( fptr);

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

Problem Solving and C Programming

Formatted I/O The formatted I/O functions can handle a group of data in a single call.

Writing formatted data to a file The function fprintf() is used. This function will write the values stored in the variables into a file pointed by fptr, according to the format specifier specified in format string. On success, the number of characters printed is returned. If an error occurred, -1 is returned. General Form: fprintf ( fptr, format-string, variable-list); The fprintf() function takes the format string specified by the format argument and applies each following argument to the format specifiers in the string, in a left to right fashion. Each character in the format string is copied to the stream except for conversion characters which specify a format specifier.

Reading formatted data from the file The function used is fscanf().This function will read the formatted data from the file pointed by fptr, as specified by the format specifiers in format-string and stores in the variables, whose addresses are given in addresses-list. Reading an input field (designated with a conversion specifier) ends when an incompatible character is met, or the width field is satisfied. On success, the number of input fields converted and stored is returned. If an input failure occurs, EOF is returned. General Form: fscanf( fptr, format-string, addresses-list);

The fscanf() function takes input in a manner that is specified by the format argument and stores each input field into the corresponding arguments, in a left to right fashion.

Each input field is specified in the format string with a conversion specifier which specifies how the input is to be stored in the appropriate variable. Other characters in the format string specify characters that must be matched from the input, but are not stored in any of the following arguments. If the input does not match, the function stops scanning and returns. A white space character may match with any white space character such as space, tab, carriage return, new line, vertical tab, or form feed, or the next incompatible character.

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

Problem Solving and C Programming Example 14.3: Program using fscanf() and fprintf() main() { FILE *fpt; struct { int no; char name[10]; int age; }std[10], std1[10]; int i; clrscr(); fpt = fopen("details.dat" , "w"); printf("\n\n enter the details (no , name , age )\n\n"); for(i=0; i
View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF