Problem solving & programming in c, Study notes of Advanced Computer Programming

Problem Solving & Programming in C

Typology: Study notes

2015/2016

Uploaded on 11/03/2016

hamed_karimi
hamed_karimi 🇮🇳

4.5

(4)

5 documents

1 / 297

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
PROBLEM SOLVING AND
PROGRAMMING IN C
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Partial preview of the text

Download Problem solving & programming in c and more Study notes Advanced Computer Programming in PDF only on Docsity!

PROBLEM SOLVING AND

PROGRAMMING IN C

CONTENTS

Page No. UNIT -I

Lesson 1 An Overview of C 7 Lesson 2 Programme Control Structures and Formatted Input/Output 39 Lesson 3 Arrays and Strings 64 Lesson 4 Function 82 Lesson 5 Structures and Unions 98

UNIT -II

Lesson 6 Pointers 125 Lesson 7 Pointers and Structures 139 Lesson 8 File Handling 148

UNIT -III

Lesson 9 Algorithm 163 Lesson 10 Sparse Matrices 169 Lesson 11 Stack 173 Lesson 12 Queue 179

UNIT-IV

Lesson 13 Singly Linked List 189 Lesson 14 Sparse Matrices 220 Lesson 15 Doubly Linked List 224 Lesson 16 Binary Tree 234 Lesson 17 Graphs 250

UNIT-V

Lesson 18 Sorting-Part-I 267 Lesson 19 Sorting-Part-II 280 Lesson 20 External Sorting 293

UNIT-I

Problem Solving & Programming in C 1.6^ Operations and Expressions 1.6.1 Arithmetic Operators 1.6.2 Unary Operators 1.6.3 Type Conversion 1.6.4 Relational and Logical Operators 1.6.5 Assignment Operator 1.6.6 Compound Assignment Operators 1.6.7 Ternary or Conditional Operator 1.6.8 Operator Precedence 1.7 Storage Classes 1.7.1 Automatic Variables 1.7.2 Register Variables 1.7.3 External Variables 1.7.4 Static Variables 1.8 Let us Sum Up 1.9 Lesson end Activities 1.10 Keywords 1.11 Questions for Discussion 1.12 Suggested Readings

1.0 AIMS AND OBJECTIVES

At the conclusion of this lesson you should be able to understand:  An overview and history of C Language  Characteristics of C Language  How to write C Programme  The C Character Set, Keywords and Identifiers  How to add Comments In C  Programme Formatting Style  Different Data Types and its Sizes used in C  Declaration of Variable and Assigning values to it  Variable Naming Conventions  Scope of a variable – Local, Global, Automatic etc.  Different types of Constants  Different types of Operators and Expressions  Operator Precedence  Different types of Storage Classes like Automatic, Register, External and Static

1.1 INTRODUCTION An Overview of C

C is a general-purpose, structured programming language. Structured Languages have a characteristic programme structure and associated set of static scope rules. C was originated in Bell Telephone Laboratories presently known as AT & T Bell Laboratories by Dennis Ritchie in 1970. The Kernighan and Ritchie description is commonly referred to as “K&R C”. Following the publication of the K & R description, computer professionals, impressed with C’s many desirable features, began to promote the use of the language. Since 1980’s, the popularity of C has become widespread. The American National Standards Institute (ANSI) proposed a standardised definition of the C language (ANSI committee X3J11). Most commercial C compilers and interpreters are expected to adopt the ANSI standard. C has the feature of high level programming language as well as the low-level programming. It works as a bridging gap between machine language and the more conventional high-level languages. This feature of C Language made it most popular for system programming as well as application programming.

1.2 AN OVERVIEW OF C

In a structured language, each programme or subprogramme is organized as a set of nested blocks. A Block introduces a new local referencing environment. It consists of a set of declarations for names and statements. In C the block structure exists only within a single subprogramme. It is possible to develop concise source programs in C mainly due to the large number of operators available in the language. Although C has a relatively small instruction set, it is possible to include extensive library functions that enhance the basic instructions. Furthermore, one can write additional library functions of his/her own and can enhance the features and capabilities of the language. C compilers are available for all types of computers whether it is PCs, workstations or super computers. The compilers are highly optimized, and generate object programs that are small and efficient. Apart from these C programs are highly portable compared to the programs written in different other high-level languages. This is because machine dependent features are often handled by the library functions. And that is why every version of C is accompanied by its own set of library functions, which are written for the particular characteristics of the host computer. These library functions are relatively standardized with a common access protocol for these functions. Therefore, most C programs can be processed on different machines with little or no alteration.

1.2.1 Characteristics of C

We briefly list some of C’s characteristics that define the language and also have lead to its popularity as a programming language. Naturally we will be studying many of these aspects throughout the course.  Small size  Extensive use of function calls  Loose typing  Structured language  Low level (BitWise) programming readily available  Pointer implementation - extensive use of pointers for memory, array, structures and functions.

Arguments are referred as parameters. The parameters are symbols that represent An Overview of C information being passed between the function and other parts of the programme. Each compound statement is enclosed within a pair of braces, i.e., { }. The braces may contain combinations of elementary expression statements and other compound statements. Compound statements may be nested, one within another. Each expression statement must end with a semicolon (;). Comments may appear anywhere within a programme , as long as they are placed within the delimiters /* and / (e.g., / this is a comment */). Comments are useful for identifying the principal features of the programme and explaining the underlying logic. The “;” denotes the end of a statement. Blocks of statements are put in braces {...}, as in the definition of functions. All C statements are defined in free format, i.e., with no specified layout or column assignment. Whitespace (tabs or spaces) is never significant, except inside quotes as part of a character string. This example will help us to understand the structure of a C Programme. Example: #include <stdio.h> main() { printf(“This is a C program \n”); } Every C programme contains a function called main. This is the start point of the programme. The first statement “#include < stdio.h>” includes a specification of the C I/O library. All variables in C must be explicitly defined before use: the “.h” files are by convention “header files” which contain definitions of variables and functions necessary for the functioning of a program, whether it be in a user-written section of code, or as part of the standard C libraries. The directive “#include” tells the C compiler to insert the contents of the specified file at that point in the code. The “< ...>” notation instructs the compiler to look for the file in certain “standard” system directories. You will find it at the beginning of almost every C programme. Main() declares the start of the function, while the two curly brackets show the start and finish of the function. Curly brackets in C are used to group statements together as in a function, or in the body of a loop. Such a grouping is known as a compound statement or a block. printf(“This is a C programme \n”); It prints the words on the screen. The text to be printed is enclosed in double quotes. The \n at the end of the text tells the programme to print a newline as part of the output. Most C programs are in lower case letters. You will usually find upper case letters used in preprocessor definitions (which will be discussed later) or inside quotes as parts of character strings. C is case sensitive, that is, it recognises a lower case letter and it’s upper case equivalent as being different. Now we will start talking about basic elements which are used to create a C programme. These elements are as follows:

  1. Valid character set
  2. Identifiers
  3. Keywords
  4. Basic data types and their representation
  5. Constants and variables

Problem Solving &

Programming in C 1.2.3 The C Character Set

The C programming language uses the English alphabets A to Z, a to z, 0 to 9, and certain special characters as building blocks to form basic programme elements like constants, variables, operators and expressions. The special characters are as follows:

! * + \ “ <
^ - [ : ,?

& - ] ‘. (blank)

Fig. 1.1: C character set Most versions of C language also allow some other characters, such as @ and $, to be included within strings and comments. Other than these, certain combinations of these characters, e.g., ‘\b’, ‘\n’ and ‘\t’, are used to represent special meaning such as backspace, new line and horizontal tab, respectively. These are known as escape sequences.

1.2.4 Identifiers

Identifiers are the names used to identify different items in the programme, such as variables, functions and arrays. It can consist of letters and digits, in any order, except that the first one. The first character must be a letter and not a digit. Both the letter casing are permitted. The C language is very case sensitive. An uppercase letter is not equivalent to the corresponding lowercase letter. The underscore character (_) can also be included, and it is considered to be a letter. Keywords like if, else, int, float, etc., are reserved and they cannot be used as identifier names. Example: The following names are valid identifiers. a b15 temparature emp_name triangle area Perimeter TABLE The following names are not valid identifiers for the reasons stated.

10th the first character must be a letter “Kolkata” illegal characters (“) Subject-code illegal character (-) Blue Colour illegal character (blank space)

Although an identifier can be of any length but most implementations recognize maximum 31 characters. There are few implementations, which recognize only eight characters. In case of ANSI standard 31 characters is the limit.

Problem Solving & Programming in C Note carefully that if anything were included in the blank spaces to the left of the threecontinuation lines of the comment, it would be part of the comment and would not be compiled. The last comment is located following the completion of the programme, illustrating that comments can go nearly anywhere in a C programme. Comments are very important in any programming language because you will soon forget what you did and why you did it. It will be much easier to modify or fix a well commented programme a year from now than one with few or no comments. You will very quickly develop your own personal style of commenting. Some compilers allow you to “nest” comments which can be very handy if you need to “comment out” a section of code during debugging. Check your compiler documentation for the availability of this feature with your particular compiler.

1.2.7 Good Formatting Style

main() /* Main programme starts here / { printf(“Good form “); printf (“can aid in “); printf (“understanding a programme .\n”); printf(“And bad form “); printf (“can make a programme “); printf (“unreadable.\n”); } It is an example of a well formatted programme. Even though it is very short and therefore does very little, it is very easy to see at a glance what it does. With the experience you have already gained, you should be able to very quickly grasp the meaning of the programme in its entirety. Your C compiler ignores all extra spaces and all carriage returns giving you considerable freedom concerning how you format your programme. Indenting and adding spaces is entirely upto you and is a matter of personal taste. In contrast to the above mentioned programme look at the following programme. main( ) / Main programme starts here */{printf(“Good form “);printf (“can aid in “);printf(“ understanding a programme .\n”) ;printf(“And bad form “);printf(“can make a programme “); printf(“unreadable.\n”);} How long will it take you to figure out what this programme will do? It doesn’t matter to the compiler which format style you use, but it will matter to you when you try to debug your programme. If you compile this programme and run it, you may be surprised to find that it is the same programme as the last one, except for the formatting. Don’t get too worried about formatting style yet. You will have plenty of time to develop a style of your own as you learn the language. Be observant of styles as you see C programs in magazines, books, and other publications. Example: We can write the same programme in different format. The following three programmes prints the same message “Hello World” on the screen but they are written in three different ways.

  1. #include < stdio.h> main(){printf(“\nHello World\n”);}
  1. #include < stdio.h> An Overview of C main() { printf(“\nHello World\n”); }
  2. #include < stdio.h> main() { printf(“\n”); printf(“Hello World”); printf(“\n”); }

1.3 DATA TYPES AND SIZES

There are only four basic data types in C. They are as follows: Basic data types:

Fig. 1.3: Details of fundamental data types These basic data types can be increased in number by using the data type qualifiers like short, long, signed and unsigned. For example, an integer data can be defined as long, short, signed or unsigned integer. The memory requirement for an integer data varies from compilers to compiler. The qualified basic data types and their sizes are as follows.

Fig. 1.4: Details of qualified data types The qualifier unsigned can be used along with the qualifiers short and long. The unsigned int occupies the same memory space as an ordinary int but differs on the possible content of the left-most bit. In case of an ordinary int it is reserved for sign (sign bit), but all the bits in an unsigned int are used for determining the magnitude of the integer value. The char data type is used to represent individual character. It occupies one byte i.e. 8 bits of memory. Each character has an equivalent ASCII representation, which is nothing but an integer. So char variables or constants can be used as integer data in arithmetic expressions.

Data type Description Size in bytes Range char single character 1 byte 0 - 255 int integer number 4 bytes. - 2147483648 to 2147483647 float single precision floating point number (number containing fraction or an exponent)

4 bytes. 3.4E-38 to 3.4E+

double double precision floating point number

8 bytes. 1.7E-308 to 1.7E+

Data type Size in bytes Range short int 2 bytes. - 32768 to 32767 long int 4 bytes - 2147483648 to 2147483647 unsigned short int 2 bytes 0 to 65535 unsigned int 4 bytes 0 to 4294967295 unsigned long int 4 bytes 0 to 4294967295 long double (Extended Precision) 8 bytes. 1.7E-308 to 1.7E+

Some of these data categories are split into more than one data type as per An Overview of C Fig. 1.6 below. ‘C’ Numeric data types. Table of Variable types.

Fig. 1.6 Variable types The main variable types that you will use most are char, int, float. If you wish to use larger numbers than those allowed in int and float then refer to this table for the type you should use.

1.4.3 Variable Declaration Examples

Single declarations int age; float amountOfMoney; char initial;

Multiple declarations You can repeat the declaration line with a different variable on each line e.g. int age; int houseNumber; but the normal way is to separate the variables by a comma. Although not required the names are easier to read if a space follows the comma. int age, houseNumber, quantity; float distance, rateOfDiscount; char firstInitial, secondInitial;

Variable Type Keyword Range Storage in Bytes Character char - 127 to 127 1 Unsigned character unsigned char 0 to 255 1

Integer int - 32,768 to 32,767 2 Unsigned integer unsigned int 0 to 65,535 2

Short integer short - 32,768 to 32,767 2 Unsigned short integer unsigned short 0 to 65,535 2

Long integer long - 2,147,483,648 to 2,147,483,647 4 Unsigned long integer unsigned long 0 to 4,294,967,295 4

Single precision floating point

float 1.2E- 38 to 3.4E38, approx. range precision = 7 digits.

4

Double precision floating point

double 2.2E- 308 to 1.8E308, approx. range precision = 19 digits.

8

Problem Solving &

Programming in C 1.4.4 Variable Scope

The scope of a variable is the area of the program where that variable is valid, i.e., the parts of the program that have access to that variable. This is determined by the location of the declaration. The life span of that variable, i.e. the length of time that the variable remains in memory. The scope of a variable depends on where it is declared.

1.4.5 Where do you Declare Variables?

Variables can be declared  Prior to the start of the main( ) function.  Within the main function, after the opening {  Within a function, after the opening {  Within a block of code, after the {

1.4.6 Global or External Variable

 Declared before the start of the main( ) function  Scope: In the small programs that are used in these tutorials the scope is any where in the program, this includes main and all the other functions.  Life Span: While the program is running.  Global variables are automatically initialised to 0 (zero), but get into the practice of initialising ALL variables.  It is usually better to avoid the use of global variables. Global variables are defined above main() in the following way:-

short number,sum; int bignumber,bigsum; char letter;

main() {

}

It is also possible to pre-initialise global variables using the = operator for assignment. For example: float sum=0.0; int bigsum=0; char letter=‘A’;

main() { }

Problem Solving &

Programming in C 1.4.9 Automatic Variable

 Declared within the { } braces of a block of code.  The declaration is placed after the { (start brace of the block of code) and before any statements in that block.  Scope: of a local local variable is limited to the braces of the portion of code it is declared in.  Life Span:Local local variables are destroyed when the end } brace is reached.

1.4.10 Assigning a value into a Variable

In the following age = 24; We are assigning the value of the expression, 24 in the example, on the right of the = (the assignment operator) into the variable on the left. When you assign a value into a variable, the previous value in that variable is overwritten and therefore destroyed. Example: int age = 21, houseNumber = 0; float amountOfMoney = 0.0; char firstInitial = ‘S’, secondInitial = 72; Note: When initialising a variable, also known as assigning a value to a variable do not think of = (the assignment operator) being the same as a mathematical = (equals), because it is not. Imagine that you wish to swap the values that are held in 2 variables named x and y after reading the above you will understand that the following will NOT work. x = y; y = x; The result of the above is that both x and y will now contain the original value of y. A way around this problem is to use a third temporary variable. temp = x; x = y; y = temp;

1.4.11 Assigning a value into Multiple Variables

C also allows multiple assignment statements using =, for example: a=b=c=d=3; ...which is the same as, but more efficient than: a=3; b=3; c=3; d=3; This kind of assignment is only possible if all the variable types in the statement are the same.

1.4.12 User defined Data Type or Typedef An Overview of C

You can define your own types use typedef. This will have greater relevance later in the course when we learn how to create more complex data structures. As an example of a simple use let us consider how we may define two new types real and letter. These new types can then be used in the same way as the pre-defined C types: typedef real float; typedef letter char; Variables declared: real sum=0.0; letter nextletter;

1.5 CONSTANTS

The constants in C can be classified into four categories.

  1. Integer constants
  2. Floating point constants
  3. Character constants
  4. String constants.
1.5.1 Integer Constants

An integer constant is written as 1234. A long int is recognized by the putting L (uppercase or lowercase) at the end of the constant, e.g. 2349713l. The suffix u or U signifies the int to be an unsigned one. The UL or ul at the end indicates the int quantity is of unsigned long type. C also supports octal and hexadecimal type data. The value of an integer data can be specified in either octal or hexadecimal form. A hexadecimal constant must begin with 0x or 0X, a leading 0 indicates the octal representation. To indicate unsigned or long U or L should follow the Octal and hexadecimal constants.

The number 0x3B7 is an example of a hexadecimal number. Internally the number is represented by the following bit patterns, 0x3B7 = 0011 1011 0111 = 3 * 16^2 + 11 * 16^1 + 7 * 16^0 = 3 B 7 The number 951 is the decimal equivalent of the number 0x3B7. The example of an octal number can be 0572. To represent each digit of an octal number in the form of binary, we need maximum of three bits since the last digit in the octal number system is 7. 0572 = 101 111 010 = 5 * 8^2 + 7 * 8^1 + 2 * 8^0 =378(in decimal) 3 4 7 In integer or floating point constants, blanks and any non-numeric characters cannot be included. The range of these constants will be limited by the maximum and minimum bounds (usually machine dependent).