179
American International University-Bangladesh Department of Computer Science AMERICAN INTERNATIONAL UNIVERSITY–BANGLADESH (AIUB) FACULTY OF SCIENCE & INFORMATION TECHNOLOGY DEPARTMENT OF COMPUTER SCIENCE LABORATORY MANUAL CSC 1102 Programming Language 1 Prepared by CSC 1102 PROGRAMMING LANGUAGE 1 Page 1 of 179

fahimbd555.files.wordpress.com  · Web viewfor consistent representation of numbers. In mathematical numeral systems, the radix or base is the number of unique digits, including

Embed Size (px)

Citation preview

American International University-BangladeshDepartment of Computer Science

AMERICAN INTERNATIONAL UNIVERSITY–BANGLADESH

(AIUB)

FACULTY OF SCIENCE & INFORMATION TECHNOLOGY

DEPARTMENT OF COMPUTER SCIENCE

LABORATORY MANUAL

CSC 1102 Programming Language 1

Prepared by

Mashiour RahmanAssistant Professor

CSC 1102 PROGRAMMING LANGUAGE 1 Page 1 of 137

American International University-BangladeshDepartment of Computer Science

Table of Contents

1. INTRODUCTION TO PROGRAMMING LANGUAGE (I)1.1. OBJECTIVES

1.1.1. LECTURE1.1.2. LABORATORY

1.2. DECLARATIVE & IMPERATIVE KNOWLEDGE1.3. COMPONENTS1.4. REPRESENTING INFORMATION

1.4.1. NUMERICAL BASES1.4.1.1. DECIMAL NUMBER1.4.1.2. BINARY NUMBER

1.4.2. CHARACTER SET1.4.2.1. THE C ALPHABET1.4.2.2. ASCII CHARACTER SET1.4.2.3. ESCAPE SEQUENCES1.4.2.4. RESERVED KEYWORDS

LABORATORY 1.5. SOLVING PROBLEMS

1.5.1. ALGORITHMS1.5.2. PSEUDO CODE / FLOW CHART1.5.3. EXERCISES

2. INTRODUCTION TO PROGRAMMING LANGUAGE (II)2.1. OBJECTIVES

2.1.1. LECTURE2.1.2. LABORATORY

2.2. EXECUTION OF A PROGRAM2.2.1. INSTRUCTION SET OR MACHINE CODE2.2.2. SOURCE CODE2.2.3. EXECUTABLE FILE2.2.4. INTEGRATED DEVELOPMENT ENVIRONMENT (IDE)2.2.5. CONVERSION

2.2.5.1. COMPILER2.2.5.2. INTERPRETER

2.3. ABSTRACTION2.3.1. LOW LEVEL LANGUAGE2.3.2. HIGH LEVEL LANGUAGE

2.4. LAYOUT OF A C PROGRAM2.4.1. PRE-PROCESSOR DIRECTIVES2.4.2. HEADER FILE2.4.3. BRACKET SET () AND {}2.4.4. STATEMENT AND SEMICOLON (;)2.4.5. FUNCTION

2.4.5.1. THE main()FUNCTION2.4.5.2. THE printf()FUNCTION

2.4.6. COMMENTS LABORATORY

2.5. IDE USAGE (EDITING, COMPILING, EXECUTING )2.6. EXERCISES

3. DATA STORAGE (I) & OPERATORS (I)3.1. OBJECTIVES

3.1.1. LECTURE

CSC 1102 PROGRAMMING LANGUAGE 1 Page 2 of 137

American International University-BangladeshDepartment of Computer Science

3.1.2. LABORATORY3.2. DATA STORAGE CONCEPT

3.2.1. VARIABLES3.2.2. IDENTIFIER3.2.3. DATA TYPES

3.2.3.1. NUMBER TYPES3.2.3.2. SYMBOL TYPE3.2.3.3. SIGNED & UNSIGNED3.2.3.4. CONSTANTS

3.2.3.4.1. INTEGER NUMERALS3.2.3.4.2. FLOATING POINT NUMBERS3.2.3.4.3. CHARACTER AND STRING LITERALS

3.2.4. DECLARING A VARIABLE3.2.5. MEMORY MANAGEMENT3.2.6. TYPE CASTING

3.3. OPERATOR, OPERAND, OPERATION3.3.1. ASSIGNMENT OPERATOR3.3.2. ARITHMETIC OPERATORS3.3.3. RELATIONAL OPERATORS3.3.4. LOGICAL OPERATORS3.3.5. BITWISE OPERATORS3.3.6. PRECEDENCE OF OPERATORS

LABORATORY3.4. THE input/output library FUNCTION

3.4.1. THE printf()OUTPUT FUNCTION3.4.2. THE scanf()INPUT FUNCTION3.4.3. THE % FORMAT SPECIFIERS

3.5. EXERCISES3.5.1. PROGRAM WRITING3.5.2. OUTPUT TRACING

4. CONTROL STRUCTURES (I)4.1. OBJECTIVES

4.1.1. LECTURE4.1.2. LABORATORY

4.2. COMPOUND STATEMENT4.3. THE DECISION STRUCTURE: if-else4.4. THE SELECTIVE STRUCTURE: switch4.5. LABORATORY EXERCISES

4.5.1. DEBUGGING TOOLS4.5.2. PROGRAM WRITING4.5.3. OUTPUT TRACING

5. CONTROL STRUCTURES (II)5.1. ITERATION STRUCTURES: LOOPS

5.1.1. THE while LOOP5.1.2. THE do-while LOOP5.1.3. THE for LOOP

5.2. LABORATORY EXERCISES5.2.1. DEBUGGING TOOLS5.2.2. LOOP CONVERSION5.2.3. PROGRAM WRITING5.2.4. OUTPUT TRACING

6. DATA STORAGE (II)6.1. OBJECTIVES

CSC 1102 PROGRAMMING LANGUAGE 1 Page 3 of 137

American International University-BangladeshDepartment of Computer Science

6.1.1. LECTURE6.1.2. LABORATORY

6.2. ARRAY6.2.1. DECLARATION6.2.2. INITIALIZATION6.2.3. ACCESS6.2.4. SOME FACTS6.2.5. DECLARATION, INITIALIZATION, AND ACCESS OF 2-D ARRAY

6.3. LABORATORY EXERCISES6.3.1. SORTING & SEARCHING6.3.2. PROGRAM WRITING6.3.3. OUTPUT TRACING

7. FUNCTIONS (I)7.1. OBJECTIVES

7.1.1. LECTURE7.1.2. LABORATORY

7.2. INTRODUCTION TO FUNCTIONS7.3. DECLARATION & DEFINITION7.4. FLOW OF FUNCTION EXECUTION

7.4.1. FUNCTION CALLS7.4.2. RETURN

7.5. SCOPE OF VARIABLES7.6. LABORATORY EXERCISES

7.6.1. PROGRAM WRITING7.6.2. OUTPUT TRACING

8. MIDTERM EXAM9. FUNCTIONS (II)

9.1. CALL BY VALUE9.2. CALL BY REFERENCE9.3. ARRAY AS PARAMETER9.4. RECURSIVE FUNCTIONS9.5. LABORATORY EXERCISES

9.5.1. I/O FUNCTION cinAND cout9.5.2. PROGRAM WRITING9.5.3. OUTPUT TRACING

10. POINTERS10.1. POINTER & VARIABLE10.2. POINTER & ARRAY10.3. POINTER AND FUNCTION

10.3.1. POINTER AS PARAMETER10.3.2. POINTER AS RETURN10.3.3.VOID POINTER

10.4. NULL POINTERS10.5. DYNAMIC MEMORY ALLOCATION10.6. MORE ON POINTER INITIALIZATION10.7. LABORATORY EXERCISES

10.7.1. PROGRAM WRITING10.7.2. OUTPUT TRACING

11. DATA STORAGE (III)11.1. STRING

11.1.1. DECLARATION & INITIALIZATION11.1.2. ACCESS, INPUT, OUTPUT11.1.3. STRING HANDLING FUNCTIONS

CSC 1102 PROGRAMMING LANGUAGE 1 Page 4 of 137

American International University-BangladeshDepartment of Computer Science

11.2. LABORATORY EXERCISES11.2.1. PROGRAM WRITING11.2.2. OUTPUT TRACING

12. PERSISTENCE

12.1. OBJECTIVES

12.2. FILE

12.2.1. DECLARING A FILE POINTER12.2.2. OPENING FILES12.2.3. READING FROM OR WRITING TO A FILE12.2.4. CLOSING A FILE

12.3. SPECIAL FILE POINTERS12.3.1. STANDARD INPUT

12.3.2. STANDARD OUTPUT

12.3.3. STANDARD ERROR12.4. LABORATORY EXERCISES

12.4.1. PROGRAM WRITING12.4.2. OUTPUT TRACING

13. CUSTOM TYPES (I)13.1. OBJECTIVES

13.2. STRUCTURE

13.2.1. DEFINING A STRUCTURE

13.2.2. ACCESSING STRUCTURE MEMBERS

13.3. UNION

13.3.1. DEFINING A UNION

13.3.2. ACCESSING UNION MEMBERS

13.4. BIT FIELD

13.4.1. BIT FIELD DECLARATION

13.5. LABORATORY EXERCISES13.5.1. PROGRAM WRITING13.5.2. OUTPUT TRACING

14. CUSTOM TYPES (II)14.1. OBJECTIVES:14.2. STRUCTURES AS FUNCTION ARGUMENTS

14.3. POINTERS TO STRUCTURES

14.4. THE typedef KEYWORD14.4.1.typedefVS #define

14.5. NESTED STRUCTURE

14.5.1. ACCESSING NESTED MEMBERS :14.6. BINARY I/O FUNCTIONS

14.7. LABORATORY EXERCISES14.7.1. PROGRAM WRITING14.7.2. OUTPUT TRACING

15. OOP15.1. OBJECTIVES:15.2. THE PHILOSOPHY OF OOP

15.2.1. WHAT IS AN OBJECT?15.2.2. WHAT IS A CLASS?15.2.3. OOP PRINCIPLES

15.3. C++ CLASS AND OBJECT

CSC 1102 PROGRAMMING LANGUAGE 1 Page 5 of 137

American International University-BangladeshDepartment of Computer Science

15.3.1. CLASS DEFINITIONS

15.3.2. DEFINE OBJECTS

15.3.3. ACCESSING THE DATA MEMBERS

15.3.4. CLASS MEMBER FUNCTIONS

15.3.5. CLASS ACCESS MODIFIERS

15.3.5.1. THE PUBLIC MEMBERS

15.3.5.2. THE PRIVATE MEMBERS

15.3.5.3. THE PROTECTED MEMBERS

15.4. LABORATORY EXERCISES15.4.1. PROGRAM WRITING15.4.2. OUTPUT TRACING

16. FINAL TERM EXAM

CSC 1102 PROGRAMMING LANGUAGE 1 Page 6 of 137

American International University-BangladeshDepartment of Computer Science

1. INTRODUCTION TO PROGRAMMING LANGUAGE (I)

1.1. OBJECTIVES:To gain experience with –

Data representation in computers using Binary number system. Understanding Algorithms Pseudo code or flow chart.

1.2. REPRESENTING INFORMATION:

We need to understand how we are going to representation information, which we will use as the basis for our computational processes. To do this, we need to decide on representations for numeric values and for symbolic ones. Let us first go through numerical system, a way to express numbers.

1.2.1. NUMERICAL BASES

A numeral system (or system of numeration) is a writing system for expressing numbers, that is, a mathematical notation for representing numbers of a given set, using digits or other symbols in a consistent manner. Generally, positional number system is used with radix or base for consistent representation of numbers. In mathematical numeral systems, the radix or base is the number of unique digits, including zero that a positional numeral system uses to represent numbers. In any numeral system (except unary, where radix is 1), the base will always be written as (x)y. For example, (10)10 represents the number ten in the decimal system;(10)2 represents the number two in a base two system. Any b base number uses the digits 0 to b-1 to represent the number. For example, base 8 numbers will use only the digits 0, 1, 2, 3, 4, 5, 6, 7 to represent its numbers. Digits 8 and 9 will never occur in a base 8 number. In general, in base-b, the number (a3a2a1a0)b = a3×b3+a2×b2

+a1×b1 + a0×b0 where a3a2a1a0represents a sequence of digits, b represents the base, an

represents the digits in position n (right to left), and bn represents the power of b for the digit in position n.

1.2.1.1. DECIMAL NUMBER

It's generally easiest to understand the concept of different bases by looking at base 10 or decimal numbers as it is the numerical base most widely used by modern civilizations. In a base 10 or decimal number system numbers are represented by only 10 digits – 0,1,2,3,4,5,6,7, 8, 9. For example, the representation of the value (286713)10is as follows – Position 5 4 3 2 1 0Decimal Number 2 8 6 7 1 3Base power 105 104 103 102 101 100

2 × 105 = 200000

8 × 104 = 80000

6 × 103 = 6000

7 × 102 = 700

CSC 1102 PROGRAMMING LANGUAGE 1 Page 7 of 137

American International University-BangladeshDepartment of Computer Science

1 × 101 = 10

3 × 100 = 3

(286713)10

When we have a number in base 10, each digit can be referred to as the ones digit, tens digit, the hundreds digit, the thousands digit, or so forth. Every base number system has their own reference names for each position or group of positions.

1.2.1.2. BINARY NUMBER

To represent a number in a machine, we have to start with the most atomic element, because electronic signals are used to represent information internally inside the computer. The fundamental values are most conveniently represented by using a high voltage/current/positive charge or a low voltage/current/negative (or no) charge. Thus, the most primitive element in representing a value is a binary variable, which takes on one of two values: a zero (low voltage) or a one (high voltage).

In a base 2 or binary number system numbers are represented by only 2 digits – 0 and1. For example, the representation of the binary value (101011)2 in decimal is as follows – Position 5 4 3 2 1 0Binary Number 1 0 1 0 1 1Base power 25 24 23 22 21 20

1 × 25 = 32

0 × 24 = 0

1 × 23 = 8

0 × 22 = 0

1 × 21 = 2

1 × 20 = 1

(43)10So, binary value (101011)2 is equivalent to (43)10 in decimal. It's important to realize that each of these base systems is just another way of writing down the same number. When you convert a number between different bases, it should still have the same value. As we generally use decimal number system, the comparison or conversion is also generallywith decimal number. So, referring to any actual value of a number (regardless of its base), is in base 10 because that's what most people are used to. Here actual value for (101011)2 is 43. Now let’s see if n=43is equal to (101011)2.

CSC 1102 PROGRAMMING LANGUAGE 1 Page 8 of 137

American International University-BangladeshDepartment of Computer Science

Position 5 4 3 2 1 0Binary Number 1 0 1 0 1 1 bit Next n n ÷ b

1 0 1 ÷ 2 0 1 2 ÷ 2 1 2 5 ÷ 2 0 5 10 ÷ 2 1 10 21 ÷ 2

1 21 43 ÷ 2Remainder Result Divide

The calculation starts at the bottom (bold) of the table. The number n=43 is divided by the base 2. The result is 21 and the remainder is 1. The result 21 becomes the next n to be divided. The process goes on until result is zero, 0. The binary digit which is calculated last (1÷2=0) goes to the first (0th) position. The previous binary digit goes to the next position, and so on.

This binary digit represents one bit. Of course, we need to group these bits together to represent other numbers, which we do typically in groupings of 8 bits (a byte) or in groupings of 16, 32, or 48 bits (a word). In computers, positional systems obtained by grouping binary digits by three (octal numeral system, base 8) or four (hexadecimal numeral system, base 16) are also commonly used.

Once we have sequences of bits, we can use them not only to represent other numbers, but we can envision encodings, in which numbers or bit sequences are used to represent characters. And characters can further be group together to represent symbolic words. There are standard encoding schemes for using bit sequences to represent characters as well as numbers (ASCII).

1.2.2. CHARACTER SET

The character set is the fundamental raw material of any language and they are used to represent information. Like natural languages, computer language also has well defined character set, which is useful to build the programs.The Standard talks about two different character sets: the one that programs are written in (Source character set) and the one that programs execute with (Execution character set).

1.2.2.1. THE C ALPHABET

The Standard requires an alphabet of 96 symbols which is available for writing code in C, also known as Source Character set. They are as follows:

a b c d e f g h I j k l m n o p q r s t u v w x y z

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

0 1 2 3 4 5 6 7 8 9

! “ # % &‘ ( ) * + , - . /

: ; < = > ? [ \ ] ^ _ { | } ~

CSC 1102 PROGRAMMING LANGUAGE 1 Page 9 of 137

American International University-BangladeshDepartment of Computer Science

space, horizontal and vertical tab

form feed, newline

These symbols are combined together to represent different meaningful words, words are combined together to represent meaningful statement, statements are combined together to represent a meaningful task for the computer to perform.

1.2.2.2. ASCII CHARACTER SET

Now let’s see the other form of alphabet which the program executes, also known as Execution Character set. It is now well-known fact that computers can manage internally only 0s (zeros) and 1s (ones). And by means of sequences of 0s and 1s the computer can express any numerical value as its binary translation.

Nevertheless, there is no such evident way to represent letters and other non-numeric characters with 0s and 1s. Therefore, in order to do that, computers use ASCII tables, which are tables or lists that contain all the letters in the Roman alphabet plus some additional characters. In these tables each character is always represented by the same order number. For example, the ASCII code for the capital letter "A" is always represented by the order number 65, which is easily representable using 0s and 1s in binary: 65 expressed as a binary number is 1000001.

The standard ASCII table defines 128 character codes (from 0 to 127), of which, the first 32 are control codes (non-printable), and the remaining 96 character codes are representable characters. The following chart contains all 128ASCII decimal (dec), octal (oct), hexadecimal (hex) and character (ch) codes.

ASCII CHART

dec oct hex ch dec oct hex ch dec oct hex ch dec oct hex ch0 0 00 NUL (null) 32 40 20 (space) 64 100 40 @ 96 140 60 `1 1 01 SOH (start of header) 33 41 21 ! 65 101 41 A 97 141 61 a2 2 02 STX (start of text) 34 42 22 " 66 102 42 B 98 142 62 b3 3 03 ETX (end of text) 35 43 23 # 67 103 43 C 99 143 63 c4 4 04 EOT (end of transmission) 36 44 24 $ 68 104 44 D 100 144 64 d5 5 05 ENQ (enquiry) 37 45 25 % 69 105 45 E 101 145 65 e6 6 06 ACK (acknowledge) 38 46 26 & 70 106 46 F 102 146 66 f7 7 07 BEL (bell) 39 47 27 ' 71 107 47 G 103 147 67 g8 10 08 BS (backspace) 40 50 28 ( 72 110 48 H 104 150 68 h9 11 09 HT (horizontal tab) 41 51 29 ) 73 111 49 I 105 151 69 i10 12 0a LF (line feed - new line) 42 52 2a * 74 112 4a J 106 152 6a j11 13 0b VT (vertical tab) 43 53 2b + 75 113 4b K 107 153 6b k12 14 0c FF (form feed - new page) 44 54 2c , 76 114 4c L 108 154 6c l13 15 0d CR (carriage return) 45 55 2d - 77 115 4d M 109 155 6d m

CSC 1102 PROGRAMMING LANGUAGE 1 Page 10 of 137

American International University-BangladeshDepartment of Computer Science

14 16 0e SO (shift out) 46 56 2e . 78 116 4e N 110 156 6e n15 17 0f SI (shift in) 47 57 2f / 79 117 4f O 111 157 6f o16 20 10 DLE (data link escape) 48 60 30 0 80 120 50 P 112 160 70 p17 21 11 DC1 (device control 1) 49 61 31 1 81 121 51 Q 113 161 71 q18 22 12 DC2 (device control 2) 50 62 32 2 82 122 52 R 114 162 72 r19 23 13 DC3 (device control 3) 51 63 33 3 83 123 53 S 115 163 73 s20 24 14 DC4 (device control 4) 52 64 34 4 84 124 54 T 116 164 74 t21 25 15 NAK (negative acknowledge) 53 65 35 5 85 125 55 U 117 165 75 u22 26 16 SYN (synchronous idle) 54 66 36 6 86 126 56 V 118 166 76 v23 27 17 ETB (end of transmission block) 55 67 37 7 87 127 57 W 119 167 77 w24 30 18 CAN (cancel) 56 70 38 8 88 130 58 X 120 170 78 x25 31 19 EM (end of medium) 57 71 39 9 89 131 59 Y 121 171 79 y26 32 1a SUB (substitute) 58 72 3a : 90 132 5a Z 122 172 7a z27 33 1b ESC (escape) 59 73 3b ; 91 133 5b [ 123 173 7b {28 34 1c FS (file separator) 60 74 3c < 92 134 5c \ 124 174 7c |29 35 1d GS (group separator) 61 75 3d = 93 135 5d ] 125 175 7d }30 36 1e RS (record separator) 62 76 3e > 94 136 5e ^ 126 176 7e ~31 37 1f US (unit separator) 63 77 3f ? 95 137 5f _ 127 177 7f DEL (delete)

1.2.2.3. ESCAPE SEQUENCES

Escape sequences are used to define certain special characters within string literals. These are special characters that are difficult or impossible to express otherwise in the source code of a program, like newline (\n) or tab (\t). All of them are preceded by a backslash (\).The following escape sequences are available:

Escapesequence Description ASCII

valueEscapesequenceDescription

ASCII value

EscapesequenceDescription

ASCII value

\0 null character 0 \n line feed - new line 10 \" double quote 22\a audible bell 7 \v vertical tab 11 \' single quote 27\b backspace 8 \f form feed - new page 12 \? question mark 63\t horizontal tab 9 \r carriage return 13 \\ backslash 92

1.2.2.4. RESERVED KEYWORDS

This is a list of some frequently used reserved keywords in C. Since they are used by the language, these keywords are not available for re-definition.auto break case float for goto struct switchchar const continue if int long typedef uniondefault do double register return short unsigned voidelse enum extern signed sizeof static volatile while

1.3. SOLVING PROBLEMS

We will be using programming language for computer to solve a given problem. Any given problem always has three components – Input, Process, and Output. A set of input (data) is given to be processed in some well-defined order to produce a legitimate set of output (information).

CSC 1102 PROGRAMMING LANGUAGE 1 Page 11 of 137

American International University-BangladeshDepartment of Computer Science

1.3.1. ALGORITHMS

This series of specific, mechanical steps is known as algorithms. So, Algorithm is the first step of solving a problem. A programmer must first analyze the problem and device an algorithm to solve it. Then the programmer will be writing the steps using some language. As we are first in programming languages, we will start with pseudo code and flow chart.

1.3.2. PSEUDO CODE& FLOW CHART

Pseudo Code is an informal high-level description of the operating principle of a computer program or other algorithm. It uses the structural conventions of a programming language, but is intended for human reading rather than machine reading.

A flowchart is a type of diagram that represents an algorithm or process, showing the steps as boxes of various kinds, and their order by connecting them with arrows. This diagrammatic representation illustrates a solution to a given problem.

Symbol Name FunctionArrows Connector showing the flow of the algorithm

Start/End Start or end point of the algorithm

Input/Output Represents data input or output

Process Any processing statement

Decision Decision which branches to two outcomes (true/false)

Let us go through the exercises for better understanding.

1.3.3. EXERCISES:

Write down steps to find -

1.3.3.1. The largest number between two given numbers.

Step 1 Step 2Step 3Step 4Step 5

// The largest number between two given numbers Start; Input two numbers: n1 and n2;Ifn1>n2thenOutputn1; go-toStep 5;(Otherwise) Outputn2;Exit.

1.3.3.2. The largest number among three given numbers.

1.3.3.3. Sum of all the even numbers from 1 to a given number.

CSC 1102 PROGRAMMING LANGUAGE 1 Page 12 of 137

STARTEND

INPUTn1, n2

OUTPUTn2

OUTPUTn1

n1 > n2

NO

YES

American International University-BangladeshDepartment of Computer Science

Step 1 Step 2Step 3Step 4Step 5Step 6Step 7Step 8

// Sum of all the even numbers // from 1 to a given numberStart;Input a number- n;Define two numbers- s and k; s0; k1;Ifk>nthengo-toStep 7;(otherwise)If (k modulo 2)=0 then ss+k;kk + 1; go-toStep 4;Outputs;Exit.

** The red arrows indicating loop

1.3.3.4. If a given year is Leap-year.

1.3.3.5. If a given number is even or odd.

Step 1 Step 2Step 3Step 4Step 5

// If a given number is even or oddStart;Input a number- n;If (n modulo 2) = 0 thenOutput“EVEN”; go-toStep 5;(otherwise) Output“ODD”;Exit.

1.3.3.6. If a given number is Prime.

Step 1 Step 2Step 3Step 4Step 5Step 6Step 7

// If a given number is PrimeStart;Input number- n;Define a number- p; p 2;Ifp≥n thenOutput“PRIME”; go-toStep 7;(otherwise) If (n modulo p)=0 thenOutput“NOT PRIME”; go-toStep 7;pp + 1; go-toStep 4;Exit.

1.3.3.7. Sum of all the Prime numbers from 1 to a given number.1.3.3.8. Sum of all the digits of a given number.1.3.3.9. Reverse a given integer. [Example: Input: 123; Output: 321]

Step 1 Step 2Step 3Step 4Step 5Step 6Step 7Step 8

// Reverse a given integerStart;Input an integer- n.Define two numbers- s, and m,; s0; Ifn= 0 then go-toStep 9;m (n modulo 10); s (s × 10) + m;nn / 10; go-toStep 4;

CSC 1102 PROGRAMMING LANGUAGE 1 Page 13 of 137

START

END

INPUT n

OUTPUTn2

k > nNO

YES

NO

YES

k = 0s = 0

k = k + 1

(k mod 2)=0

s = s + k

American International University-BangladeshDepartment of Computer Science

Step 9Step 10

Outputs;Exit.

1.3.3.10.If a given number is palindrome. [Example: 123321 is a palindrome as it is same after reversing].

CSC 1102 PROGRAMMING LANGUAGE 1 Page 14 of 137

American International University-BangladeshDepartment of Computer Science

2. INTRODUCTION TO PROGRAMMING LANGUAGE (II)

2.1. OBJECTIVES:To gain experience with –

The processes related to writing and execution of a program. Compiler & Interpreter. Components, construction, compilation, execution of a sample program. Introductory concept of statement, library/header files in C.

Introductory concept of function using main and I/O (printf, scanf) in C.

2.2. EXECUTION OF A PROGRAM:

Just writing the instruction using any computer programming language won’t execute the instructions. There are different ways to convert the written code to a suitable code which the machine can understand and then execute. To have a better understanding first let us go through some terminologies.

2.2.1. INSTRUCTION SET OR MACHINE CODE:

The instruction set, also called instruction set architecture (ISA), is a part of the computer that relates to programming, which is basically machine language. The instruction set provides commands to the processor, to tell it what it needs to do. The instruction set consists of multiple pieces, including addressing modes, instructions, native data types, registers, memory architecture, interrupt and exception handling, and externalI/O.

2.2.2. SOURCE CODE:

Source code is any collection of computer instructions (possibly withcomments) written using some human-readable computer language, usually as text, using any text editor or IDE. The source code of a program is specially designed to facilitate the work of computer programmers, who specifies the actions to be performed by a computer mostly by writing source code. Source code cannot be executed as the instructions are not written in machine code or using the instruction set.

2.2.3. EXECUTABLE FILE:

An executable file causes a computer to perform indicated tasks according to encoded instructions. These instructions are traditionally machine code instructions for a physical CPU. However, in a more general sense, a file containing instructions (such as byte code) for a software interpreter may also be considered executable; even a scripting language source file may therefore be considered executable in this sense. The exact interpretation depends upon the use.

2.2.4. INTEGRATED DEVELOPMENT ENVIRONMENT (IDE):

An integrated development environment (IDE) or interactive development environment is a software application that provides comprehensive facilities to computer programmers for software development. An IDE normally consists of a source code editor to write the codes using one or more defined language, build automation tools to build one or more files from the written code that is executable using a compiler or interpreter and a debugger to test the program for errors.

2.2.5. CONVERSION

CSC 1102 PROGRAMMING LANGUAGE 1 Page 15 of 137

American International University-BangladeshDepartment of Computer Science

There are basically two ways to convert a written code to be executable. They are using compiler & interpreter. In this course we will concentrate on compiler as C/C++ uses compiler for execution.

2.2.5.1. COMPILER:

A program maybe made by running a compiler which takes the typed source program and converts it into an object file that the computer can execute. A compiler usually operates in two or more phases (and each phase may have stages within it). These phases must be executed one after the other. This approach provides a flexibleway of compiling programs which are split into many files. Thegeneralsteps of how a compiler works:

Scans a source program, perhaps generating an intermediate code (quadruples or pcode) which helps to simplify the grammar of the language for subsequent processing.

It then converts the intermediate code into a file of object code (though this is usually not executable yet). A separate object file is built for each separate source file.

A program named Linker appends standard library code and links together all the functions and objects ofall the object filesand creates an executable file. Than the code is complete and can "stand alone".

IDE

EDITOR DEBUG

C/C++ SOURCE PROGRAM

COMPILERINTERMEDIATE CODE

LINKER

MACHINE CODE

ERROR

EXECUTABLE FILE

2.2.5.2. INTERPRETER:

CSC 1102 PROGRAMMING LANGUAGE 1 Page 16 of 137

American International University-BangladeshDepartment of Computer Science

In computer science, an interpreter is a computer program that executes, i.e. performs, instructions written in a programming language. An interpreter generally uses one of the following strategies for program execution:

Parse the source code and perform its behavior directly. Translate source code into some efficient intermediate representation and

immediately execute this. Explicitly execute stored precompiled code made by a compiler which is part of the

interpreter system.

2.3. LAYOUT OF A C PROGRAM:

The general form of a C program is as follows (don't worry about what everything means at the moment - things will be explained later):

pre-processor directivesglobal declarationsvoidmain(void){ local variabledeclarations to function main ; statements associated with function main ;}f1(){ local variabledeclarations to function 1 ; statements associated with function 1 ;}f2(){ local variabledeclarations to function f2 ; statements associated with function 2 ;}...etc

2.3.1. PRE-PROCESSOR DIRECTIVES:

Preprocessor directives are lines included in the code of our programs that are not program statements but directives for the preprocessor. The preprocessor provides the ability for the inclusion of header files, macro expansions, conditional compilation, and line control. These lines are always preceded by a hash sign (#). The preprocessor is executed before the actual compilation of code begins. These preprocessordirectives extend only across a single line of code. As soon as a newline character isfound, the preprocessor directive is considered to end. No semicolon (;) is expected atthe end of a preprocessor directive

2.3.2. HEADER FILE:

A header file is a file containing C declarations and macro definitions to be shared between several source files. C Standard library functions or simply C Library functions are inbuilt functions in C programming. Function prototype and data definitions of these functions are written in their respective header file. For example: to print anything on the console screen a readymade function printf()can be used.The header file stdio.h, standard input output library, should be included with the C preprocessing directive #include<stdio.h>. In C,

CSC 1102 PROGRAMMING LANGUAGE 1 Page 17 of 137

American International University-BangladeshDepartment of Computer Science

the usual convention is to give header files names that end with .h extension. Note the use of the angle brackets (< and >) around the header's name. These indicate that the header file is to be looked for on the system disk which stores the rest of the C program application. An alternative convention #include "stdio.h"is also used. The double quotes indicate that the current working directory should be searched for the required header file. This will be true when you write your own header files but the standard header files should always have the angle brackets around them. So, header files serve two purposes.

System header files declare the interfaces to parts of the operating system. You include them in your program to supply the definitions and declarations you need to invoke system calls and libraries.

Your own header files contain declarations for interfaces between the source files of your program. Each time you have a group of related declarations and macro definitions all or most of which are needed in several different source files, it is a good idea to create a header file for them.

There are many library functions available in C programming to help the programmer to write a good efficient program. Suppose, to find the square root of a number,a piece of code can be written to find square root but, this process is time consuming and the written code may not be the most efficient process to find square root. But, in C programming you can find the square root by just using sqrt() function which is defined under header file math.h.

2.3.3. BRACKET SET () AND {}

Note the use of the bracket set () and {}. () are used in conjunction with function names whereas {} are used as to delimit the C statements that are associated with that function.

2.3.4. STATEMENT AND SEMICOLON (;):

Note that a semicolon (;) is used to terminate C statements. C is a free formatlanguage and long statements can be continued, without truncation, onto the next line.The semicolon informs the C compiler that the end of the statement has been reached.Free format also means that you can add as many spaces as you like to improve thelook of your programs.

2.3.5. FUNCTION:

A function in mathematics relates an input to an output. It is like a machine that has an input and an output. And the output is related somehow to the input. "f(n) = ... " is the classic way of writing a function. There will always be three main parts in a function: the input, therelationship,the output. For example: "Multiply by 2" is a very simple function represented as f( n ) = n × 2.

Input (n) Relationship(n × 2) Output (2n)0 × 2 01 × 2 27 × 2 1410 × 2 20... ... ...

Function in programming is a segment that groups a number of program statements to perform specific task. The format of a function in C is

CSC 1102 PROGRAMMING LANGUAGE 1 Page 18 of 137

American International University-BangladeshDepartment of Computer Science

data_typefunction_name( argument_list ){

processing statements;return value;

}

Let us construct a function for the mathematical function f( n ) = n × 2.123456

// Function in ProgrammingintDouble( int n ){

int r = n * 2;return r;

}

// Function in Mathematicsf( n ) = n × 2 = 2n

Following the color codes respectively for programming and mathematic functions –

function_name: Double and f are the names of the function.

argument _list vs input: int n within parenthesis () after Double corresponds to the input n within the parenthesis after f. Here int represents integer number.

processing vs relationship: The statement int r=n*2 inside parenthesis {} corresponds to n × 2after f(n). The result of n*2 (* represents ×) is kept in an integer (int) variable r.

return vs result: int before Double and return r; within the {} corresponds to the 2n, the final result of f(n). An integer (int) value r is returned (return r).

Basically, there are two types of functions in C on basis of whether it is defined by user or not.

Library functionis the in-built function in C programming system. For example:

main()- The execution of every C program starts from this main() function.printf()- is used for displaying output in C.scanf()- is used for taking input in C.

User Defined functionis defined by the programmer according to their requirement. We will only go for the library function now. More on function will be discussed when we learn user defined function.

2.3.5.1. THE main()FUNCTION:

In C/C++ programming languages, the main function is where a program starts execution, independently of its location within the source code. It does not matter whether there are other functions with other names defined before or after it - the instructions contained within this function's definition will always be the first ones to be executed in any C/C++ program. For that same reason, it is essential that all C/C++ programs have a main function.

For simplicity we are going to write void main( void ). The type void inside the parentheses () indicates that there is no input parameter or argument list. The void before main indicates there is no output or result from this function. So we cannot use the word return at the end of the function.

CSC 1102 PROGRAMMING LANGUAGE 1 Page 19 of 137

American International University-BangladeshDepartment of Computer Science

Right after these parentheses we can find the body of the main function enclosed in braces {}. What is contained within these braces is what the function does when it is executed.

2.3.5.2. THE printf()FUNCTION:

The printf functions always takes the first parameter as string (c.f. "Hello World") but after that you can include as many parameters of any type that you want to. That is, the printf function is usually of the form:

printf(string,variable,variable,variable...)

Now we will only go for the format printf(string). For example:printf("Hello World");it results in Hello World being displayed on the screen. Anything we type within the "" will be displayed on the output screen.

2.3.6. COMMENTS

Comments are parts of the source code disregarded by the compiler. They simply do nothing. Their purpose is only to allow the programmer to insert notes or descriptions embedded within the source code. C++ supports two ways to insert comments: 12// line comment/* block comment */

The first of them, known as line comment, discards everything from where the pair of slash signs (//) is found up to the end of that same line. The second one, known as block comment, discards everything between the /*characters and the first appearance of the */ characters, with the possibility of including more than one line.

LABORATORY

2.4. IDE USAGE (EDITING, COMPILING, EXECUTING )

[Depends on which IDE is being used by the course teacher. Please add or supply separate noteregarding the IDE, editing, compiling, building, execution, output, debugging, etc.]

2.5. EXERCISES:

2.5.1. Write the first C program which prints Hello World on the screen.

123456

#include <stdio.h>//needed to run printf() function void main(void) { printf("Hello World"); //displays the content inside quotation }

Hello World

2.5.2. Write a program to print a triangle of height 5 using the character *. 1234

#include <stdio.h>void main(void) { //\n is used to goto the nextlineprintf("*\n");

**********

CSC 1102 PROGRAMMING LANGUAGE 1 Page 20 of 137

American International University-BangladeshDepartment of Computer Science

56789

printf("**\n");printf("***\n");printf("****\n");printf("*****\n");}

*****

2.5.3. Write a program to print the escape characters. 1234567891011

#include <stdio.h>void main(void) { printf("Teacher: Do you know programming\?\n");//\? is used to print ? printf("Student: No, I\'m not prepared.\n");//\' is used to print 'printf("Teacher: Check D:\\Programming\\Tutorial for details.\n");//\\ is used to print \ printf("Student: Is the book \"C++ Bible\" good?\n");//\" is used to print " printf("Teacher: Yes, it is.\n");} Teacher: Do you know programming?Student: No, I'm not prepared.Teacher: Check D:\Programming\Tutorial for details.Student: Is the book "C++ Bible" good?Teacher: Yes, it is.

2.5.4. Write a program to print a 3 × 5 table the character * in 1 st row, ** in second row, and so on.

12345678910

#include <stdio.h>void main(void) { printf("*\t*\t*\n"); //\t is used to print tab printf("**\t**\t**\n");printf("***\t***\t***\n");printf("****\t****\t****\n");printf("*****\t*****\t*****\n");}

* * *** ** ***** *** ******* **** ********* ***** *****

2.5.5. Write a program that prints your Name, ID and Department in three separate lines.(hint: \n is used to move onto new line)

2.5.6. There are three resistors in a circuit. Resistor 1 has value 4 ohm. Resistor 2 has value 8ohm and Resistor 3 has value 1 ohm. Write a program that gives the following outputValue of resistor 1: 4 ohmValue of resistor 2: 8 ohmValue of resistor 3: 1 ohmHint: Store the resistor values in integer variables.

CSC 1102 PROGRAMMING LANGUAGE 1 Page 21 of 137

American International University-BangladeshDepartment of Computer Science

3. DATA STORAGE (I) & OPERATORS (I)

3.1. OBJECTIVES:To gain experience with –

Different types of operators- arithmetic, logical, bitwise, assignment; Expressions evaluate with operator precedence; Input/Output Library functions in C Using stdio.h and math.h library function;

3.2. DATA STORAGE:

3.2.1. IDENTIFIER

A name or identifier in C can be anything from a single letter to a word. The name of a variable must begin with an alphabetic letter or the underscore _ character but the other characters in the name can be chosen from the following groups:

a ..z(any letter from a to z)A .. Z (any letter from A to Z)0 .. 9 (any digit from 0 to 9)_ (the underscore character)

3.2.2. DATA TYPES:

Any executable program must be brought to the main memory (popular as RAM) for execution. So, if we need memory to store some data we have to specify how much space is required before storing the data. For even a simple computational problem we will require a good number of data space with various sizes. We already know that, data needs to be represented in binary as a byte or a word. This means, the size must be defined in bytes starting with the lowest possible size 1 byte. For every data we have to specify the size in bytes and also need to know the address in the main memory where the data is stored. According to the knowledge we have so far about the binary number system, we can only represent whole numbers or positive integer numbers in binary. But for computational problems, we need real numbers too. And also, we need to represent the character symbols. This is a great hectic job for a programmer. So, here comes the abstraction concept. In every programming language, some basic data types are already defined. These data types vary in size and the meaning of the content in each bit.

3.2.2.1. NUMBER TYPES:

We are familiar with three types of number types – Integer (no fractional part), Real (contains fractional part) and complex numbers. C has basic type for the first two number types. They are as follows –

Type Declaration Size RangeInteger int

32 bitsSigned: From −2,147,483,648 to 2,147,483,647from −(231) to 231 − 1Unsigned: From 0 to 4,294,967,295 which equals 0 to 232 − 1

long64 bits

Signed: From −9,223,372,036,854,775,808 to9,223,372,036,854,775,807from −(263) to 263 − 1Unsigned: From 0 to 18,446,744,073,709,551,615 which equals 0 to 264 – 1

Real float 32 bits 3.4 × (10-38) to 3.4 × (10+38) with 7 digit precisiondouble 64 bits 1.7 × (10-308) to 1.7 × (10+308)with 15-16 digits precision

CSC 1102 PROGRAMMING LANGUAGE 1 Page 22 of 137

American International University-BangladeshDepartment of Computer Science

long double 80 bits 3.4× (10-4932) to 1.1 × (10+4932)

3.2.2.2. SYMBOL TYPE:

We already know that only numbers can be represented in computers. So to represent symbols we need to have a different method. We are familiar with the character set (ASCII) for C/C++. Each of these characters is numbered in the character set. For example character 'A' is numbered 65. As there are 128 symbols to represent the symbols from the ASCII character set, we need at least 1 byte (8 bits) which can range from -128 to +127. But to represent UNICODE we require 2 bytes (16 bits) which represent the all the ASCII character symbols along with all other language symbols. Following is the data type to represent UNICODE in C/C++.

Type Declaration Size RangeCharacter char 16 bits Signed: From −32,768 to 32,767, from −(215) to 215 − 1

Unsigned: From 0 to 65,535 which equals 0 to 216 − 1

3.2.2.3. SIGNED & UNSIGNED:

Let’s consider a 3 digit number in our decimal system. Using 3 digits we can represent 1000 (103) different numbers, from 0 to 999. An integral type with n bits can encode 2n numbers. An unsigned type typically represents the non-negative values 0 through 2n−1. For example, 8bits (1byte) can represent 28 (256) different numbers; 0 to 28-1 (0 to 255) unsigned (positive) numbers. As there is no way to store the negative sign '–' in bits, two’s complement is used to represent negative numbers. This enables an integral type with n bits to represent values (-2n-1) through (2n-1-1). So 8 bits (1 byte) can represent signed values from -27 to 27-1 (-128 to +127).

3.2.3. DECLARING A VARIABLE:

In order to use a variable in C/C++, we must first declare it specifying which data type we want it to be. The syntax to declare a new variable is to write the specifier of the desired data type (like int, char, float...) followed by a valid variable identifier. For example:12int a;float mynumber;

These are two valid declarations of variables. The first one declares a variable of type int with the identifier a. The second one declares a variable of type float with the identifier mynumber. Once declared, the variables a andmynumber can be used within the rest of their scope in the program.

To declare more than one variable of the same type, declare all of them in a single statement by separating their identifiers with commas. For example:  int a, b, c;

This declares three variables (a, b and c), all of them of type int, and has exactly the same meaning as:

CSC 1102 PROGRAMMING LANGUAGE 1 Page 23 of 137

American International University-BangladeshDepartment of Computer Science

123

int a;int b;int c;

The data types char, long and int can be either signed or unsigned depending on the range of numbers needed to be represented. Signed types can represent both positive and negative values, whereas unsigned types can only represent positive values (and zero). This can be specified by using either the specifiersigned or the specifier unsigned before the type name. For example:12unsignedintMyNumber;signedintMyAccountBalance;

By default, if we do not specify either signed or unsigned most compiler settings will assume the type to be signed, therefore instead of the second declaration above we could have written: intMyAccountBalance;

with exactly the same meaning (with or without the keyword signed).

3.2.4. MEMORY MANAGEMENT:

A variable is an area of memory that has been given a name. For example: the declaration int x;acquires four byte memory area and this area of memory that has been given the name x. One can use the name to specify where to store data. For example:x=lO;is an instruction to store the data value 10 in the area of memory named x. The computer access its own memory not by using variable names but by using a memory map with each location of memory uniquely defined by a number, called the address of that memory location. To access the memory of a variable the program uses the & operator. For Example: &x returns the address of the variablex.

&x represents the memory area of variable named x.

int x; x represents the value stored inside the area of variable named x.

3.2.5. TYPE CASTING:

Type casting operators allow you to convert a datum of a given type to another. There are several ways to do this in C++. The simplest one, which has been inherited from the C language, is to precede the expression to be converted by the new type enclosed between parentheses (()):123

inti;floatf = 3.14;i = (int) f;

The previous code converts the float number 3.14 to an integer value (3), the remainder is lost. Here, the typecasting operator was (int). Another way to do the same thing in C++ is using the functional notation: preceding the expression to be converted by the type and enclosing the expression between parentheses:i = int ( f );

Both ways of type casting are valid in C++.

CSC 1102 PROGRAMMING LANGUAGE 1 Page 24 of 137

American International University-BangladeshDepartment of Computer Science

3.3. CONSTANTS

Constants are expressions with a fixed value.Literals are the most obvious kind of constants. They are used to express particular values within the source code of a program. We have already used these previously to give concrete values to variables or to express messages we wanted our programs to print out, for example, when we wrote: a = 5;

the 5 in this piece of code was a literal constant.

Literal constants can be divided inInteger Numerals,Floating-Point Numerals, Characters, Strings and Boolean Values.

3.3.1. INTEGER NUMERALS

123

int x, y;y = 1776;x = -273;

They are numerical constants that identify integer decimal values. Literal constants, like variables, are considered to have a specific data type. By default, integer literals are of typeint. However, we can force them to either be unsigned by appending the u character to it, or long by appending l:12345678

int x;unsigned int y;long u;unsigned long v;x = 75;// inty = 75u;// unsigned intu = 75l;// longv = 75ul;// unsigned long

In both cases, the suffix can be specified using either upper or lowercase letters.

3.3.2. FLOATING POINT NUMBERS

They express numbers with decimals and/or exponents. They can include either a decimal point, an e character (that expresses "by ten at the Xth height", where X is an integer value that follows the e character), or both a decimal point and an e character:12345

double d;d = 3.14159;// 3.14159d = 6.02e23;// 6.02 x 10^23d = 1.6e-19;// 1.6 x 10^-19d = 3.0;// 3.0

These are four valid numbers with decimals expressed in C++. The first number is PI, the second one is the number of Avogadro, the third is the electric charge of an electron (an extremely small number) -all of them approximated- and the last one is the number three expressed as a floating-point numeric literal.

The default type for floating point literals is double. If you explicitly want to express a float or a longdoublenumerical literal, you can use the f or l suffixes respectively:1long double d;

CSC 1102 PROGRAMMING LANGUAGE 1 Page 25 of 137

American International University-BangladeshDepartment of Computer Science

234

float f d = 3.14159L // long doublef = 6.02e23f // float

Any of the letters that can be part of a floating-point numerical constant (e, f, l) can be written using either lower or uppercase letters without any difference in their meanings.

3.3.3. CHARACTER AND STRING LITERALS

There also exist non-numerical constants, like:12charch;ch = 'z';// char

The 2ndexpression represent single character constants. Notice that to represent a single character we enclose it between single quotes (').

When writing single character, it is necessary to put the quotation marks surrounding it to distinguish it from possible variable identifiers or reserved keywords. Notice the difference between these two expressions:123456

int x, y;char b;x = 5;y = x;b = 'x';b = '\t';

x alone would refer to a variable whose identifier is x, whereas 'x' (enclosed within single quotation marks) would refer to the character constant 'x'. The escape sequence '\t' (tab) is assigned to b as a character constant.

Additionally, the following four represent string literals composed of severalcharacters. To express a string (which generally consists of more than one character) we enclose it between double quotes ("). 1234

"Hello World""I Like C\n""Left \t Right""one\ntwo\nthree"

3.4. OPERATOR, OPERAND, OPERATION:

An operator is something which takes one or more values and does something useful with those values to produce a result. It operates on them. The terminology of operators is the following:

Operator: Which operates on something.

Operand: Each object which is operated upon by an operator.

Operation: The action which was carried out upon the operands by the operator.

There are lots of operators in C. Some of them may already be familiar: + - * / =.

Most operators can be thought of as belonging to one of three groups, divided up arbitrarily according to what they do with their operands. These rough groupings are thought of as follows:

CSC 1102 PROGRAMMING LANGUAGE 1 Page 26 of 137

American International University-BangladeshDepartment of Computer Science

Operators which produce new values from old ones. They make a result from their operands. e.g. +, the addition operator takes two numbers or two variables or a number and a variable and adds them together to give a new number.

Operators which make comparisons. e.g. less than, equal to, greater than... Operators which produce new variable types: like the cast operator.

The majority of operators fall into the first group. In fact the second group is a subset of the first, in which the result of the operation is a boolean value of either true of false.

3.4.1. ASSIGNMENT OPERATOR:

Operators would not be useful without a partner operator which could attach the values which they produce to variables. Perhaps the most important operator then is the assignment operator:

= (assignmentoperator)

For example: 1234

double x, y;x = 2.356;y = x;x = x + 2.0 + 3.0/5.0;

The assignment operator assigns a value to a variable. That is, the assignment operator takes the value of whatever is on the right hand side of the =symbol and puts it into the memory location of the variable on the left hand side. The assignment operator can be summarized in thefollowing way:lvalue= expression;

An expression is simply thename for any string of operators, variables and numbers. All of the following could be called expressions: 12345678

1 + 2 + 3a + somefunction()32 * x/3i % 4x1(22 + 4*(function() + 2))function () /* provided it returns a sensible value */

Lvalues on the other hand are simply names for memory locations: in other words variable names, or identifiers.

The most important rule when assigning is the right-to-left rule: The assignment operation always takes place from right to left, and never the other way: a = b;

This statement assigns to variable a (the lvalue) the value contained in variable b (the rvalue). The value that was stored until this moment in a is not considered at all in this operation, and in fact that value is lost.Consider also that we are only assigning the value of b to a at the moment of the assignment operation. Therefore a later change of b will not affect the new value of a.

CSC 1102 PROGRAMMING LANGUAGE 1 Page 27 of 137

American International University-BangladeshDepartment of Computer Science

3.4.2. ARITHMETIC OPERATORS:

The most common operators in any language are basic arithmetic operators. In C/C++ these are the following:

+ plus (unary)- minus (force value to be negative)+ addition- subtraction* multiplication/ floating point division/ integer division "div"% integer remainder "mod"

12345678910111213141516171819202122232425262728293031

// demonstrate the working of arithmetic operators#include <stdio.h>void main(void) {

int a=9,b=4,c;float d;c=a+b; printf("a+b=%d\n",c); c=a-b; printf("a-b=%d\n",c); c=a*b; printf("a*b=%d\n",c); printf("For integer division:\n");c=a/b; printf("a/b= %d(result), ",c); c=a%b; printf("%d(remainder)\n",c); printf("For floating division:\n");d=a/(float)b;/*As one of the operands must be of type float for floating point division, type casting any one of the operands, here b, to float.*/printf("a/b=%f\n",d);d=c+d;printf("c+d=%f\n",d);/*As d is float (larger size than int) the result is also in float*/c=c+d;printf("c+d=%d\n",c);/*The result of c+d(=4.25)is in float but as c is int on the left side of = the value after point (0.25) is ignored as c has no place to put that value*/

}a+b=13 a-b=5 a*b=36 For integer division:a/b=2(result), 1(remainder)For floating division:a/b=2.250000c+d=3.250000c+d=4

CSC 1102 PROGRAMMING LANGUAGE 1 Page 28 of 137

American International University-BangladeshDepartment of Computer Science

3.4.3. RELATIONAL OPERATORS:

In order to evaluate a comparison between two expressions we can use the relational and equality operators. The result of a relational operation is a Boolean value that can only be true or false, according to its Boolean result.

We may want to compare two expressions, for example, to know if they are equal or if one is greater than the other is. Here is a list of the relational and equality operators that can be used in C++:

== Equal to!= Not equal to> Greater than< Less than>= Greater than or equal to<= Less than or equal to

Here there are some examples:12345

(7 == 5) // evaluates to false.(5 > 4) // evaluates to true.(3 != 2) // evaluates to true.(6 >= 6) // evaluates to true.(5 < 5) // evaluates to false.

Of course, instead of using only numeric constants, we can use any valid expression, including variables. Supposethat a=2, b=3 and c=6,1234

(a == 5) // evaluates to false since a is not equal to 5.(a*b >= c) // evaluates to true since (2*3 >= 6) is true.(b+4 > a*c) // evaluates to false since (3+4 > 2*6) is false.((b=2) == a) // evaluates to true.

So the general format is:

(expression1) relational_operator (expression2)

Be careful! The operator = (one equal sign) is not the same as the operator == (two equal signs), the first one is an assignment operator (assigns the value at its right to the variable at its left) and the other one (==) is the equality operator that compares whether both expressions in the two sides of it are equal to each other. Thus, in the last expression ((b=2)==a), we first assigned the value 2 to b and then we compared it to a, that also stores the value 2, so the result of the operation is true.

3.4.4. PRECEDENCE OF OPERATORS

When writing complex expressions with several operands, we may have some doubts about which operand is evaluated first and which later. For example, in this expression: a = 5 + 7 % 2

we may doubt if it really means:12a = 5 + (7 % 2) // with a result of 6, ora = (5 + 7) % 2 // with a result of 0

CSC 1102 PROGRAMMING LANGUAGE 1 Page 29 of 137

American International University-BangladeshDepartment of Computer Science

The correct answer is the first of the two expressions, with a result of 6. There is an established order with the priority of each operator, and not only the arithmetic ones (those whose preference come from mathematics) but for all the operators which can appear in C++. From greatest to lowest priority, the priority order is as follows:

Level Operator Description Grouping

1 :: scope Left-to-right2 () [] . -> ++ -- postfix Left-to-right

3++ -- ~ ! sizeof new delete unary (prefix)

Right-to-left* & indirection and reference (pointers)+ - unary sign operator

4 (type) type casting Right-to-left5 .* ->* pointer-to-member Left-to-right6 * / % multiplicative Left-to-right7 + - additive Left-to-right8 <<>> shift Left-to-right9 <><= >= relational Left-to-right10 == != equality Left-to-right11 & bitwise AND Left-to-right12 ^ bitwise XOR Left-to-right13 | bitwise OR Left-to-right14 && logical AND Left-to-right15 || logical OR Left-to-right16 ?: conditional Right-to-left17 = *= /= %= += -= >>= <<= &= ^= |= assignment Right-to-left18 , comma Left-to-right

Grouping defines the precedence order in which operators are evaluated in the case that there are several operators of the same level in an expression.

All these precedence levels for operators can be manipulated or become more legible by removing possible ambiguities using parentheses signs ( and ), as in this example:a = 5 + 7 % 2; might be written either as: a = 5 + (7 % 2); or a = (5 + 7) % 2;

depending on the operation that we want to perform. Here are some examples –   3 * 4 / 2 + 3 -

1=12 / 2 + 3 - 1=6 + 3 - 1=9 - 1 = 8

6 + 2 * 3 - 4 / 2

= 6 + 6 - 4 / 2 =6 + 6 – 2=12 – 2 =10

20 / 3 + 5 % 2

=6 + 5 % 2 =6 + 1 =7

So if you want to write complicated expressions and you are not completely sure of the precedence levels, always include parentheses. It will also make your code easier to read. For example –   3 * 4 / 2 + (3 - 6 + 2 * (3 - 4 ) / 20 / (3 + 5 ) %

CSC 1102 PROGRAMMING LANGUAGE 1 Page 30 of 137

American International University-BangladeshDepartment of Computer Science

1 )= 3 * 4 / 2 + 2= 12 / 2 + 2= 6 + 2 = 8

2= 6 + 2 * -1 / 2= 6 + -2 / 2 = 6 + -1 = 5

2= 20 / 8 % 2= 2 % 2 = 0

LABORATORY

3.5. THE input/output libraryFUNCTION:

There are several input/output library functions depending on the data type, data format, and user/problem requirements. The most basic input/output library functionsareprintf() and scanf(). Both the functions belong to the header file stdio.h.

3.5.1. THE printf() OUTPUT FUNCTION:

The printf functions can take a variable number of parameters. In the case of printf the first parameter is always a string (c.f. "Hello World") but after that as many parameters of any type can be included. That is, the printf function is usually of the form:

printf(string,variable,variable,variable...)

where the ... means you can carry on writing a list of variables separated by commas as long as required. The string specifies the type of each variable in the list and how it will be printed. The string is usually called the control string or the format string.

The printf scans the string from left to right and prints on the screen, or any suitable output device, any characters it encounters - except when it reaches a % character. The % character is a signal that a value is to be printed next. The specifier %d means a signed decimal integer is to be printed next. So a specifierinstructs how the next variable in the list of variables should be printed. printf uses this information to convert and format the value that was passed to the function by the variable and then moves on to process the rest of the control string and anymore variables it might specify. For example: printf("Hello World");

only has a control string and, as this contains no % characters it results in Hello World being displayed and doesn't need to display any variable values. The specifier %d means convert the next value to a signed decimal integer and so: printf("Sum of %d + %d = %d", num1, num2, sum);

will print Sum of and then the value passed by variable num1 as a decimal integer. Next + will be printed and then the value passed by the variable num2. Finally, = will be printed followed by the value passed by variable sum as a decimal integer. So considering values of num1, num2, and sum to be 3, 5, and 8 respectively, the above printf will print –  sum of 3 + 5 = 8

The first % specifier will be associate with the first variable, second % specifier with second variable and so on.

CSC 1102 PROGRAMMING LANGUAGE 1 Page 31 of 137

American International University-BangladeshDepartment of Computer Science

The C view of output is at a lower level than one might expect. The %d isn't just a format specifier, it is a conversion specifier. It indicates the data type of the variable to be printed and how that data type should be converted to the characters that appear on the screen. That is %d says that the next value to be printed is a signed integer value (i.e. a value that would be stored in a standard int variable) and this should be converted into a sequence of characters (i.e. digits) representing the value in decimal.

1234567891011121314

/*declare-output an integer, a float, a character*/#include <stdio.h>void main(void) {int a;float b;char c; a = 5; b = 7.9; c = 'g';printf("Integer a = %d\n", a); printf("Float b = %f\n", b);printf("Character c = %c\n", c);}

Integer a = 5Float b = 7.900000Character c = g

3.5.2. THE scanf()INPUT FUNCTION:

The scanf function works in much the same way as the printf. That is it has the general form:scanf(control string,variable,variable,...)

In this case the control string specifies how strings of characters, usually typed on the keyboard, should be converted into values and stored in the listed variables.

The most obvious thing to understand here is that scanf will take an input value from input console and store that value in acomputer memory location that is associated with a variable in the parameter. This will also replace the old value with the new one. To do this the scanf function has to have the addresses(computer memory location) of the variables rather than just their values. This means that simple variables have to be passed with a preceding &. We have learn earlier that, &variable-name, represents or gives us the memory location of the value of that variable.  scanf("%d%d",&i,&j);

will read in two integer (as there are two %d) values from the keyboard and store these values in the memory locations given by &i and &j.

The scanf processes the control string from left to right and each time it reaches a specifier it tries to interpret what has been typed as a value. If multiple values are given as input then these are assumed to be separated by white-space - i.e. spaces, newline or tabs. This means the input can be typed:

3 4 5 or 345

CSC 1102 PROGRAMMING LANGUAGE 1 Page 32 of 137

American International University-BangladeshDepartment of Computer Science

and it doesn't matter how many spaces are included between items. For example: scanf("%d%d%d",&i,&j,&k);

will read in three integer (as there are two %d) values from the keyboard into i, jand k. The integer values can be typed on the same line or on different lines as long as there is at least one white-space character between them.The only exception to this rule is the %c specifier which always reads in the next character typed no matter what it is. Example:input and output an integer and a float

123456789

10111213

// program 1#include <stdio.h>void main( void ) {int a;float b; printf("Input an integer: ");// using & to get the address of variable a scanf("%d", &a); // input 5 printf("Input a float: "); scanf("%f", &b); // input 7.9 printf("You input integer %d and float %f", a, b); } Input an integer: 5Input a float: 7.9You input integer 5 and float 7.900000

123456789

10

// program 2#include <stdio.h>void main( void ) {int a;float b; printf("Input an integer followed by a float:\n"); scanf("%d%f", &a, &f); // input 5 and 7.9 separated by space/enter printf("You input integer %d and float %f", a, b); } Input an integer followed by a float:5 7.9You input integer 5 and float 7.900000

3.5.3. THE % FORMAT SPECIFIERS

The % specifiers that you can use in ANSI C are:

Specifier Usual variable type Display Others

%c char single character

%d int signed integer %ld – long

%f float signed format %lf – double

CSC 1102 PROGRAMMING LANGUAGE 1 Page 33 of 137

American International University-BangladeshDepartment of Computer Science

%p pointer address or location

%s array of char sequence of characters

%u unsigned int unsigned decimal

3.6. EXERCISES:

3.6.1. PROGRAM WRITING

3.6.1.1. A program that takes an alphabet inlower case & converts to capital & vise-versa.1234567891011

// Small to Capital#include <stdio.h>void main(void) {

char x, y;printf("Input an alphabet in small letter: ");scanf("%c", &x); // input dy = x – 32; // x+('A'-'a')='d'+('A'-'a')=100+(65-97)=100-32=68='D';//difference of the ASCII values of small and capital alphabet is 32. printf("%c in capital letter is %c.", x,y);

} Input an alphabet in small letter: dd in capital letter is D.

1234567891011

// Capital to Small#include <stdio.h>void main(void) {

char x, y;printf("Input an alphabet in capital letter: ");scanf("%c", &x); // input Dy = x + 32; // x+('a'-'A')='D'+('a'-'A')=68+(97-65)=68+32=100='d';//difference of the ASCII values of small and capital alphabet is 32.printf("%c in small letter is %c.", x,y);

} Input an alphabet in capital letter: DD in small letter is d.

3.6.1.2. Write a program that takes a character as input and outputs the ASCII value of that character. Also try the opposite.

12345678

// character to ASCII#include <stdio.h>void main(void) {char x = 'A';// using type casting to convert char to int printf("ASCII value of %c is %d", x,(int)x);}

ASCII value of A is 65

1234567

// ASCII to character#include <stdio.h>void main(void) {char x = 65;// using type casting to convert int to char printf("%d is ASCII value of %c",x,(char)x);

65 is ASCII value of A

CSC 1102 PROGRAMMING LANGUAGE 1 Page 34 of 137

American International University-BangladeshDepartment of Computer Science

8}

3.6.1.3. Write a program to interchange the value of two variables, say x and y. 12345678910

#include <stdio.h>void main(void) {// assigning value at declarationint x = 5, y = 10, t; printf("Before Swap, x=%d, y=%d\n", x, y); t = x; x = y; y = t; printf("After Swap, x=%d, y=%d\n", x, y);}

Before swap, x=5, y=10After swap, x=10, y=5

3.6.1.4. Write a program that takes two inputs from the user and adds, subtracts, multiplies anddivide it and also print the output.

3.6.1.5. Write a program that creates two integer variables and assigns value to them thendivide the first variable from the second variable and give output in float number.

3.6.1.6. Write a program that take two integer variable as input from the user. If variable a isgreater or equal to variable b output is 1 else output is 0.

3.6.1.7. Write a program that takes one integer variable as input from the user and checks if it iseven.

3.6.1.8. Write a program that calculates the equivalent resistance of the following circuit

CSC 1102 PROGRAMMING LANGUAGE 1 Page 35 of 137

American International University-BangladeshDepartment of Computer Science

Where R1=5 ohm, R2=3 ohm and R3=9 ohm.3.6.1.9. Write a program that calculates the CGPA of a student who is in 1st Semester

Course GradeElectric Circuit 1 3.75Math 1 4.0Physics 1 3.75English 1 3.5

3.6.1.10. Write a program that will ask for a resistance in kilo ohm and display the output in ohm.

3.6.1.11. Write a program that takes two voltage input voltage1=5V and voltage2=12V and print their average.

3.6.1.12. Write a program that takes length and breadth as input from the user and prints thearea of a rectangle as output.

3.6.1.13. Write a program that calculates the area of an equilateral triangle where the length ofone side a=5.

3.6.1.14. Write a program that calculates the equivalent resistance of the following circuit

Where R1=12 ohm, R2=3 ohm, R3=9 ohm and R4=16 ohm.3.6.1.15. Write a program that calculates the equivalent resistance of the following circuit

Where R1=5 ohm, R2=12 ohm and R3=8 ohm.3.1.1. OUTPUT TRACING

CSC 1102 PROGRAMMING LANGUAGE 1 Page 36 of 137

Hint: area=length*breadth

American International University-BangladeshDepartment of Computer Science

3.1.1.1. 1234567891011

#include <stdio.h>void main(void) {

int i=2, j=3, k, l;float a, b;k = i /j * j;l = j / i * i;a = i / (float)j * j + 2;b = j / i * i * 3;printf("%d %d \n%f %f", k,l,a,b);

}3.1.1.2. 1

23456789

#include <stdio.h>void main(void) {

int i = 22, j;j = i%10;i = i + j;j = i - (i % 5);printf("%d %d",i,j);

}3.1.1.3. 1

2345678

#include <stdio.h>void main(void) {

int c=5, l=6, m=7, q=8, r=9;float a=2.3, b=3.2, z;z = (8.8 * (a + b) + 2/c - 0.5+2*a/(q+r))/((a+b)*(l/m)+(a+b));printf("%f", z);

}3.1.1.4. A C program contains the following declarations and initial assignments:

123

int i= 8, j = 5;float x = 0.005, y = -0.01;char c = 'c' , d = 'd' ;

Determine the value of each of the following expressions, which involves the use of a library function. Identify the purpose of each expression.(a) abs(i-2*j) (b) floor(x) (c) log(exp(x)) (d) log(x)(e) fabs(x+y) (f) floor(x+y) (g) pow(x-y,

3.0)(h) sin(x-y)

(i) ceil(x) (j) exp(x) (k) fmod(x, Y) (l) ceil(x+y)(m)sqrt(x*x + y*y) (n) sqrt(sin(x) + cos(y))

3.1.1.5. A C program contains the following declarations and initial assignments:123

int i= 8, j = 5;float x = 0.005, y = -0.01;char c = 'c' , d = 'd' ;

Determine the value of each of the following expressions. Use the values initially assigned to the variables for each expression.

(a) -(i + j) (b) –j (c) j != 6 (d) c == 99(e) x >= 0 (f) x < y (g) i <= j (h) c > d(i) ! ( i <=

j )(j) ! ( c ==

99)(k) ! ( x > 0) (l) 2*x+y== 0

(m)5 * (i + j) > 'c' (n) ( 2 * x + y) == 0

CSC 1102 PROGRAMMING LANGUAGE 1 Page 37 of 137

American International University-BangladeshDepartment of Computer Science

(o) 2 * x + ( y == 0) (p) (i > 0) && ( j < 5)(q) (i>0) || (j<5) (r) (x > y)&&(i>0)||( j < 5)(s) (x>y)&&(i>0)&&(j<5) (t) (3*i-2*j)%(2*d-c)(u) 2*((i/5)+(4*(j-3))%(i+j-2)) (v) (i-3*j)%(c+2*d)/(x-y)

CSC 1102 PROGRAMMING LANGUAGE 1 Page 38 of 137

American International University-BangladeshDepartment of Computer Science

4. OPERATORS (II) &CONTROL STRUCTURE (I)4.1. OBJECTIVES:

To gain experience with – Logical, Bitwise, Increment, and Decrement Operators Compound Assignment Introduction to Control Structure if-else, switchstatement

Writing C programs using – Debugging tools Operators if-else andswitchstatement.

4.2. OPERATORS (II)

4.2.1. LOGICAL OPERATORS:

The Operator ! is the C/C++ operator to perform the Boolean operation NOT, it has only one operand, located at its right, and the only thing that it does is to inverse the value of it, producing false if its operand is true and true if its operand is false. Basically, it returns the opposite Boolean value of evaluating its operand. For example:12!(5==5) //is false, because the expression at its right (5==5) is true.!(6<=4) //is true, because (6 <= 4) would be false.

The logical operators && and || are used when evaluating two expressions to obtain a single relational result. The operator && corresponds with Boolean logical operation AND. This operation results true if both its two operands are true and false otherwise. The following panel shows the result of operator && evaluating the expression a&&b:

&& OPERATOR || OPERATORa b a && b a b a || b

true true true true true truetrue false false true false truefalse true false false true truefalse false false false false false

The operator || corresponds with Boolean logical operation OR. This operation results true if either one of its two operands is true, thus being false only when both operands are false themselves. Here are the possible results ofa || b:

For example:12( (5==5) && (3>6) ) // evaluates to false ( true&& false ).( (5==5) || (3>6) ) // evaluates to true ( true || false ).

When using the logical operators, C/C++ only evaluates what is necessary from left to right to come up with the combined relational result, ignoring the rest. Therefore, in this last example ((5==5)||(3>6)), C/C++ would evaluate first whether 5==5 is true, and if so, it would never check whether 3>6 is true or not. This is known as short-circuit evaluation, and works like this for these operators:

CSC 1102 PROGRAMMING LANGUAGE 1 Page 39 of 137

American International University-BangladeshDepartment of Computer Science

operator short-circuit

&& if the left-hand side expression is false, the combined result is false (right-hand side expression not evaluated).

|| if the left-hand side expression is true, the combined result is true (right-hand side expression not evaluated).

4.2.2. BITWISE OPERATORS:

Bitwise operators modify variables considering the bit patterns that represent the values they store.

Operator asm equivalent description& AND Bitwise AND| OR Bitwise Inclusive OR^ XOR Bitwise Exclusive OR~ NOT Unary complement (bit inversion)<< SHL Shift Left>> SHR Shift Right

4.2.3. COMPOUND ASSIGNMENT

Compound assignment operators (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=) modify the current value of a variable by performing an operation on it. They are equivalent to assigning the result of an operation to the first operand:

expression equivalent to...y += x; y = y + x;x -= 5; x = x - 5;x /= y; x = x / y;price *= units + 1;price = price * (units+1);

and the same for all other compound assignment operators. Compound assignment operators exist for all the binary operators (those thatrequire two operands). In general, statements like:var = var operator expression

can be rewritten asvar operator = expression

For example:123456789

// compound assignment operators#include <stdio.h>void main(void) {int a, b=3; a = b; a+=2; // equivalent to a=a+2printf("a = %d\n", a); }

a = 5

4.2.4. INCREMENT (++) AND DECREMENT (--) OPERATORS:

CSC 1102 PROGRAMMING LANGUAGE 1 Page 40 of 137

American International University-BangladeshDepartment of Computer Science

Some expression can be shortened even more: the increase operator (++) and the decrease operator (--) increases or reduces by one the value stored in a variable. They are equivalent to +=1 and to -=1, respectively. Thus:123

++x;x+=1;x=x+1;

are all equivalent in its functionality; the three of them increase by one the value of x.

This operator can be used both as a prefix and as a suffix. That means that it can be written either before the variable name (++x) or after it (x++). Although in simple expressions like x++ or ++x, both have exactly the same meaning. But using them in other expressions it may have an important difference in their meaning:

In the case that the increase operator is used as a prefix (++x) the value is increased first, then the expression evaluates with the new value of x.

In case that it is used as a suffix (x++) the expression evaluates with the current value of x, then the value stored in x increased.

Example 1 Example 2x = 3;y = ++x;// x contains 4, y contains 4

x = 3;y = x++;// x contains 4, y contains 3

In Example 1, the value assigned to y is the value of x after being increased. While in Example 2, it is the value xhad before being increased.

4.3. CONTROL STATEMENTS (I)

4.3.1. COMPOUND STATEMENT

A program is usually not limited to a linear sequence of instructions. During its process it may split, repeat code or take decisions. For that purpose, C++ provides control structures that serve to specify what has to be done by our program, when and under which circumstances.

With the introduction of control structures we are going to introduce a new concept: the compound-statement or block. A statement can be either a simple statement (a simple instruction ending with a semicolon) or a compound statement (several instructions grouped in a block). So acompound-statement is a group of statements which are separated by semicolons (;) like any statement, but grouped together in a block enclosed in braces: { }:

{ statement1; statement2; statement3; }

4.3.2. THE DECISION STRUCTURE: if-else

The if keyword is used to execute a statement or block only if a condition is fulfilled (true). Its form is:

if (condition) statement

where condition is thelogicalexpression that is being evaluated. If this condition is true, statement is executed. If it is false, statement is ignored (not executed) and the

CSC 1102 PROGRAMMING LANGUAGE 1 Page 41 of 137

American International University-BangladeshDepartment of Computer Science

program continues right after this conditional structure.For example, the following code fragment prints x is 100 only if the value stored in the x variable is indeed 100:

12if (x==100)

printf( "x is 100" );

If we want more than a single statement to be executed in case that the condition is true we can specify a block or compound statement using braces { }:

1234

if (x==100){printf( "x is 100" );printf( "\n" );

}

We can also specify what to happen if the condition is not fulfilled by using the keyword else. Its form used in conjunction with ifis:

if (condition) statement1 else statement2

For example:1234

if (x==100)printf("x is 100");

elseprintf("x is not 100");

prints on the screen x is 100 if indeed x has a value of 100, and prints out x is not 100only if not. One thing to notice here is, though if-else statements contains the keywords if and else, condition/expressions, statement1 (statements under if)andstatement2(statements under else)- the whole if-else block or structure (line 1-4) is one statement.

The if-else structures can be concatenated with the intention of verifying a range of values. The following example shows its use telling if the value currently stored in x is positive, negative or none of them (i.e. zero):123456

if (x>0)printf("x is positive");

elseif (x<0)printf("x is negative");

elseprintf("x is 0");

If you inspect carefully, this is still of the if-else form. Line 2 is the statement1 and the whole shaded part from lines 3 to 6 is statement2, which is again another if-else statement. In this way one can build as much long block of if-else as possible by writing if-else statements for each statement2 of each if-else statement. But at the end, the whole block together will act as one statement, because, based on the truth value of multiple conditions only one of the statements will be executed. Such block is known as if-elseladder.

123

// Find the letter grade of given mark#include <stdio.h>void main(void)

C+

CSC 1102 PROGRAMMING LANGUAGE 1 Page 42 of 137

American International University-BangladeshDepartment of Computer Science

456789101112131415

{float a=67.8;if(a>=90.0) printf("A+");elseif(a>=80.0) printf("A");elseif(a>=75.0) printf("B+");elseif(a>=70.0) printf("B");elseif(a>=65.0) printf("C+");elseif(a>=60.0) printf("C");elseif(a>=55.0) printf("D+");elseif(a>=50.0) printf("D");elseprintf("F");}

Same way, we can build as much long block of if/if-elseas possible by writing if/if-elsestatements for each statement1of each if/if-else statement. Consider the following statements which decide upon the value of some variable i.

123

if (i>2)if (i<4)printf("i is 3");

This is of the form if, as the shaded area from line 2-3 act as statement which is another if statement.

123456789101112131415

// Find the largest of given three numbers#include <stdio.h>void main(void) {int a=5, b=10, c=7;if(a>b)

if(a>c) // a > b, a > cprintf("a is largest");else// c > a > bprintf("c is largest");

elseif(b>c) // b > a, b > cprintf("b is largest");else// c > b > aprintf("c is largest");

}

b is largest

Every else must be in relationship with exactly one if. So every else relates to its immediate preceding if, who is not already in relationship with another else. Here, the else in line 11 looks for its preceding if and finds one in line7, but if in line 7 is already in relationship with else in line 9. So it goes for the next preceding if and finds one in line 6. As if in line 6 is still single, else in line 11 relates to it. Another thing to notice here is, lines 7-10 acts as statement1 and lines 11-14, after else in line 11, acts as statement2. This block (line 6-10) is known as nested if-else.

We can also use logical operators to combine different condition to act as one. Let’s rewrite the above code using logical operators.1234

// Find the largest of given three numbers#include <stdio.h>void main(void) {

b is largest

CSC 1102 PROGRAMMING LANGUAGE 1 Page 43 of 137

American International University-BangladeshDepartment of Computer Science

56789101112

int a=5, b=10, c=7;if(a>b&&a>c)printf("a is largest");elseif(b>a&&b>c)printf("b is largest");elseif(c>a&&c>b)printf("c is largest");}

Another example is to find if a given year is a leap year or not. A given year is leap year only if - it is divisible by 4 but not divisible by 100, if it is divisible by 100 then it must be divisible by 400.12345678910

// Find if the given year is leap year#include <stdio.h>void main(void) {int a=2012;if((a%4==0 && a%100!=0) || (a%4==0 && a%100==0 && a%400==0))printf("a=%d is leap year", a);else

printf("a=%d is NOT leap year", a);} 2012 is leap year

4.3.3. THE SELECTIVE STRUCTURE: switch

The objective of switch statement is to check several possible constant values for an expression. Its form/syntax is the following:switch (expression){case constant1: group of statements1;break;case constant2: group of statements2;break; ..// you can include as many case labels as values you want to check .default: default group of statements}

switch evaluates expression and checks with all thecase sequentially until it is equivalent to one of them. So first it checks with constant1. If it is equivalent to constant1, it executes group of statements1 until it finds the break statement. This break statement makes the program jump to the end of the switch selective structure.

If expression was not equal to constant1 it will be checked against constant2. If it is equal to this, it will execute group of statements2 until a break keyword is found, and then will jump to the end of the switch selective structure.

Both of the following code fragments have the same behavior:switch example if-else equivalent

CSC 1102 PROGRAMMING LANGUAGE 1 Page 44 of 137

American International University-BangladeshDepartment of Computer Science

switch(x){case 1:

printf( "x is 1");break;

case 2:printf( "x is 2");break;

default:printf( "value of x unknown");

}

if (x == 1){printf("x is 1");

}else if (x == 2){printf( "x is 2");

}else{printf("value of x unknown");

}

Finally, if the value of expression did not match any of the previously specified constants, the program will execute the statements included after the defaultlabel, if it exists (since it is optional).

The switch statement is a bit peculiar within the C++ language because it uses labels instead of blocks. This forces us to put break statements after the group of statements that we want to be executed for a specific condition. Otherwise the remainder statements -including those corresponding to other labels- will also be executed until the end of the switch selective block or a break statement is reached.

For example, if we did not include a break statement after the first group for case one, the program will not automatically jump to the end of the switch selective block and it would continue executing the rest of statements until it reaches either a break instruction or the end of the switch selective block. This makes it unnecessary to include braces {} surrounding the statements for each of the cases, and it can also be useful to execute the same block of instructions for different possible values for the expression being evaluated. For example:123456789

switch (x) {case 1:case 2:case 3:

printf("x is 1, 2 or 3");break;

default:printf("x is not 1, 2 nor 3");

}

Notice that switch can only be used to compare an expression against constants. Therefore we cannot put variables as labels (for example case n: where n is a variable) or ranges (case (1..3):) because they are not valid C++ constants.

4.4. LABORATORY EXERCISES:

4.4.1. DEBUGGING TOOLS:

[Please include notes/references regarding the debugging tools for the IDE being used]

4.4.2. PROGRAM WRITING

4.4.2.1. Any year is entered through the keyboard. Write a program to determine whether the year is a leap year or not (use nested if-else).

CSC 1102 PROGRAMMING LANGUAGE 1 Page 45 of 137

American International University-BangladeshDepartment of Computer Science

4.4.2.2. A program to find a given number is greater than 100 and less than 250 and divisible by 7.

4.4.2.3. Write a program to find a given number is even or odd.

4.4.2.4. Input a character. If the character is between ‘A’-‘Z’ convert to small letter. If the character is between ‘a’-‘z’ convert to capital letter.

4.4.2.5. Let consider the conversion rate of US Dollar and Taka are 1 dollar = 80.45 taka. Write a program that first takes the choice from the user what conversion (hint 1 for dollar to taka or 2 for taka to dollar) he/she wants. Then an amount is given as input. Convert the amount and output the result according to the given choice.

4.4.2.6. Consider the room numbers of our campus - 423, 432, 441, 234, 534, 132. Here first digit represent campus number, second digit represent floor number and the third number represent room number in that floor. Write a program that will take a three digit number (like 423) and output the Campus, Floor, and Room Number according to the input.

Sample example: INPUT: 423 OUTPUT: Campus 4, Floor 2, Room 3.

4.4.2.7. A C program contains the following declarations and initial assignments:

123

int i=8, j=5, k;float x=0.005, y=-0.01, z;chara, b, c='c' , d='d' ;

Determine the value of each of the following expressions. Use the values initially assigned to the variables for each expression.

(a) k = i+j++ (b) a=b=d (c) i %= j (d) z = x+ ++y(e) y -= x (f) i /= j (g) k=c (h) i+= (j-2)(i) k=z=x (j) z=k=x (k) i= j (l) k = (x+y) (m)x *= 2 (n) i +=2 (o) z=i/j (p) i= j = 1.1(q) 5 * (++i + j) > 'c' (r) ( 2 * x++ + y) == 0(s) 2 * x + ( ++y >= 0) (t) (i--> 0) && ( --j < 5)(u) (i-- > 0) || (--j<5) (v) (--x > y++)&&(i>0)||(j < 5)(w)(x-- > ++y)&&(i>0)&&(j<5) (x) (3*i – 2* --j)%(2*d – c++)(y) ((--i/5)+(4*(j++-3)))%(i+j-

2)(z) (--i-3*j)%(c+2*--d)/(x-y)

CSC 1102 PROGRAMMING LANGUAGE 1 Page 46 of 137

American International University-BangladeshDepartment of Computer Science

4.4.2.8. Write a program that asks the user to give input salary. If salary is greater than 10000TK than the program outputs CONGRATULATION.

4.4.2.9. Write a program that takes length and breadth as input from the user and prints the area of a rectangle as output. If the area is greater than 200 square meters the program outputs THE AREA IS VERY LARGE else the program outputs THE AREA IS JUST RIGHT.

4.4.2.10.Write a program that calculates the CGPA of a student who is in 1st Semester.

Course GradeElectric Circuit 1 3.75Math 1 4.0Physics 1 3.75English 1 3.5

If CGPA is 3.75 to 4.00 the program outputs GOOD

If CGPA is 3.5 to 3.74 the program outputs SATISFACTORY

If CGPA is 3.0 to 3.49 the program outputs NEED TO IMPROVE

If CGPA is less than or equal to 2.99 then program outputs POOR

Hint: use else if clause to do this program.

4.4.2.11.Write a program that calculates the voltage of the given circuit. The value of R and I have to be taken input from the user. If voltage is greater or equal to 10v then the program will output DECREASE THE VOLTAGE. Hint: use if statement to do this program

4.4.2.12.Write a program that calculates the equivalent resistance of the following circuit. Input is taken from the user.

CSC 1102 PROGRAMMING LANGUAGE 1 Page 47 of 137

Hint: area=length*breadth

V=IR

American International University-BangladeshDepartment of Computer Science

Where R1=? Ohm, R2=? Ohm and R3=? Ohm.If the equivalent resistance R is greater than 40 ohm the program outputs GOOD else the program outputs BAD. Hint: use if else statement to do this program.

4.4.2.13.Write a program that calculates the equivalent resistance R of the following circuit

Where R1=12 ohm, R2=3 ohm, R3=9 ohm and R4=16 ohm.If V=.1 volt calculate the current flow, I for R. If I is less than or equal to 1 print I IS LESS THAN OR EQUAL TO 1If I is less than or equal to 2 print I IS LESS THAN OR EQUAL TO 2If I is less than or equal to 3 print I IS LESS THAN OR EQUAL TO 3If I is less than or equal to 4 print I IS LESS THAN OR EQUAL TO 4If I is less than or equal to 5 print I IS LESS THAN OR EQUAL TO 5If I is greater than 5 print “I IS GREATER THAN 5”

Hint: use else if clause to do this program.

4.4.2.14.

CSC 1102 PROGRAMMING LANGUAGE 1 Page 48 of 137

American International University-BangladeshDepartment of Computer Science

4.4.3. OUTPUT TRACING

4.4.3.1. 123456789101112

#include <stdio.h>void main(void) {

int i, j;i = 0; j = 0;if( (i+1) || j){ j=i=i+1; printf("%d . . .%d\n", i, j); j=(i+12)%5;}printf("%d . . .%d", i, j);

}4.4.3.2. 1

234567891011121314

#include <stdio.h>void main(void) {

int i, j, x; i=2; j=3; x=1; x = x + (i + j -1);if(x % 2 != 0){ i=x+j; printf("\nx = %d\ni = %d\nj = %d\n", x, i, j); }else{ j=x+i; printf("\nx = %d\ni = %d\nj = %d\n", x, i, j);

} }

4.4.3.3. 12345678910

#include <stdio.h>void main(void) {inti, j, k, x;i=3; j=2; k=10; x=0;k = k+j/i-1;if(k%2==0) x=x+k;else if(k%3==0)x=x+k%2;printf("%d", x);}

4.4.3.4. 12345678910111213141516

#include <stdio.h>void main(void) {

floatn;scanf("%f", &n); // consider n=78.5, 85.2, 46.9, or 95.0if(n>=94.0) printf("A+");else if(n>=90.0) printf("A");else if(n>=86.0) printf("A-");else if(n>=82.0) printf("B+");else if(n>=78.0) printf("B");else if(n>=74.0) printf("B-");else if(n>=70.0) printf("C+");else if(n>=66.0) printf("C");else if(n>=62.0) printf("C-");else if(n>=58.0) printf("D+");else if(n>=54.0) printf("D");

CSC 1102 PROGRAMMING LANGUAGE 1 Page 49 of 137

American International University-BangladeshDepartment of Computer Science

171819

else if(n>=50.0) printf("D-");else printf("F");

}4.4.3.5. 1

23456789101112

#include <stdio.h>void main(void) {

int i, j;i = 10; j = 0;if( i-- && ++j){ j *= ((i++)%5); printf("i=%d\nj=%d\n", i, j); i = (i+(++j))%5;}printf("i=%d\nj=%d\n", i, j);

}4.4.3.6. 1

234567891011121314

#include <stdio.h>void main(void) {

char ch='F';int i=83;switch(ch) {case 65 : i++; break;case 68 : ++i;

case 70 : i++;case 73 : ++i; break;

default : i++;}printf"%c", (char)i);

}

CSC 1102 PROGRAMMING LANGUAGE 1 Page 50 of 137

American International University-BangladeshDepartment of Computer Science

5. CONTROL STRUCTURE (II)5.1. OBJECTIVES:

To gain experience with – whilestatement do-whilestatement for statement break and continue statement

Writing C programs using – Debugging tools while,do-while, and for statement.

5.2. ITERATION STRUCTURES: LOOPS

Loops are used by the programmers to repeat a statement a certain number of times or untilsome condition is fulfilled.

5.2.1. THE while LOOP

Its format is:

while (expression) statementand its functionality is simply to repeat statement while the condition set in expression is true.For example, we are going to make a program to countdown using a while-loop:

12345678910111213

// custom countdown using while#include <stdio.h>void main (void){int n;printf("Enter the starting number > ");scanf("%d",&n);while (n > 0) {printf("%d, ", n); n = n - 1; }printf("FIRE!\n");}

Enter the starting number > 88, 7, 6, 5, 4, 3, 2, 1, FIRE!

When the program starts the user is prompted to insert a starting number for the countdown. Then the while loop begins, if the value entered by the user fulfills the condition n>0 (that n is greater than zero) the block that follows the condition will be executed and repeated while the condition (n>0) remains being true.

The whole process of the previous program can be interpreted according to the following script (beginning in main):

1. User assigns a value to n2. The while condition is checked (n>0). At this point there are two possibilities:

*condition is true: statement block is executed (line9-10). End of block (line 11). return automatically to line 8 and repeat.

CSC 1102 PROGRAMMING LANGUAGE 1 Page 51 of 137

American International University-BangladeshDepartment of Computer Science

* condition is false: ignore statement controlled by while (line 9-11) and continue with the next statement after while (line12).

3. End of main (step 13). end of program.

When creating a while-loop, we must always consider that it has to end at some point, therefore we must provide within the block some method to force the condition to become false at some point, otherwise the loop will continue looping forever. In this case we have included statement n=n-1; that decreases the value of the variable by one - this will eventually make the condition (n>0) to become false after a certain number of loop iterations: to be more specific, when n becomes 0, that is where our while-loop and our countdown ends.

5.2.2. THE do-while LOOP

Its format is:

do statement while (expression)Its functionality is exactly the same as the while loop, except that condition in the do-while loop is evaluated after the execution of statement instead of before, granting at least one execution of statement even if condition is never fulfilled. For example, the following example program echoes any number you enter until you enter 0.

1234567891011

// number echoer#include <stdio.h>void main (void){unsignedlongn;do {printf("Enter number (0 to end): ");scanf("%d",&n);printf("You entered: %d\n", n); } while (n != 0);}

Enter number (0 to end): 12345You entered: 12345Enter number (0 to end): 160277You entered: 160277Enter number (0 to end): 0You entered: 0

The do-while loop is usually used when the condition that has to determine the end of the loop is determinedwithin the loop statement itself, like in the previous case, where the user input within the block is what is used to determine if the loop has to end. In fact if you never enter the value 0 in the previous example you can be prompted for more numbers forever.

5.2.3. THE for LOOP

Its format is:for (initialization;condition; update)statement

and its main job is to repeat statement while condition remains true, like the while loop. But in addition, thefor loop provides specific locations to contain aninitialization statement and an update statement. So this loop is specially designed to perform a repetitive action with a counter which is initialized and updatedon each iteration.

It works in the following way:

CSC 1102 PROGRAMMING LANGUAGE 1 Page 52 of 137

;{

statements}

);for(initialization condition update

Step 1 Step 2

Step 3Step 4

Step 5

American International University-BangladeshDepartment of Computer Science

Step 1

Step 2

Step 3

Step 4

// execution flow of for loopinitialization is executed. Generally it is an initial value setting for a counter variable. This is executed only once.condition is checked. If it is true the loop continues, otherwise the loop ends and statement is skipped (not executed) and goes to the next statement after loop.statement is executed. As usual, it can be either a single statement or a block enclosed in braces { }.whatever is specified in the update field is executed and the loop gets back to step 2.

Here is an example of countdown using a for loop:

12345678910

// countdown using a for loop#include <stdio.h>void main (void){int n;for (n=10; n>0; n--) {printf("%d, ",n); }printf("FIRE!\n");}

10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!

The initialization, update, and condition fields might be empty. But in all cases the semicolon signs between them must be written. For example, we could write: for(;n<10;) if we wanted to specify no initialization and no update; or for(;n<10;n++) if we wanted to include an update field but no initialization; or for(;;) if we want an infinite loop.

Optionally, using the comma operator (,) we can specify more than one expression in any of the fields included in afor loop, like in initialization, for example. The comma operator (,) is an expression separator, it serves to separate more than one expression where only one is generally expected. For example, suppose that we wanted to initialize more than one variable in our loop:1234

for ( n=0, i=100; n!=i ; n++, i-- ){// statements}

This loop will execute for 50 times if neither n or i are modified within the loop statements. n starts with a value of 0, and i with 100, the condition is n!=i (that n is not equal to i). Because n is increased by one and i decreased by one, the loop's condition will become false after the 50th loop, when both n and i will be equal to 50.

CSC 1102 PROGRAMMING LANGUAGE 1 Page 53 of 137

American International University-BangladeshDepartment of Computer Science

5.3. JUMPSTATEMENTS

Jump statements allow altering the flow of a program by performing jumps to specific locations.

5.3.1.breakSTATEMENTS

The break statement is used to terminate loops or to exit from a switch. It can be used within a for, while, do-while, or switch statement. The break statement is written simply as break; without any embedded expressions or statements. We have already seen several examples of the use of the break statement within a switch statement. When breakencounters inside a loop, it leaves the scope of the loop it resides, even if the condition for the end of loop is not fulfilled.The break statement causes a transfer of control out of the loop it resides, to the first statement following the loop statement.It can be used to end an infinite loop, or to force it to end before its natural end.The break statement is generally associated/controlled with an if statement.

123456789101112131415

// break loop example#include <stdio.h>void main (void){

/*Loop terminating conditionn>0*/for (int n=10; n>0; n--){printf("%d, ",n);if (n==3){/*break condition n==3*/printf("countdown aborted!\n");break; } }

/*first statement after loop*/printf("countdown aborted at %d.", n);

}10, 9, 8, 7, 6, 5, 4, 3, countdown aborted!countdown aborted at 3.

5.3.2.continueSTATEMENTS

When acontinue statement is encountered, a loop will stop whatever it is doing and will go straight to the start of the next iteration.continue forces the next iteration of the loop to take place, skipping any code in between. In case of while&do-while loop, the control goes to the loop terminating condition for next iteration. In case of for loop, the control first goes to the update part, then to the loop termination condition part and proceed from there for the next iteration.

CSC 1102 PROGRAMMING LANGUAGE 1 Page 54 of 137

American International University-BangladeshDepartment of Computer Science

123456789101112131415

// continue loop example#include <stdio.h>void main (void){

/*Loop terminating conditionn<10*/for (int n=-10; n<10; n++){

if (n==0){/*continue condition n==0*/printf("devide by zero.\n");continue;

}printf("%f, ",20.0/n);

}/*first statement after loop*/printf("\nexited at %d.", n);

}10, 9, 8, 7, 6, 5, 4, 3, countdown aborted!countdown aborted at 3.

5.4. LABORATORY EXERCISES:

5.4.1. DEBUGGING TOOLS:

[Please include notes/references regarding the debugging tools for the IDE being used]

5.4.2. LOOP CONVERSION

5.4.2.1. 123456789101112

#include <stdio.h>void main(void){

int i=0, x=0;while (i < 20){

if (i%5 == 0) {x += i;printf("%d ", x);

}++i;

}printf("\nx = %d", x);

}

#include <stdio.h>void main(void){

int i=0, x=0;do{

if (i%5 == 0) {x += i;printf("%d ", x);

}++i;

}while (i < 20);printf("\nx = %d", x);

}5.4.2.2. 1

2345678910

#include <stdio.h>void main(void){

inti, x;for(i=1,x=0; i<10; i*=2) {

x++;printf("%d",x);

} printf("\nx = %d", x);

}

#include <stdio.h>void main(void){

inti=1, x=0;while(i<10){

x++;printf("%d",x);i*=2;

} printf("\nx = %d", x);

}

5.4.3. PROGRAM WRITING

5.4.3.1. Write a program that receives 5 integers and output the sum and average of these numbers.

5.4.3.2. Write a program to calculate the factorial value of any integer entered through the keyboard.

CSC 1102 PROGRAMMING LANGUAGE 1 Page 55 of 137

American International University-BangladeshDepartment of Computer Science

5.4.3.3. Write a program to read the age of n persons and count the number of persons who are not in the age group 50-60.

5.4.3.4. Write a program which will calculate the value of nth position of this following series.1 + 3 + 9 + 27 + 81+................

5.4.3.5. Write a program segment that reads and sums data values until a negative value is read. Use a while loop for your solution.

5.4.3.6. A positive integer is entered through the keyboard. Write a program to obtain the prime factors of this number.For example, prime factors of 24 are 2, 2, 2 and 3, whereas prime factors of 35 are 5 and 7.

5.4.3.7. A positive integer is entered through the keyboard. Write a function to determine whether the input number is a perfect number or not. A perfect number is one whose sum of factors is equal to the number, like 6. 6 has 3 factors 1,2,3 when we add 1+2+3 it is equal to 6; hence 6 is perfect number. Likewise 28 is another perfect number.

5.4.3.8. Ten numbers are entered from the keyboard into an array. Write a program to find out how many of them are even and how many are odd.

5.4.3.9. A positive integer is entered through the keyboard. Write a program to calculate sum of all the digits of the number.

5.4.3.10. Write a program to obtain the first 25 numbers of a Fibonacci sequence. In a Fibonacci sequence the sum of two successive terms gives the third term. Following are the first few terms of the Fibonacci sequence:1 1 2 3 5 8 13 21 34 55 89 …

5.4.3.11.Below there are three Electrical series circuits. Write a program that calculates their equivalent resistance taking input from the user. Hint: Use FOR LOOP

5.4.3.12.Below there is an electric circuit. The amount of current passing through the circuit is I=2A.Write a program that prints the word CORRECT until the value of I becomes less than or equal to 10. Hint: Use WHILE LOOP

CSC 1102 PROGRAMMING LANGUAGE 1 Page 56 of 137

I=2A

American International University-BangladeshDepartment of Computer Science

5.4.3.13.Below there is an electric circuit. The amount of voltage passing through the circuit is V=3V.Write a program that prints the word CORRECT until the value of V becomes less than or equal to 20. Hint: Use DO WHILE LOOP

5.4.3.14. Generate the following “pyramid” of digits, using nested loops.

1232

345434567654

56789876567890109876

7890123210987890123454321098

901234567654321090123456789876543210

Do not simply write out 10 multi digit strings. Instead, develop a formula to generate the appropriate output for each line.

CSC 1102 PROGRAMMING LANGUAGE 1 Page 57 of 137

V=3V

American International University-BangladeshDepartment of Computer Science

5.4.4. OUTPUT TRACING

5.4.4.1. 123456789

#include <stdio.h>void main(void){

int num, sum = 0; while(1){ scanf("%d", &num); // let num = 4, 2, 7, 1, 6, 8

sum += num;if(sum % 5 ==0)break; }

}5.4.4.2. 1

23456789101112

#include <stdio.h>void main(void){

int i, j, x = 0;for(i=0; i<5; ++i)

for(j=0; j<i; ++j) {x += (i + j -1);if (x % 2 == 0)continue;printf("%d ", x);break;

}printf("\nx = %d", x);

}5.4.4.3. 1

23456789

#include <stdio.h>void main(void){

int j=50;while(j!=0){

j=j/2;if(j%5==0)continue;printf("Help !! SOS\n");

}}

5.4.4.4. 123456789

#include <stdio.h>void main(void){

int a=6,s=1;while(a!=0){

printf("s=%d, a=%d\n", s, a);s=s*a;a--;

}printf("s=%d, a=%d\n", s, a);

}5.4.4.5. 1

234567891011121314

#include <stdio.h>void main(void){

int i,j, k, x = 0; for (i=0;i<5; ++i)

for (j=0; j<i; ++j){ switch (i + j - 1) { case -1: case 0: x += 1; break; case 1:case 2: case 3: x += 2; break; default : x += 3; }

printf("%d ", x);

CSC 1102 PROGRAMMING LANGUAGE 1 Page 58 of 137

American International University-BangladeshDepartment of Computer Science

151617

}printf ("\nx = %d", x) ;

}5.4.4.6. 1

23456789

#include <stdio.h>void main(void){

inti = 0, x = 0;for(i=1; i<10; i*=2) {

x++;printf("%d",x);

} printf("\nx = %d", x);

}5.4.4.7. 1

23456789

#include <stdio.h>void main(void){

inti = 0, x = 0;for(i=1; i<10; i*=2) {

x++;printf("%d",x);

} printf("\nx = %d", x);

}5.4.4.8. 1

2345678

#include <stdio.h>void main(void){

int i = 0;for( ; i<16; i++){

if(i%5 ==0) continue;printf("%d",i);

} }

5.4.4.9. 123456789101112131415

#include <stdio.h>void main(void){int i=0, j, k, x=0;do{

for(j=0; j<i; j++) {k = (i+j-1);if(k%2==0) x+=k;elseif(k%3==0) x+=k%2;printf("%d ", x);

} i++; }while(i<5); }

5.4.4.10. 1234567891011

#include <stdio.h>void main(void){

int i, n = 5;for( ; ; ){

if(n = =1)break;

printf("%d\t",n);if(n%2==1)

n = 3*n+1;else

CSC 1102 PROGRAMMING LANGUAGE 1 Page 59 of 137

American International University-BangladeshDepartment of Computer Science

121314

n = n / 2;}

}5.4.4.11. 1

23456789101112131415

#include <stdio.h>void main(void){int i, j, n=24;for(i=2; i<=n; i++ ){for(j=2; j<i; j++) if(i%j==0) break;if(j==i){while(n%i==0){printf("%d ", i);

n /= i;}

}}

}

CSC 1102 PROGRAMMING LANGUAGE 1 Page 60 of 137

American International University-BangladeshDepartment of Computer Science

6. DATA STRUCTURE (II)

6.1. OBJECTIVES:

To gain experience with – Introduction to Array. Array declaration, name, size, and index. Memory management and access into array elements. The 2-dimensional array

Writing C programs using – Accessing, manipulating, input, and output of array. Sorting, searching, adding, and deleting element in array. Simple problem using 2-dimensional array.

6.2. ARRAY

An array can hold a series of elements of the same type placed in contiguous memory locations. Each of these elements can be individually referenced by using an index to a unique identifier. In other words, arrays are a convenient way of grouping a lot of values of same type under a single variable name. Arrays are like pigeon holes or chessboards, with each compartment or square acting as a storage place; they can be one dimensional, two dimensional or more dimensional.

Arrays are most useful when they have a large number of elements: that is, in cases where it would be completely impractical to have a different name for every storage space in the memory. It is then highly beneficial to move over to arrays for storing information for two reasons:

The storage spaces in arrays have indices. These numbers can often be related to variables in a problem and so there is a logical connection to be made between an array and a program.

In C, arrays can be initialized very easily indeed. It is far easier to initialize an array than it is to initialize twenty or so variables.

That means that, for example, we can store 5 values of type int in an array without having to declare 5 different variables, each one with a different identifier. Instead of that, using an array we can store 5 different values of the same typewith a unique identifier.For example, an array to contain 5 integer values of type int called mimo could be represented like this:

0 1 2 3 4mimo

|---int---|

where each blank panel represents an element of the array, that in this case are integer values of type int with size 4 bytes. These elements are numbered from 0 to 4 since in arrays the first index is always 0, independently of its length.

6.2.1. DECLARATION:

CSC 1102 PROGRAMMING LANGUAGE 1 Page 61 of 137

American International University-BangladeshDepartment of Computer Science

Like a regular variable, an array must be declared before it is used. A typical declaration for an array in C++ is:

  type name [total number of elements];

where type is a valid type(like int, float …), name is a valid identifier and the elements field (which is always enclosed in square brackets []), specifies how many of these elements the array can contain.

Therefore, in order to declare an array called mimo as the one shown in the above diagram it is as simple as:  intmimo [5];

The elements field within brackets [] which represents the number of elements the array is going to hold, must be a constant integer value, since arrays are blocks of non-dynamic memory whose size must be determined before execution.

6.2.2. INITIALIZATION:

When declaring a regular array of local scope (within a function, for example) its elements will not be initialized to any value by default, so their content will be undetermined until we store some value in them. The elements of global and static arrays are automatically initialized with their default values, zeros.

When we declare an array, we have the possibility to assign initial values to each one of its elements by enclosing the values in braces { }. For example:

  intmimo [5] = { 16, 2, 77, 40, 12071 };

This declaration would have created an array like this:0 1 2 3 4

mimo 16 2 77 40 12071

The amount of values between braces { } must not be larger than the number of elements that we declare for the array between square brackets [ ].

When an initialization of values is provided for an array, C++ allows the possibility of leaving the square brackets empty [ ]. In this case, the compiler will assume a size for the array that matches the number of values included between braces { }:

  intmimo [] = { 16, 2, 77, 40, 12071 };

After this declaration, array mimo would be 5 ints long, since we have provided 5 initialization values.

6.2.3. ACCESS

The number in the square brackets [ ]of the array is referred to as the `index' (plural: indices) or `subscript' of the array and it must be an integer number 0 to one less than the declared number of elements. We can access the value of any of its elements individually as if it was a normal variable, thus being able to both read and modify its value. The format is as simple as:

CSC 1102 PROGRAMMING LANGUAGE 1 Page 62 of 137

American International University-BangladeshDepartment of Computer Science

name[index]

For the declaration intmimo[5]; the five elements in mimo is referred in the program by writing:

mimo[0] mimo[1] mimo[2] mimo[3] mimo[4]

Each of the above array elements is an integer and each of them also acts as an integer variable. That is, whatever we can do with an integer variable we can do the same with these array elements using same set of rules. The array name is used to refer to each element as following:

mimo[0] mimo[1] mimo[2] mimo[3] mimo[4]mimo

Following is some demonstration of the access of the array mimo.

12345678910111213141516

int mimo[5], a, b, i;// declaration of a new arraymimo[2] = 75; // store 75 in the third element of mimoa = mimo[2];// copy/assign a with the third value of mimoscanf("%d",&mimo[2]);// read a value for the third element of mimo// read 5 values for the five elements of mimo sequentiallyfor(i=0; i<5; i++)

scanf("%d",&mimo[i]);// print 5 values for the five elements of mimo sequentiallyfor(i=0; i<5; i++)

printf("%d\n",mimo[i]);// some more interesting accessesa = 4;mimo[2] = a;mimo[a] = 3;b = mimo[a-2] + 2;mimo[mimo[a]] = mimo[2] + b;

6.2.4. SOME FACTS:

Arrays have a natural partner in programs: the for loop. The for loop provides a simple way of counting through the numbers of an index in a controlled way. The for loop can be used to work on an array sequentially at any time during a program.

It is important to be able to clearly distinguish between the two uses that brackets [ ] have related to arrays. They perform two different tasks: one is to specify the size of arrays when they are declared; and the second one is to specify indices for concrete array elements. Do not confuse these two possible uses of brackets [ ] with arrays.

Consider the following example: char array[5];array[7] = '*';

The assignment of array[7]is clearly wrong as index 7 or element 8 in array[5] does not exists. But, C/C++ would happily try to write the character * at the index 7.

CSC 1102 PROGRAMMING LANGUAGE 1 Page 63 of 137

American International University-BangladeshDepartment of Computer Science

Unfortunately this would probably be memory taken up by some other variable or perhaps even by the operating system. The result would be either:

The value in the incorrect memory location would be corrupted with unpredictable consequences.

The value would corrupt the memory and crash the program completely! On Unix systems this leads to a memory segmentation fault.

The second of these tends to be the result on operating systems with proper memory protection. Writing over the bounds of an array is a common source of error. Remember that the array limits run from zero to the size of the array minus one.

6.3. TWO-DIMENSION ARRAY

Two-dimensional arrays can be described as "arrays of arrays". For example, a Two-dimensional array can be imagined as a Two-dimensional table made of elements, all of them of a same uniform data type.

minu{0 1 2 3 4

012

minu represents a Two-dimensional array of 3 per 5 elements of type int. The way to declare this array in C++ would be: int minu [3][5];

and, for example, the way to reference the second element vertically and fourth horizontally in an expression would be:

 minu [1][3]

minu{0 1 2 3 4

0 minu[0][0] minu[0][1] minu[0][2] minu[0][3] minu[0][4]1 minu[1][0] minu[1][1] minu[1][2] minu[1][3] minu[1][4]2 minu[2][0] minu[2][1] minu[2][2] minu[2][3] minu[2][4]

Generally, for two-dimensional array, 1st dimension is considered as row and the 2nd

dimension is considered as column. Here, we have 3 rows and 5 columns.

Two-dimensional arrays are just an abstraction for programmers, since we can obtain the same results with a simple array just by putting a factor between its indices:12int minu [3][5]; // is equivalent toint minu [15]; // (3 * 5 = 15)

With the only difference that with Two-dimensional arrays the compiler remembers the depth of each imaginary dimension for us. Take as example these two pieces of code, with both exactly the same result. One uses a Two-dimensional array and the other one uses a simple array: 

CSC 1102 PROGRAMMING LANGUAGE 1 Page 64 of 137

American International University-BangladeshDepartment of Computer Science

Code 1 Code 2#define WIDTH 5#define HEIGHT 3int minu [HEIGHT][WIDTH];int n,m;void main (void){for (n=0;n<HEIGHT;n++)for (m=0;m<WIDTH;m++) { minu [n][m]=(n+1)*(m+1); }}

#define WIDTH 5#define HEIGHT 3int minu [HEIGHT * WIDTH];int n,m;void main (void){for (n=0;n<HEIGHT;n++)for (m=0;m<WIDTH;m++) { minu [n*WIDTH+m]=(n+1)*(m+1); }}

Code 1 stores value in the following way:

minu{0 1 2 3 4

0 1 2 3 4 51 2 4 6 8 102 3 6 9 12 15

Code 2 stores value in the following way:0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

minu 1 2 3 4 5 2 4 6 8 10 3 6 9 12 15

But, as memory is flat, in both codes the values are actually stored sequentially in the memory (just like the Code 2). The access for the two-dimensional array in that case is just as the indexing of the array in Code 2. That is,

 [(row index) * (Total # of column) + (column index)]

Assigning values at the time of declaring a two-dimensional array can be any one of the following ways: int minu[3][5] = {1,2,3,4,5,2,4,6,8,10,3,6,9,12,15};int minu[3][5] = {{1,2,3,4,5},{2,4,6,8,10},{3,6,9,12,15}};int minu[3][5] = {

{1,2,3,4,5}, {2,4,6,8,10}, {3,6,9,12,15} };

The internal braces are unnecessary, but helps to distinguish the rows from the columns.Take care to include the semicolon at the end of the curly brace which closes the assignment.Note that, if there are not enough elements in the curly braces to account for every single element in an array, theremaining elements will be filled out with garbage/zeros. Static and global variables are always guaranteed to be initialized to zeroanyway, whereas auto or local variables are guaranteed to be garbage.

6.4. LABORATORY EXERCISES:

6.4.1. SORTING & SEARCHING

CSC 1102 PROGRAMMING LANGUAGE 1 Page 65 of 137

American International University-BangladeshDepartment of Computer Science

Given n numbers.Write a program to find a given number q from the list of n numbers. If found at position i output "FOUND in item 5" (considering i=5) else "NOT FOUND". Then ask the user if he wants to find another number. Continue to find the next given number q until user quits.

123456789101112131415161718192021222324252627282930313233

void main(void){

int n, q, next, i; intlist[100]; /* read a value for n */ printf ("\nHow many numbers will be listed? ") ; scanf ("%d",&n) ; printf ("\n") ; /* read the numbers and store them in array list[] */ for (i=0; i<n; ++i) {

printf ("item %d = ", i + 1); scanf ( "%d", &list[i] ) ;

}/* searching first element */next = 1; do{

printf ("\nWrite number to be searched? "); scanf ("%d",&q) ;/* searching through the elements from item 1 to n */for (i=0; i<n; ++i)

if(list[i] == q){printf ("FOUND in item %d.\n", i+1);/* no more searching needed, get out of the loop */break;

}/* not found; i stops at n */if(i == n) printf ( "NOT FOUND.\n", &list[i] );/* going for the next search */printf("type 1 to find another\n");printf("type 0 to quit\n? ");scanf("%d",&next);

}while( next );}

Given n numbers.Write a program to sort the numbers in ascending order.

123456789101112131415

void main(void){

int n, i, j, tempVal; intlist[100]; /* read a value for n */ printf ("\nHow many numbers will be listed? ") ; scanf ("%d",&n) ; printf ("\n") ; /* read the numbers and store them in array list[] */ for (i=0; i<n; ++i) {

printf ("item %d = ", i + 1); scanf ( "%d", &list[i] ) ;

}/* sorting elementin ascending order *//* find the smallest value for index i */

CSC 1102 PROGRAMMING LANGUAGE 1 Page 66 of 137

American International University-BangladeshDepartment of Computer Science

1617181920212223242526272829

for (i=0; i<n-1; ++i)/* compare with rest of the element in index j*/for (j=i+1; j<n; ++j)

if(list[i] > list[j]){/* interchange if value at index j is small */tempVal = list[i];list[i] = list[j];list[j] = tempVal;

}/* print the sorted list */printf("\nThe sorted list:\n\n");for (i=0; i<n; ++i)

printf ("item %d =%d\n", i+1, list[i]); }

Let n=9 and list[] = {3, 5, -3, 2, 7, -2, 8, 6, 4};

i j Comparing list[i] > list[j] Swapping if true0 1 2 3 4 5 6 7 8 0 1 2 3 4 5 6 7 8

0 1 3 5 -3 2 7 -2 8 6 42 3 5 -3 2 7 -2 8 6 4 -3 5 3 2 7 -2 8 6 43 -3 5 3 2 7 -2 8 6 44 -3 5 3 2 7 -2 8 6 45 -3 5 3 2 7 -2 8 6 46 -3 5 3 2 7 -2 8 6 47 -3 5 3 2 7 -2 8 6 48 -3 5 3 2 7 -2 8 6 49

1 2 -3 5 3 2 7 -2 8 6 4 -3 3 5 2 7 -2 8 6 43 -3 3 5 2 7 -2 8 6 4 -3 2 5 3 7 -2 8 6 44 -3 2 5 3 7 -2 8 6 45 -3 2 5 3 7 -2 8 6 4 -3 -2 5 3 7 2 8 6 46 -3 -2 5 3 7 2 8 6 47 -3 -2 5 3 7 2 8 6 48 -3 -2 5 3 7 2 8 6 49

2 3 -3 -2 5 3 7 2 8 6 4 -3 -2 3 5 7 2 8 6 44 -3 -2 3 5 7 2 8 6 45 -3 -2 3 5 7 2 8 6 4 -3 -2 2 5 7 3 8 6 46 -3 -2 2 5 7 3 8 6 47 -3 -2 2 5 7 3 8 6 48 -3 -2 2 5 7 3 8 6 49

3 4 -3 -2 2 5 7 3 8 6 45 -3 -2 2 5 7 3 8 6 4 -3 -2 2 3 7 5 8 6 46 -3 -2 2 3 7 5 8 6 47 -3 -2 2 3 7 5 8 6 48 -3 -2 2 3 7 5 8 6 4

CSC 1102 PROGRAMMING LANGUAGE 1 Page 67 of 137

American International University-BangladeshDepartment of Computer Science

94 5 -3 -2 2 3 7 5 8 6 4 -3 -2 2 3 5 7 8 6 4

6 -3 -2 2 3 5 7 8 6 47 -3 -2 2 3 5 7 8 6 48 -3 -2 2 3 5 7 8 6 4 -3 -2 2 3 4 7 8 6 59

5 6 -3 -2 2 3 4 7 8 6 57 -3 -2 2 3 4 7 8 6 5 -3 -2 2 3 4 6 8 7 58 -3 -2 2 3 4 6 8 7 5 -3 -2 2 3 4 5 8 7 69

6 7 -3 -2 2 3 4 5 8 7 6 -3 -2 2 3 4 5 7 8 68 -3 -2 2 3 4 5 7 8 6 -3 -2 2 3 4 5 6 8 79

7 8 -3 -2 2 3 4 5 6 8 7 -3 -2 2 3 4 5 6 7 89

8

6.4.2. PROGRAM WRITING

6.4.2.1. Calculate the average of n numbers, then compute the deviation of each number about the average.

123456789101112131415161718192021222324

void main(void){

int n, count; float avg, d, sum = 0; float list[100]; /* read a value for n */ printf ("\nHow many numbers will be averaged? ") ; scanf ("%d",&n) ; printf ("\n") ; /* read the numbers and calculate their sum */ for (count = 0; count < n; ++count) {

printf ("item = %d x = ", count + 1); scanf ( "%f", &list [count] ) ; sum += list[count];

}/* calculate and display the average */ avg = sum / n; printf("\nThe average is %f\n\n", avg); /* calculate and display the deviations about the average */ for (count = 0; count < n; ++count) {

d = list[count] - avg; printf("i = %d x = %f d = %f\n", count+1, list[count], d);

}}

6.4.2.2. Suppose we are given a table of integers, A, having m rows and n columns, and a list of integers, X,havingn elements. We wish to generate a new list of integers, Y, that is formed by carrying out the following operations. Y[1] = A[l][l]*X[l] + A[l][2]*X[2] + . . . + A[l][n]*X[n] Y[2] = A[2][1]*X[l] + A[2][2]*X[2] + . . . + A[2][n]*X[n] .....

CSC 1102 PROGRAMMING LANGUAGE 1 Page 68 of 137

American International University-BangladeshDepartment of Computer Science

Y[m] = A[m][1]*X[l] + A[m][2]*X[2] + . . . + A[m][n]*X[n]Display the input data (i.e., the values of the elements A and X), followed by the values of the elements of Y.

6.4.2.3. Suppose A is a table of floating-point numbers having k rows and m columns, and B is a table of floating- point numbers having m rows and n columns. We wish to generate a new table, C having k rows and n columns, where each element of C is determined by

C[i][j]=A[i][1]*B[1][j]+A[i][2]*B[2][j]+...+ A[i][m]*B[m][j]

wherei = 1, 2, ...,k and j = 1, 2, ...,n. (This operation is known as matrix multiplication.)Display the elements of A, B and C. Be sure that everything is clearly labeled.

6.4.2.4. Write a program that takes 3 quiz marks of n (n<=40) number of students according to their roll number (1…n). Generate the sum of best two quiz marks for all students. Output the student roll number along with their best two marks in descending order of their marks.

6.4.2.5. Below there is an Array of positive and negative number. Write a program that calculates how many of the numbers are positive and how many of them are negative. Hint: Use ONE DIMENSIONAL ARRAY. A [ ] = {10, -2, 9. -4, -6, -7, 12, 14, 19, -20}

6.4.2.6. Below there are two matrices A and B. Write a program that adds them. Hint: Use TWO DIMENSIONAL ARRAY.

6.4.2.7. Let us consider a laboratory has 10 resistors with the following values R1=12, R2=10, R3=9, R4=3, R5=1, R6=3, R7=8, R8=13, R9=17 AND R10=11. Write a program that gives notification to the user how many of these resistors have odd values and how many of the resistors have even values. Hint: Use ONE DIMENSIONAL ARRAY

6.4.2.8. Let us consider two 3*2 matrices A and B. Write a program that multiplies them after taking input for matrices A and B from the user. Hint: Use TWO DIMENSIONAL ARRAY

CSC 1102 PROGRAMMING LANGUAGE 1 Page 69 of 137

American International University-BangladeshDepartment of Computer Science

6.4.2.9. Write a function named UpperRight, which will display the upper right triangle elements of a matrix. Declare the matrix as a global variable. Declare the number of rows and columns using #define. Also declare the prototype of the UpperRight Function. Write a main function which will take the elements of the matrix from the user and call the UpperRight

function

6.4.3. OUTPUT TRACING

6.4.3.1. 12345678910

void main(void){

int a[5]={5,2,15,30,20};int b[5]={10,4,12,42,20};int i,j,k=1,m;i=a[1]++;j= b[3]--;m=a[i++]++;printf("\n%d %d %d", i,j,m);

}6.4.3.2. 1

234567891011121314

void main(void){

int a[3][3] = { 3, 6, 9, 2, 5, 8, 1, 4, 7 };int b[3][3] = { 5, 9, 10, 5, 4, 7, 2, 8, 1 };int i,j,s;for( i = 0; i < 3; i++) {

for( j = 0, s = 0; j < 3; j++){print("%d %d\n",a[j][i],b[i][j]);s = s + a[j][i]+ b[i][j];

}printf("\n %d", s);

}6.4.3.3. 1

2345678

void main(void){

int i,j; int a[3]={15,2,12};int b[3]={10,4,12};for(i=0;i<3;i++)

printf("%d \n", a[i] + b[i]);}

6.4.3.4. 1234

void main(void){

int a[2][3]={15,3,10,12,4,8}; int i,j;

CSC 1102 PROGRAMMING LANGUAGE 1 Page 70 of 137

Sample Input: Sample Output:

123456789

12356 9

American International University-BangladeshDepartment of Computer Science

5678

for(i=0;i<3;i++)for(j=0;j<2;j++)

printf("%d", a[j*j][j]);}

6.4.3.5. 12345678

void main(void){

int i,j,s=1; int a[3][2]={15,2,12,32,12,1};for(i=0,j=0;i<3;i++)

s=s+a[i][j];printf("%d \n", s);

}6.4.3.6. 1

23456789

void main(void){

int j,sum=0;static int c[8]= {1,2,3,4,5,6,7,8};for(j=0;j<8;j++)

if(c[j]%3==0)sum+=c[j];

printf("%d",sum);}

6.4.3.7. 123456789

void main(void){

for(i=0;i<10;i++)a[i]=i+1;

for(i=0;i<10;i++)if(i%2==0)

sum+=a[i];printf("%d",sum);

}6.4.3.8. 1

23456789101112131415

void main(void){

int a[3][4], b[4][3], i, j, k=3;for(i=0;i<3;i++)

for(j=0;j<4;j++)a[i][j] = ++k;

for(i=0;i<4;i++)for(j=0;j<3;j++)

b[i][j]=a[j][i];for(i=0;i<4;i++){

for(j=0;j<3;j++)printf("%d ",b[i][j]);

printf("\n");}

}7. FUNCTION (I)7.1. OBJECTIVES:

To gain experience with – Introduction to Function. Function name, parameter, return. Flow of Function execution The scope of variables

Writing C programs using –

CSC 1102 PROGRAMMING LANGUAGE 1 Page 71 of 137

American International University-BangladeshDepartment of Computer Science

Functions

7.2. INTRODUCTION TO FUNCTIONS

Functions break large computing tasks into smaller ones, encapsulate some computation, and enable people to reuse without worrying about its implementation, and to build on what is already done instead of starting over from scratch. Appropriate functions hide details of operation from parts of the program that don't need to know about them, thus clarifying the whole, and easing the pain of making changes. 7.3. DECLARATION & DEFINITION

Each function declaration/ function prototype has the form return-typefname(type1 argument1, type2 argument2,…, typen argumentn);

Parameter names are optional in a function prototype, so for the prototype we could have written

For example:intpower(int,int); insteadof intpower(intbase,intn);

If the function definition comes before its use in other functions, then function declaration is not required.Each function definition has the form

return-typefname(type1 argument1, type2 argument2,…, typen argumentn) {

declarations and statements }

fname is just an identifier by which it will be possible to call the function. Generally, Function declaration/definition takes a space in the memory under the fname just like the variable declaration. Difference is, the space taken during variable declaration can store a value of its declared type and the space taken during function declaration can store an address/location of the memory where the function definition is located.

argument declarations are also known as parameters which are used to carry data values from the caller function into thecalled function. Parameters (as much as needed) are listed and declared in between the () brackets in the function's definition - (type1 argument1, type2 argument2,…,typen argumentn). Each variable must be declared separately.

The returnstatement is the mechanism for returning a value from the called function to its caller. Any expression can follow return:

As the function's name is used to return the value in the caller function, it has to be given a return-type. This is achieved by writing the data type in front of the function's name.

7.4. FLOW OF FUNCTION EXECUTION

CSC 1102 PROGRAMMING LANGUAGE 1 Page 72 of 137

returnexpression;

int Sum(int a,int b)

z = Sum( 2, 3);

int Sum(int a,int b)5z = Sum( 2, 3);

American International University-BangladeshDepartment of Computer Science

Here is a function example: 1234567891011121314

// function example#include <stdio.h>int Sum (int a, int b){int r; r=a+b;return (r);}void main (void){int z; z = Sum (5,3); printf("The result is %d", z);}

The result is 8

Asthe function sum is declared/defined globally, a space in the memory is first created to keep the address/location of the actual function-definition in the memory. Then the main function begins by declaring the variable z of type int. Next line is an assignment statement z = Sum (2,3);. To assign a value to the variable za function Sum is called with parameters 2and 3. At this point the control is lost by main and passed to functionSum. The value of both arguments passed in the call (2and 3) are copied/assigned to the parameter variables inta and int b respectively within the function.

Function Sum declares a local variable (int r), and by means of the expression r=a+b, it assigns5 to rthe result of a plus b. The parameters a and b are alsolocal variables just as the variable r declared inside the function. The only way in which parameters are any different is that they are given initial values/expressions by the caller function (main in this case) by assigning the values to each parameter variables.The next line of code:return (r);,finalizes function Sum, and returns the control back to the function main that called it in the first place. Thereturned value of the variable r becomes the value 5of evaluating the function callsum(2,3) in main.At this moment the program follows its regular course from the same point at which it was interrupted by the call to Sum. So the variable z will be set to the value returned by sum(2,3), that is 5. To explain it another way, you can imagine that the call to a function (sum(2,3)) is literally replaced by the value it returns (5).

The next line of code in mainproduces the printing of the result on the screen.

7.5. MORE ON FUNCTION CALLS

sum(x,y);

CSC 1102 PROGRAMMING LANGUAGE 1 Page 73 of 137

American International University-BangladeshDepartment of Computer Science

will assign a to the value stored in x and b to the value stored in y.sum(x+2,z*10);

which will set a equal to whatever x+2 works out to be and b equal to whatever z*10 works out to be.A function can be used anywhere that a variable can be used. For example,r=sum(1,2)*3; r=3+sum(1,2)/n-10;

And here is another example about functions: 1234567891011121314151617181920

// function example#include <stdio.h>int subtraction (int a, int b){int r; r=a-b;return (r);}void main (void){int x=5, y=3, z; z = subtraction (7,2);printf("The first result is %d\n", z);printf("The second result is ");printf("%d\n", subtraction(7,2) );printf("The third result is ");printf("%d\n", subtraction(x,y)); z= 4 + subtraction (x,y);printf("The fourth result is %d\n", z);}

The first result is 5The second result is 5The third result is 2The fourth result is 6

7.6. MORE ON RETURN

A return, wherever it occurs inside the function, always terminates the function and returns control back to the callingfunction.The void statement is used as returned type to represent – nothing will be returned. Furthermore, there need to be no expression after return; in that case, no value is returned to the caller, only the control of the program returns to the caller. If the return type is omitted, intis assumed. The expressionwill be converted to the return type of the function if necessary. Parentheses are often used around the expression, but they are optional. The calling function is free to ignore the returned value. 7.7. SCOPE OF VARIABLES

The functions can occur in any order in the source file. Communication between the functions is by argument list,returnedvalue, and through external/global variables. Global variables are defined outside of any function, are globally accessible, and thus potentially available to many functions. If a large number of variables must be shared among functions, global variables are more convenient and efficient than long argument lists. Global variables are also useful because of their greater scope and

CSC 1102 PROGRAMMING LANGUAGE 1 Page 74 of 137

American International University-BangladeshDepartment of Computer Science

lifetime. Automatic/local variables are internal to a function; they come into existence when the function is entered, and disappear/destroyed when it is left. Global variables, on the other hand, are permanent, so they can retain values from one function invocation to the next. Thus if two functions must share some data, yet neither calls the other, it is often most convenient if the shared data is kept in global variables rather than being passed in and out via arguments. Here is a program that uses a function Sum_Averageto take five integers and calculates and sends the sum and average of the numbers to the caller function main.12345678910111213141516171819

// Scope of variable example#include <stdio.h>float avg;int Sum_Average(int a,int b,int c,int d,int e){int s; s=a+b+c+d+e; a = b = c = d = e = 0; avg = s/5.0;return (s);}void main (void){int s, a=5, b=3, c=7, d=9, e=2; s = Sum_Average (a,b,c,d,e); printf("a=%d\nb=%d\nc=%d\nd=%d\ne=%d",a,b,c,d,e); printf("\nThe Sum is %d\n", s); printf("The Average is %.2f\n", avg);}

a=5b=3c=7d=9e=2The Sum is 26The Average is 5.20

Now let us see the flow of execution.After initializing the header files, the program starts by creating the (global) floating point variable avg (line 3).

avg

Then the control goes to function main where six integer (local) variable s, a, b, c, d, e is created (line 14) with a, b, c, d, e assigned to the values 5, 3, 7, 9, 2 respectively.

avg

main s a b c d e&main 5 3 7 9 2

With the function call in line 15 the control goes to Sum_Average where five integer variables a, b, c, d, e are created in the parameter and assigned to the values passed from the function main. Here one thing must be cleared that, the variables a, b, c, d, e in the parameter are newly created at the

CSC 1102 PROGRAMMING LANGUAGE 1 Page 75 of 137

American International University-BangladeshDepartment of Computer Science

time of entering into the function Sum_Average and only the values of the variables a, b, c, d, e of main is passed/assigned to these newly created parameter variables respectively.

avg

main s a b c d e&main 5 3 7 9 2

Sum_Average a b c d e&Sum_Averag

e 5 3 7 9 2

Once the control is transferred to the Sum_Average, all the local variables in main- s, a, b, c, d, e are inaccessible. But the global variable avg is still accessible.

avg

main s a b c d e&main 5 3 7 9 2

inaccessibleSum_Average a b c d e&Sum_Averag

e 5 3 7 9 2

Now another variable s is created in line six. Line 7, assigns the summation of the five values to s. line 8, and assigns all the five variables a, b, c, d, e to zero. Line 9, assigns the average to the global variable avg.

avg5.20main s a b c d e&main 5 3 7 9 2

inaccessibleSum_Average s a b c d e&Sum_Averag

e 26 0 0 0 0 0

And finally the control is given back to the caller function main (line 15) by returning the summation value s. At the exit of the function, all the variables (s, a, b, c, d, e) created inside function Sum_Average is destroyed. Once the control is in main, all the local variables are again accessible, and in line 15s is assigned to the return value from Sum_Average.

avg5.20main s a b c d e&main 26 5 3 7 9 2

accessible

Sum_Average s a b c d e

CSC 1102 PROGRAMMING LANGUAGE 1 Page 76 of 137

American International University-BangladeshDepartment of Computer Science

&Sum_Average 26 0 0 0 0 0

DestroyedThen the consecutive lines prints the values of the variables s, a, b, c, d, e, avg. Though, we have changed the values of the variables a, b, c, d, ein function Sum_Average to zero, nothing changes for the variables a, b, c, d, ein function main, as they are in different scope. But global variable avg, whose value has been changed/assigned in Sum_Average remains unchanged as it was not destroyed (as its scope is global) at the exit of the function. At the exit of the function main, all the local variables s, a, b, c, d, e are destroyed. At the exit of the program the global variable avg is destroyed. One thing to remember here is, each time Sum_Average is called the variables s, a, b, c, d, e is created afresh and destroyed upon exit from the function.

7.8. LABORATORY EXERCISES:

7.8.1. PROGRAM WRITING

7.8.1.1. Write a function that receives 5 integers and returns the sum and average of these numbers. Call this function from main() and print the results in main().

7.8.1.2. Write 4 different functions for calculating the area of a triangle, rectangle, square and circle.

7.8.1.3. A positive integer is entered through the keyboard. Write a function to determine whether the input number is a perfect number or not.

7.8.1.4. A positive integer is entered through the keyboard. Write a function to obtain the prime factors of this number. For example, prime factors of 24 are 2, 2, 2 and 3, whereas prime factors of 35 are 5 and 7.

7.8.1.5. Write a function to calculate the factorial value of any integer entered through the keyboard.

7.8.1.6. Any year is entered through the keyboard. Write a function to determine whether the year is a leap year or not.

7.8.1.7. Give declaration for a function called DigitCount( ), which takes a integer and returns the number of digit found in the given integer.

7.8.1.8. Write necessary functions for number conversion, e.g., decimal to binary, binary to decimal, binary to hexadecimal, decimal to octal, octal to hexadecimal and so on.

7.8.1.9. A 5-digit positive integer is entered through the keyboard. Write a function to calculate sum of digits of the 5-digit number.

7.8.1.10. Write a function to find the factorial of a given integer.

7.8.1.11. Write a function to obtain the first 25 numbers of a Fibonacci sequence. In a Fibonacci sequence the sum of two successive terms gives the third term. Following are the first few terms of the Fibonacci sequence:

1 1 2 3 5 8 13 21 34 55 89 …

CSC 1102 PROGRAMMING LANGUAGE 1 Page 77 of 137

American International University-BangladeshDepartment of Computer Science

7.8.1.12 .Write a program that can add, subtract, multiply and divide two integer numbers. Hint: Use the concept of functions

7.8.1.13 .Write a program that can add, subtract, multiply and divide three integer numbers. Send the third number as parameter from the main function to the other functions. Hint: Use the concept of functions, parameters and scope rule of functions

7.8.1.14 .Write a program that can add, subtract, multiply and divide two float numbers. Hint: Use the concept of function declaration and prototypes

7.8.1.15 .Write a program that takes input from the user the no of subjects, mark and credit of each subject and calculates CGPA. Hint: Use the concept of functions

Subject Mark CreditSubject 1Subject 2Subject 3……………Subject n

7.8.1.16. There are three resistors in a circuit. Resistor 1 has value 4 ohm. Resistor 2 has value 8 ohm and Resistor 3 has value 1 ohm. Write a program that stores the values of the resistors in the main function but have to print the values from a separate function. Hint: Use the concept of functions, parameters and scope rule of functions

7.8.1.17. Write a program that calculates the equivalent resistance of the following circuit where R1=5.5 ohm, R2=3.7 ohm and R3=9.8 ohm. Hint: Use the concept of functions declaration and prototypes

CSC 1102 PROGRAMMING LANGUAGE 1 Page 78 of 137

American International University-BangladeshDepartment of Computer Science

9. FUNCTION (II)9.1. OBJECTIVES:

To gain experience with – The scope of variables Call By Value & Reference Passing Array into the function and Constant variable Recursion

Writing C programs using –

Functions Call By Value & Reference Recursion

9.2. CALL BY VALUE

We already know that in C/C++ it is only possible to pass one value using one parameter to a function.This means that when calling a function with parameters, what we have passed to the function were copies of their values but never the variables themselves. This is known as call by value. All the examples we have seen so far uses call by value as parameter.

9.3. CALL BY REFERENCE

There might be cases where we need to manipulate the value of an external variable (ex. Variable of another function which is inaccessible to the current function) from inside a function. For that purpose we can use arguments passed by reference. 1234567891011121314151617

18 19

// Call by reference example#include <stdio.h>int Sum_Average(int a,int b,int c, int d,int e,float& v ){int s; s=a+b+c+d+e; a = b = c = d = e = 0; v = s/5.0;return (s);}void main (void){int s, a=5, b=3, c=7, d=9, e=2;float avg; s = Sum_Average (a,b,c,d,e, avg); printf("a=%d\nb=%d\nc=%d\nd=%d\ne=%d\n", a, b, c, d, e); printf("The Sum is %d\n", s); printf("The Average is %.2f\n", avg);}a=5b=3c=7d=9e=2The Sum is 26The Average is 5.20

CSC 1102 PROGRAMMING LANGUAGE 1 Page 79 of 137

American International University-BangladeshDepartment of Computer Science

We are using the same example of Sum_Average with variable avg declared inside main. And it is sent as a parameter to the function Sum_Average. The parameter float &v in the function Sum_Average takes the reference that is the address/location, of the variable avg of main. We have already seen while using scanf that &variable_name represents the address/location of the variable in the memory.

main s a b c d e avg&main 5 3 7 9 2

Sum_Average a b c d e &v&Sum_Averag

e 5 3 7 9 2 &avg

Once the control is transferred to the Sum_Average, all the local variables in main- s, a, b, c, d, e, and avg are inaccessible. Though the variable avg cannot be accessed directly, still it is accessible via the reference variable &v as it contains the location of avg. So any change we make to variable v in Sum_Average will change the value at the location pointed to by vthat is the variable avg in main.

main s a b c d e avg&main 5 3 7 9 2

inaccessible

Sum_Average a b c d e&v

&Sum_Average 5 3 7 9 2 &avg

Now, same way as before, another variable s is created in line 5. Line 6, assigns the summation of the five values to s. And line 7, assigns all the five variables a, b, c, d, e to zero. Line 8, assigns the average to the location provided/pointed by the reference variable &v. That is variable avg in main is assigned to the calculated average value in Sum_Average.

main s a b c d e avg&main 5 3 7 9 2 5.20

inaccessible

Sum_Average a b c d e &v&Sum_Averag

e 26 5 3 7 9 2 &avg

And finally the control is given back to the caller function main (line 15) by returning the summation value s. At the exit of the function, all the variables (s, a, b, c, d, e, &v) created inside function Sum_Average is destroyed. So, the space provided for &v is destroyed, but the variable avg in main has no effect. It still holds the value changed by &v. Once the control is in main, all the local variables are again accessible, and in line

CSC 1102 PROGRAMMING LANGUAGE 1 Page 80 of 137

American International University-BangladeshDepartment of Computer Science

15 s is assigned to the return value from Sum_Average. Rest follows as before.

main s a b c d e avg&main 26 5 3 7 9 2 5.20

accessible

Sum_Average s a b c d e &v&Sum_Averag

e 26 5 3 7 9 2 &avg

destroyed

9.4. ARRAY AS PARAMETER

It is not possible to pass a complete block of memory by value as a parameter to a function.But we are allowed to pass its reference to its address as one value. In order to accept arrays as parameters the only thing that we have to do when declaring the function is to specify in its parameters the element type of the array, an identifier and a pair of void brackets []. For example, the following function:

Here is a complete example: 

123456789

1011121314151617181920212223

// arrays as parameters#include <stdio.h>void TwiceArray (int arg[], int length) {for (int n=0; n<length; n++) arg[n] *= 2;}void PrintArray (const int arg[], int length) {for (int n=0; n<length; n++) printf("%d ", arg[n]); printf("\n");}

void main (void){int FirstArray[3] = {5, 10, 15};int SecondArray[] = {2, 4, 6, 8, 10}; TwiceArray (FirstArray,3); PrintArray (FirstArray,3); PrintArray (SecondArray,5);}

10 20 302 4 6 8 10

Let’s look at the working flow of the program. First we have global declaration and definition of the functions TwiceArray and PrintArray. Both these identifiers will hold the starting address/location of, where their definition is located in the memory. Then we start with the function main where two arrays, FirstArray with 3 elements and SecondArray with 5 elements, are declared and created. Both these identifiers will hold the starting address/location of their elements. That is, FirstArray holds the location of

CSC 1102 PROGRAMMING LANGUAGE 1 Page 81 of 137

American International University-BangladeshDepartment of Computer Science

the first element, &FirstArray[0]and SecondArray holds the location of the first element, &SecondArray[0].

TwiceArray&TwiceArray[

0]PrintArray&PrintArray

FirstArray SecondArraymain int FirstArray[3] int SecondArray[5]&main 5 10 15 2 4 6 8 10

Then, the TwiceArray is called with the parameters FirstArray and 3. As the identifier FirstArray represents the starting location of the array itself, the location of the first element (&FirstArray[0]) is passed to the parameter int arg[] of the function TwiceArray. So now, the identifier arg holds the starting address (&FirstArray[0]) of the FirstArray of the function main. As arg itself is an array, arg behaves like an array. That means, if we use arg[2], this will access 3rd element from the starting address of the array arg - which is actually the address of the FirstArray[2] of main. The control is transferred from function main to functionTwiceArray.

TwiceArray arglengt

h n

&TwiceArray &FirstArray[0] 3

PrintArray &PrintArray

FirstArray SecondArraymain int FirstArray[3] int SecondArray[5]&main 5 10 15 2 4 6 8 10

Inside function TwiceArray another variable n is declared. Using n as the index 0..2the 3 (length=3) elements of arg are made twice of their original value through the for statement. As arg represents the array FirstArray on main, the 3 elements of the FirstArray are actually made twice. Hypothetically, FirstArray[n] arg[n] *= 2. So, after the for loop is executed –

TwiceArray arglengt

h n&TwiceArray FirstArray 3 3PrintArray Value being accessed &&PrintArray Changed by arg

FirstArray SecondArraymain int FirstArray[3] int SecondArray[5]&main 10 20 30 2 4 6 8 10

CSC 1102 PROGRAMMING LANGUAGE 1 Page 82 of 137

American International University-BangladeshDepartment of Computer Science

Before exiting from the function TwiceArray, all the variables (arg, length, n) are destroyed and the control is returned to the main. Now, if we access FirstArray[1], we will have the value 20, not 10. The value changed inside the function TwiceArray remains. Next we are calling the function PrintArray to print the elements of the FirstArray and SecondArray consecutively. Here, it works as same in terms of parameter passing. But there is one difference, the parameter arg in PrintArray is declared as constant variable. The value of a variable declared as constant can be used anywhere in the scope, but the value cannot be changed. That’s why; a constant variable is always assigned value at the time of declaration. After that any change attempt would result in compilation error.

As we do not need to change any elements of the array inside PrintArray, the parameter arg is declared as constant variable. So inside PrintArray we have access to the FirstArray but we do not have the permission to change any value. This is how any function (main in this example) can protect its data array (FirstArray) from being changed by another function (PrintArray). Following is an example for Constant variable.

1234567891011121314

//constant example#include <stdio.h>void main( void ){

int i, minu[15]; const int n=10;for(i=0; i<n; i++)

printf("%d\n ",minu[i]);/* any following attempts would result in errorn++;n=i;printf("%d\n ",n);*/

}

Once an array is passed through the parameter from the caller function to the called function, the actual address of the array is passed. Though the array in the caller function is out of scope inside the called function, because of the passing of the address, whatever changes are made to the array inside the called function will change the array in the caller function. The only way to stop the changes to take effect in the caller function is to declare the parameter array as constant variable.

Once a function finishes it destroys all its variable locally declared before exiting. So if we come back to the function again in the same program execution, all the variables are created again. Whatever was stored in different variables in previous function call cannot be retained in the current call.

9.5. RECURSIVE FUNCTIONS

C/C++ functions may be used recursively; that is, a function may call itself either directly or indirectly. The following program prints all the digits of n in separate lines using recursive function.

CSC 1102 PROGRAMMING LANGUAGE 1 Page 83 of 137

American International University-BangladeshDepartment of Computer Science

12345678910

#include <stdio.h>void PrintDigit(int n) {

if (n / 10)PrintDigit(n / 10); printf("%d\n", n % 10);

} void main (void){ PrintDigit( 123 );}

123

When a function calls itself recursively, each invocation gets a fresh set of all the automatic variables, independent of the previous set. Thus in PrintDigit(123)the first PrintDigitreceives the argument n = 123. It passes 12to a second PrintDigit, which in turn passes 1to a third. The third-level PrintDigitprints 1 and goes to the next line, then returns to the second level.That PrintDigitprints 2 and goes to the next line, then returns to the first level. That one prints3and goes to the next line.Then it terminates and goes back to main.

1 2 3main&main 123

PrintDigit n&PrintDigit 123

main&main 123

PrintDigit n&PrintDigit 123n/10=123/10=12

PrintDigit n&PrintDigit 12

main&main 123

PrintDigit n&PrintDigit 123n/10=123/10=12

PrintDigit n&PrintDigit 12n/10=12/1=1

PrintDigit n&PrintDigit 1

6 5 4main&main 123

PrintDigit n&PrintDigit 123

Print(n%10=123%10=)3

main&main 123

PrintDigit n&PrintDigit 123

PrintDigit n&PrintDigit 12Print(n%10=12%10=)2

main&main 123

PrintDigit n&PrintDigit 123n/10=123/10=12

PrintDigit n&PrintDigit 12

PrintDigit n&PrintDigit 1Print(n%10=1%10=)1

Write a C program to find sum of first n natural numbers using recursion. Note: Positive integers are known as natural number i.e. 1, 2, 3....n.

CSC 1102 PROGRAMMING LANGUAGE 1 Page 84 of 137

American International University-BangladeshDepartment of Computer Science

123456789101112131415

#include <stdio.h>int Sum( int n ){if( n==0 )return n;elsereturn n+Sum(n-1); //self call}void main( void ){int num, add; printf("Enter a positive integer:\n"); scanf("%d", &num); add = Sum( num ); printf("sum=%d", add);}

For better visualization of this recursion: Considering num = 5;

sum(5) =5+sum(4) =5+4+sum(3) =5+4+3+sum(2) =5+4+3+2+sum(1) =5+4+3+2+1+sum(0) =5+4+3+2+1+0 =5+4+3+2+1 =5+4+3+3 =5+4+6 =5+10 =15

In, this simple C program, sum() function is invoked from the same function. If n is not equal to 0 then, the function calls itself passing argument 1 less than the previous argument it was called with. Suppose, n is 5 initially. Then, during next function calls, 4is passed to function and the value of argument decreases by 1 in each recursive call. When, n becomes equal to 0, the value of n is returned which is the sum numbers from 5 to 1.

9.6. LABORATORY EXERCISES:9.6.1. I/O FUNCTIONS cin AND cout9.6.2. PROGRAM WRITING

9.6.2.1. A 5-digit positive integer is entered through the keyboard. Write a recursive function to calculate sum of digits of the 5-digit number.

9.6.2.2. Write a function that will scan a character string passed as an argument and convert all lower-case characters into their upper-case equivalents.

9.6.2.3. Write a program that will do the following:Declare and initialize 3 (three) 2-dimensional array of 3/3 in function main().Pass the contents of 1st and 2nd array elements into function change().Multiply the contents of 1st array element by 7.Add 5 to each of the array elements of 2nd array.Bring the control back to the function main().Now add 1st, 2nd, and 3rd array and store the result into another 2-dimensional array.Finally print the contents of the 4th array

9.6.2.4. Write a program which performs the following tasks:initialize an integer array of 10 elements in main()pass the entire array to a function modify()in modify()multiply each element of array by 3return the control to main()and print the new array elements in main()

9.6.2.5. Write a recursive function to find the factorial of a given integer.

9.6.2.6. Write a recursive function to obtain the first 25 numbers of a Fibonacci sequence. In a Fibonacci sequence the sum of two successive terms gives the third term. Following are the first few terms of the Fibonacci sequence:

CSC 1102 PROGRAMMING LANGUAGE 1 Page 85 of 137

American International University-BangladeshDepartment of Computer Science

1 1 2 3 5 8 13 21 34 55 89 …9.6.2.7. Write a function to interchange the value of two variables, say x and y. Illustrate the

use of this function, in a calling function. (Hint: Assume that x and yare defined as global variables.)

CSC 1102 PROGRAMMING LANGUAGE 1 Page 86 of 137

American International University-BangladeshDepartment of Computer Science

9.6.2.8. Write a program that can add, subtract, multiply and divide two integer numbers. Hint: Use the concept of functions, parameters and calling function by value

9.6.2.9. Write a program that can add, subtract, multiply and divide two integer numbers. Hint: Use the concept of functions, parameters and calling function by reference

9.6.2.10.Write a program that can ask user to input two numbers then choose from 4 options I.e. addition, subtraction, multiplication and division .The program continues until the user choose to exit from the program. Hint: Use the concept of functions, parameter and recursion

9.6.2.11.Write a program that takes input from the user the no of subjects, mark and credit of each subject and calculates CGPA. Hint: Use the concept of functions, parameter and calling by value

9.6.2.12.Write a program that calculates the equivalent resistance of the following circuit where R1=5 ohm, R2=3 ohm and R3=9 ohm. Hint: Use the concept of functions, parameters and calling function by reference

9.6.2.13.Write a program that takes input from the user the no of subjects, mark and credit of each subject and calculates CGPA. The program continues to calculate CGPA of 1 to n students until the user quits the program. Hint: Use the concept of functions, parameter and recursion.

CSC 1102 PROGRAMMING LANGUAGE 1 Page 87 of 137

Subject Mark CreditSubject 1Subject 2Subject 3……………Subject n

American International University-BangladeshDepartment of Computer Science

CSC 1102 PROGRAMMING LANGUAGE 1 Page 88 of 137

American International University-BangladeshDepartment of Computer Science

10. POINTERS

10.1. OBJECTIVES:To gain experience with – Introduction to Pointer. Pointer declaration, initialization, access. Memory management using pointer. Pointer in Array, string, and function. Array of pointers.

Writing C programs using –

Accessing, manipulating, input, and output of Pointer. Use of pointer in Array, string, and function.

10.2. POINTER

Pointers are a very powerful, but primitive facility contained in the C language. To understand pointer let us go through the concept of variables once more.

A variable is an area of memory that has been given a name. For example:int x;is an area of memory that has been given the name x. One can use the name to specify where to store data. For example:x=10;is an instruction to store the data value 10 in the area of memory named x. The computer access its own memory not by using variable names but by using a memory map with each location of memory uniquely defined by a number, called the address of that memory location. To access the memory of a variable the program uses the & operator. For Example: &x returns the address of the variablex. This has been used in scanf function.

A pointer is a variable that stores the location of memory. In more fundamental terms, a pointer stores the address of a variable. In more picturesque terms, a pointer points to a variable.A pointer has to be declared just like any other variable. For example: int *p;is a pointer to an integer. Adding an asterisk (called the de-referencing operator) in front of a variable's name declares it to be a pointer to the declared type. For example:int *p , q;declares p, a pointer to int, and q an int and the instruction:p=&q;stores the address of q in p. After this instruction, conceptually, p is pointing at q.

After declaring a pointer *p variable it can be used like any other variable. That is, p stores theaddress, or pointer, to another variable, &pgives the address of the pointer variable itself, and *p is the value stored in the variable that p points at.

&x represents the memory area of variable named x.

&p represents the memory area of variable named *p.

int x;x represents the value stored inside the area of variable named x. int *p;

p represents the address stored inside the area of variable named *p.

*p represents the value stored in the area represented/pointed to by address p.

CSC 1102 PROGRAMMING LANGUAGE 1 Page 89 of 137

American International University-BangladeshDepartment of Computer Science

123456789101112131415161718

// Understanding pointer variable#include <iostream.h>voidmain( void){intx;x = 10;int*p;p = &x;inty;y = *p; cout <<"Address of integer variable x: "<<&x <<"\n"; cout <<"Value stored in the memory area of variable x: "<< x <<"\n"; cout <<"Address of integer pointer variable *p: "<<&p <<"\n"; cout <<"Address stored in the area of pointer variable *p: "<<p<<"\n"; cout <<"Address of integer variable y: "<<&y <<"\n"; cout <<"Value pointed to by the pointer *p: "<< *p <<"\n"; cout <<"Value stored in the memory area of variable y: "<< y <<"\n";}Address of integer variable x: 0x8fbbfff0Value stored in the memory area of variable x: 10Address of integer pointer variable *p: 0x8fbbfff4Address stored in the area of pointer variable *p: 0x8fbbfff0Address of integer variable y: 0x8fbbfff8Value pointed to by the pointer *p: 10Value stored in the memory area of variable y: 10

On execution of the statement, int x; an area of memory of size intis created with name x.Addressof the memory area of variable x is0x8f86fff0, represented in the program using&x. On execution of statement x=10; the integer value 10 is stored in the memory area 0x8f86fff0 created for x. And this stored value (10) is represented in the program usingx.

On execution of the statement, int *p; an area of memory of size address is created with name *p.Address of the memoryarea of variable *p is0x8f86fff4, represented in the program using &p.On execution of the statement p=&x; the address of x, (&x)0x8f86fff0, is stored in the memory area 0x8f86fff4 created for the pointer variable *p. And this address (0x8f86fff0) is represented in the program using p.

Memory Address value varaible0x8f86fff0

10 int x

x=100x8f86fff1 &x=0x8f86fff00x8f86fff20x8f86fff30x8f86fff4

0x8f86fff0 int *p

p=0x8f86fff00x8f86fff5 &p=0x8f86fff40x8f86fff6 *p=*(0x8f86fff0)0x8f86fff7 =*(&x)= x = 100x8f86fff8

10 int y

y=*p=100x8f86fff9 &y=0x8f86fff80x8f86fffa0x8f86fffb

CSC 1102 PROGRAMMING LANGUAGE 1 Page 90 of 137

American International University-BangladeshDepartment of Computer Science

On execution of the statement, int y; an area of memory of size int is created with name y.Address of the memory area of variable yis0x8f86fff8, represented in the program using&y.

On execution of statement y=*p; the value of *p is computed (conceptually) as follows. *plooks into its own memory area (&p=) 0x8f86fff4 and finds the address value (p=) 0x8f86fff0 inside it, which is actually the memory area of variable x (&x= 0x8f86fff0). Then, *p goes to the found/pointed location (p=&x=) 0x8f86fff0 and finds the value 10 stored inside this memory area. This stored value 10 is returned by *p.

So *p represents the value (10) stored in the memory area (&x= 0x8f86fff0) pointed to by its stored address value (p= 0x8f86fff0).

This returned value 10 is then stored in the area 0x8f86fff8 created for y.

10.3. POINTERS & ARRAYS:

An alternative idea of an array is to consider it as simply a block of memory. An array can be accessed with pointers as well as with [] square brackets. The name of an array variable, standing alone, is actually a pointer to the first element in the array.So, any operation that can be achieved by array subscripting can also be done with pointers or vice-versa.12345678910111213141516171819

// Understanding pointer variable#include <iostream.h>voidmain( void){floatnumbers[5] = {22.5,34.8,46.8,59.1,68.3};cout <<"1st element of array numbers: "<< numbers[0] <<"\n";cout <<"1st element of array numbers: "<< *numbers <<"\n";cout <<"3rd element of array numbers: "<< numbers[2] <<"\n"; cout <<"3rd element of array numbers: "<< *(numbers+2) <<"\n";float *p;p = numbers;//&numbers[0] cout <<"1st element of array numbers: "<< p[0] <<"\n"; cout <<"1st element of array numbers: "<< *p <<"\n"; cout <<"3rd element of array numbers: "<< p[2] <<"\n";cout<<"3rd element of array numbers: "<< *(p+2) <<"\n"; int i;for(i=0, p=numbers; i<5; i++, p++)cout<<"Element "<< (i+1) <<" of array numbers: "<< *p <<"\n"; }1st element of array numbers: 22.51st element of array numbers: 22.53rd element of array numbers: 46.83rd element of array numbers: 46.81st element of array numbers: 22.51st element of array numbers: 22.53rd element of array numbers: 46.83rd element of array numbers: 46.8Element 1 of array numbers: 22.5Element 2 of array numbers: 34.8Element 3 of array numbers: 46.8Element 4 of array numbers: 59.1

CSC 1102 PROGRAMMING LANGUAGE 1 Page 91 of 137

American International University-BangladeshDepartment of Computer Science

Element 5 of array numbers: 68.3

The array name numbersor the pointer variable *p(after p = numbers) is a pointer to the first floating point number in the declared arrayfloat numbers[5]; So the first element of the array, 22.3, could be accessed by writing:numbers[0]or p[0]or by writing*numbersor *p. The third element of the array, 46.8, could be accessed by writing: numbers[2]or p[2]or by writing*(numbers+2)or *(p+2).Now, let’s examine the notation (numbers+2), (p+2).

numbers numbers+2123472

123456 0 1 2 3 422.5 34.8 46.8 59.1 68.3

float size

p+2 123472

p

Here,p+2 ornumbers+2 means the second cell after the cell represented by p ornumbers, in this case second cell afternumbers[0]isnumbers[2]. Also need to notice that, each cell is of sizefloat(8 bytes). Every pointer value (i.e address) always points to the starting byte of an element or variable. Additionally, pointer value + n = pointer value + n * (sizeof(data type)).

Assuming the starting address of the array numbersis 123456 –

numbers[0] starts at address, numbers+0*sizeof(float) = 123456+0*8 = 123456, numbers[1] starts at address, numbers+1*sizeof(float) = 123456+1*8 = 123464, numbers[2] starts at address, numbers+2*sizeof(float) = 123456+2*8 = 123472.

When apointer value is increased by a numbern, it actually increases by n*sizeof(data type) number of bytes. So with every increase ofpby one inline17 by p++in the for loop, pointer p moves to the next cell.

123456789101112131415161718

// Pointer Arithmetic#include <iostream.h>voidmain( void){intnumbers[5] = {22,34,46,59,68};int *p, i;p = numbers;//&numbers[0]for(i=0; i<5; i++){ (*p)++; //increases the value at pcout<<"Element "<< (i+1) <<" of array numbers: "<< *p <<"\n"; p++; //increases p to the next cell }cout<<"Element "<< (p-numbers+1) <<" of array numbers: "<<*(--p)<<"\n";cout<<"Element "<< (p-numbers+1) <<" of array numbers: "<<*(--p)<<"\n";cout<<"Element "<< (p-numbers+1) <<" of array numbers: "<<*(--p)<<"\n";cout<<"Element "<< (p-numbers+1) <<" of array numbers: "<<--(*(--p))<<"\n";cout<<"Element "<< (p-numbers+1) <<" of array numbers: "<<(*(--p))--<<"\n";}Element 1 of array numbers: 23

CSC 1102 PROGRAMMING LANGUAGE 1 Page 92 of 137

American International University-BangladeshDepartment of Computer Science

Element 2 of array numbers: 35Element 3 of array numbers: 47Element 4 of array numbers: 60Element 5 of array numbers: 69Element 5 of array numbers: 69Element 4 of array numbers: 60Element 3 of array numbers: 47Element 2 of array numbers: 34Element 1 of array numbers: 23

In line 7-11, as p = numbers;the notation *p initially gives the valuenumbers[0]. So,(*p)++indicatesnumbers[0]++. Afterp++is executed,pnow points to numbers[1]. (*p)++then indicatesnumbers[1]++. And so on. Before getting out of the loop the value ofpbecomes equivalent tonumbers+5 (as variableiincreases5 times), that is the next byte afternumbers[4].

Thecoutworks from right to left. In line 13-15,*(--p)will be evaluated first. In line 13, the--pwill be evaluatep=numbers+4. And*(--p)will represent the value at numbers[4]. Then the expressionp-numbers+1is evaluated as(numbers+4)-numbers+1=5. Accordingly, in line14-15the prefix--pwill evaluate p to (numbers+3) and (numbers+2) and *(--p)will represent the value numbers[3]and numbers[2]respectively. Finally, the expression (p–numbers+1) is evaluated as (numbers+3)-numbers+1=4(line 14) and (numbers+2)-numbers+1 = 3(line 15) respectively.

In line18, --(*(--p))will first evaluate p = numbers+1, which makes *(--p)representing numbers[1], and finally--(*(--p))will evaluate as --numbers[1], decreasing the value at numbers[1]by 1. Then the expression p–numbers+1is evaluated as (numbers+1)-numbers+1 =2.

In line 19, (*(--p))--will first evaluate p = numbers + 0, which makes *(--p)representing numbers[0], and finally(*(--p))--will evaluate as numbers[1]--, decreasing the value at numbers[0]by 1 after printing the value at numbers[1](postfix). Then the expression p-numbers+1is evaluated as (numbers+0)-numbers+1 = 1.

10.4. POINTERS & FUNCTIONS

Passing arguments to functions by value, there is no direct way for the called function to alter a variable in the calling function. Pointer arguments enable a function to access and change objects in the function that called it. Let’s consider the following example:12345678910111213

/* Swap two numbers using function. */ #include <iostream.h>void swap(int *a,int *b); void main(void){ int num1=5,num2=10; swap(&num1,&num2); /* address of num1 and num2 is passed */ cout<<"Number1 = "<<num1<<"\n"; cout<<"Number2 = "<<num2;} void swap(int *a,int *b){ //a and b points to &num1 and &num2 respectively int t;

Number1 = 10Number2 = 5

CSC 1102 PROGRAMMING LANGUAGE 1 Page 93 of 137

American International University-BangladeshDepartment of Computer Science

14151617

t=*a; *a=*b; *b=t; }

The program starts with function main getting the control and creating two variables num1 and num2 with values 5 and 10 respectively (line 5).main int num1 int num2&main 5 10

Function main calls the function swap with two parameter values &num1 and &num2 (line 6). So the address of num1 and num2 is send through the parameter of swap. Now the control goes to the function swap and it creates two pointer (parameter) variables *a and*b assigned with the address values of num1 and num2 of main respectively. Another variable t is created (line 14).main num1 num2&main 5 10

swap&swap

int *a int *b int t

With the statement t=*a; variable t is assigned to the value, num1 of main, pointed to by pointer *a. main num1 num2&main 5 10

swap&swap 5

*a *b t

With the statement *a = *b; pointer variable *a, pointing to num1 of main, is assigned to the value, num2 in main, pointed to by pointer *b.main num1 num2&main 10 10

swap&swap 5

*a *b t

With the statement *b=t;pointer variable *b, pointing to num2 of main, is assigned to the value of t.main num1 num2&main 10 5

swap&swap 5

CSC 1102 PROGRAMMING LANGUAGE 1 Page 94 of 137

American International University-BangladeshDepartment of Computer Science

*a *b t

Any changes we make to*aand*bin functionswap, will change the values ofnum1andnum2respectively in functionmain as a is pointing to num1 and b is pointing to num2. Before exiting the function swap, the variables created by swap is destroyed.Then the control goes back to the function main (in line 6).main num1 num2&main 10 5

swap&swap 5

*a *b t

So nothing changes for the values of the variables num1 and num2 of main due to the destruction of the variables *a and*b. Because, destruction only destroys the space provided for *a and*b. It does not destroy the space it was pointing to. Whatever changes were made in swap by *a and*b remains. So, line 8 and 9 prints the swapped values of the variables num1 and num2.

10.5. void POINTERS

The void type of pointer is a special type of pointer which represents the absence of type.So void pointers are pointers that point to a value that has no type (and thus also an undetermined length and undetermined dereference properties).This allows voidpointers to point to any data type, int,float, char, double or any type of array. But the data pointed by them cannot be directly dereferenced, since we have no type to dereference to.So need to cast the address in the void pointer to some other pointer type that points to a concrete data type before dereferencing it. Let us consider the following example:1234567891011121314151617181920212223

// increaser#include <iostream.h>void increase (void*data, int psize){if ( psize == sizeof(char) ){ char*pchar; pchar=(char*)data; ++(*pchar); }elseif (psize == sizeof(int) ){ int*pint; pint=(int*)data; ++(*pint); }}void main (void){char a = 'x';int b = 1602; increase (&a,sizeof(a)); increase (&b,sizeof(b));cout<< a <<", "<< b <<endl;}

y, 1603

CSC 1102 PROGRAMMING LANGUAGE 1 Page 95 of 137

American International University-BangladeshDepartment of Computer Science

We start with the main where two variables chara andint b is created with the values ‘x’ and 1602 respectively (line 18-19).

 main char a int b&main ‘x’ 1602

Line 20 calls the function increase with address of a and the size of a as parameters. sizeof is an operator integrated in the C++ language that returns the size in bytes of its parameter. For non-dynamic data types this value is a constant. Therefore, sizeof(a)= sizeof(char)= 2, because char type is two bytes long.Now the control goes to the function increase and it creates two (parameter) variablesvoid *data and int psize assigned with the address value of a andsizeof(a)=2 of main respectively.

main char a intb&main ‘x’ 1602

increase&increase &a 2

void *data int psize

With the true value of the conditional statement psize==sizeof(char)a new pointer variable char *pchar is created and assigned to the value, *data. As *data has no type, it must be type casted to char * before being assigned. Though *data contains the address of a in main, this address cannot be accessed using *data with type mismatch.

main a b&main ‘x’ 1602

increase

&increase &a(char *)

2

*data *pchar psize

With the statement ++(*pchar); pointer variable *pchar, pointing to a of main, is increased by one. So, the value of a in main is changed to ‘y’(the ASCII value is increased by one).

main a b&main ‘y’ 1602

increase&increase &a 2

*data *pchar psize

Before exiting the function increase, the variables created by increase is destroyed.Then the control goes back to the function main (in line 20). So, we see the value a is changed to ‘y’.

main a b&main ‘y’ 1602

CSC 1102 PROGRAMMING LANGUAGE 1 Page 96 of 137

American International University-BangladeshDepartment of Computer Science

increase&increase &a 2

*data *pchar psize

Line 21 calls the function increase with address of b and the size of b as parameters. sizeof(b)= sizeof(int)= 4, because char type is four bytes long.Now the control goes to the function increase and it creates two (parameter) variables void *data and int psize assigned with the address value of b and sizeof(b)=4 of main respectively.

main char a intb&main ‘y’ 1602

increase&increase &b 4

void *data int psize

With the true value of the conditional statement psize==sizeof(int)a new pointer variable int *pint is created and assigned to the value, *data. As *data has no type, it must be type casted to int * before being assigned. Though *data contains the address of b in main, this address cannot be accessed using *data with type mismatch.

main a b&main ‘y’ 1602

increase

&increase &b(int *)

4

*data *pint psize

With the statement ++(*pint); pointer variable *pint, pointing to b of main, is increased by one. So, the value of b in main is changed to 1603.

main a b&main ‘y’ 1603

increase&increase &b 4

*data *pint psize

Before exiting the function increase, the variables created by increase is destroyed.Then the control goes back to the function main (in line 21). So, we see the value b is changed to 1603.

main a b&main ‘y’ 1603

increase&increase &b 4

*data *pint psize

CSC 1102 PROGRAMMING LANGUAGE 1 Page 97 of 137

American International University-BangladeshDepartment of Computer Science

Line 22 prints the value of y for a and1603 for b which is the value changed by increase.

10.6. NULL POINTER

A NULL pointer is a regular pointer of any pointer type which has a special value that indicates that it is not pointing to any valid reference or memory address. This value is the result of type-casting the integer value zero to any pointer type.12int * p;p = 0; //can also write, p = NULL;// p has a null pointer value

Do not confuse null pointers with void pointers. A null pointer is a value that any pointer may take to represent that it is pointing to "nowhere", while a void pointer is a special type of pointer that can point to somewhere without a specific type. One refers to the value stored in the pointer itself and the other to the type of data it points to.

10.7. DYNAMIC MEMORY ALLOCATION

The exact size of array is unknown until the compile time, i.e., time when a compiler compiles code written in a programming language into an executable form. The size of array declared initially can be sometimes insufficient and sometimes more than required. Also, what if we need a variable amount of memory that can only be determined during runtime? Dynamic memory allocation allows a program to obtain more memory space, while running or to release space when no space is required. There are 4 library functions under "stdlib.h" for dynamic memory allocation.

malloc()

The name malloc stands for "memory allocation". The function malloc() reserves a block of memory of specified size and return a pointer of type void which can be casted into pointer of any form. Syntax – ptr=(cast-type*)malloc(byte-size)

Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of memory with size of byte-size. If the space is insufficient, allocation fails and returns NULL pointer. Example –

ptr=(int*)malloc(100*sizeof(int));

This statement will allocate 400(size ofint=4) bytes consecutively and the pointer points to the address of first byte of memory.calloc()

The name calloc stands for "contiguous allocation". The only difference between malloc() and calloc() is that, malloc() allocates single block of memory whereas calloc() allocates multiple blocks of memory each of same size and sets all bytes to zero.Syntax –ptr=(cast-type*)calloc(n,element-size);

CSC 1102 PROGRAMMING LANGUAGE 1 Page 98 of 137

American International University-BangladeshDepartment of Computer Science

This statement will allocate contiguous space in memory for an array of n elements. For example:ptr=(int*)calloc(25,sizeof(int));

This statement allocates contiguous space in memory for an array of 25 elements each of size of integer, i.e, 4 bytes.

realloc()

If the previously allocated memory is insufficient or more than sufficient. Then, you can change memory size previously allocated using realloc().For example:ptr=(int*)malloc(25*sizeof(int));

ptr=(int*)realloc(ptr,40);

First statement allocates contiguous space in memory for an array of 25 elements each of size of integer, i.e, 4 bytes. Next statement reallocates additional 15 contiguous space in memory along with the previous 25 for the new size 40.

free()

Dynamically allocated memory with either calloc()or malloc()or realloc()does not get return on its own. The programmer must use free()explicitly to release space. Syntax –free(ptr);

This statement cause the space in memory pointer by ptr to be deallocated.

Examples:1234567891011121314151617181920212223242526

// malloc, calloc#include <iostream.h>#include <stdlib.h>void main(void){int n,i,*ptr,sum=0;cout<<"# of elements: ";cin>>n;//input 5 ptr=(int*)malloc(n*sizeof(int)); //ptr=(int*)calloc(n,sizeof(int));/*Using line 10 instead of line 9 will give different memory allocation scheme but same output. */ if(ptr==NULL){/*The requested dynamic memory is allocated by the system from the memory heap. It is important to check if the request to allocate memory was successful or not.*/cout<<"Error! memory not allocated.";exit(0); }cout<<"Enter elements:\n";for(i=0;i<n;++i) { //input 2 6 7 4 3cin>>(ptr+i); sum+=*(ptr+i); }cout<<"Sum = "<<sum;

# of elements: 5Enter elements:26743Sum = 22

CSC 1102 PROGRAMMING LANGUAGE 1 Page 99 of 137

American International University-BangladeshDepartment of Computer Science

2728

free(ptr); //memory deallocated}

The most important difference between declaring a normal array and assigning dynamic memory to a pointer is that the size of an array has to be a constant value, which limits its size to what we decide at the moment of designing the program, before its execution, whereas the dynamic memory allocation allows us to assign memory during the execution of the program (runtime) using any variable or constant value as its size.1234567891011121314151617181920

// realloc#include <iostream.h>#include <stdlib.h>void main(void){int *ptr,i,n1,n2;cout<<"Enter size of array: ";cin>>n1;//input 5 ptr=(int*)malloc(n1*sizeof(int));cout<<"Address of allocated memory:\n";for(i=0;i<n1;++i)cout<<(ptr+i)<<"\n";cout<<"\nEnter new size of array: ";cin>>n2;//input 8 ptr=(int *)realloc(ptr,n2);cout<<"Address of reallocated memory:\n";for(i=0;i<n2;++i)cout<<(ptr+i)<<"\t";free(ptr); //memory deallocated}

Enter size of array: 5 Address of allocated memory:0x8f9813bc0x8f9813c00x8f9813c40x8f9813c80x8f9813cc

Enter new size of array: 8Address of reallocated memory:0x8f9813bc0x8f9813c00x8f9813c40x8f9813c80x8f9813cc0x8f9813d00x8f9813d40x8f9813d8

C++ integrates the operators new and deletefor dynamic memory allocation.

10.8. Operators new and new[]

In order to request dynamic memory we use the operator new. new is followed by a data type specifier.If a sequence of more than one memory block is required, the data type specifier is followed by the number of these memory blocks within brackets []. It returns a pointer to the beginning of the new block of memory allocated. Syntax:12pointer = new vtype;pointer = new vtype [number_of_elements];

The first expression is used to allocate memory to contain one single element of type vtype. The second one is used to assign a block (an array) of elements of type vtype,wherenumber_of_elements is an integer value representing the amount of these.

10.9. Operators delete and delete[]

Since the necessity of dynamic memory is usually limited to specific moments within a program, once it is no longer needed it should be freed so that the memory becomes available again for other requests of dynamic memory. This is the purpose of the operator delete, whose format is:12delete pointer;delete [] pointer;

CSC 1102 PROGRAMMING LANGUAGE 1 Page 100 of 137

American International University-BangladeshDepartment of Computer Science

The first expression should be used to delete memory allocated for a single element, and the second one for memory allocated for arrays of elements. The value passed as argument to delete must be either a pointer to a memory block previously allocated with new, or a null pointer (in the case of a null pointer, delete produces no effect).1234567891011121314151617181920212223

// new, delete#include <iostream.h>#include <stdlib.h>void main(void){int n,i,*ptr,sum=0;cout<<"# of elements: ";cin>>n;//input 5 ptr=newint[n]; if(ptr==NULL)//ptr==0 {cout<<"Error! memory not allocated.";exit(0); }cout<<"Enter elements:\n";for(i=0;i<n;++i) {//input 2 6 7 4 3cin>>(ptr+i);//ptr[i] sum+=*(ptr+i);//ptr[i] }cout<<"Sum = "<<sum;delete[](ptr);//memory deallocated}

# of elements: 5Enter elements:26743Sum = 22

Let us now look into an example showing the return of pointers from a function.123456789101112131415161718192021222324

//Array Multiplication#include <iostream.h>#include <stdlib.h>

int*ArrMul(int a[], int b[], intsize){int i,*c = new int[size]; //c[5]for(i=0; i<size; i++) c[i] = a[i] * b[i];return c;}void PrintArr(int*a, int size){ for(int i=0; i<size; i++)cout<<a[i]<<"\t";cout<<"\n ";}void main(void){int*z,x[5]={1,2,3,4,5},y[5]={5,6,7,8,9}; z = ArrMul(x, y, 5);cout<<"First array:\n"; PrintArr( x, 5 );cout<<"second array:\n";

First array:1 2 3 4 5second array:5 6 7 8 9result array:5 12 21 32 45

CSC 1102 PROGRAMMING LANGUAGE 1 Page 101 of 137

American International University-BangladeshDepartment of Computer Science

2526272829

PrintArr( y, 5 );cout<<"result array:\n"; PrintArr( z, 5 );delete[](z);//memory deallocated}

Two array x and y with five elements are multiplied index wise using the function ArrMul. Function ArrMul dynamically allocates memory for the resultant array cof the multiplication.

main *z x y

&main 1 2 3 4 5 5 6 7 8 9

5 12 21 32 45ArrMul&ArrMul 5 5

*c i size a[] b[]Before exit from function ArrMul the address stored in *c returned and all the variables created in ArrMul is destroyed. The control is transferred to main and z is assigned to the address value returned by c of ArrMul. Then the arrays represented by x,y, and z is printed using function PrintArr.

main *z x y

&main 1 2 3 4 5 5 6 7 8 9

5 12 21 32 45ArrMul&ArrMul 5 5

*c i size a[] b[]

Consider the case, if dynamic array c in ArrMul was declared as an array c[5]. That is, instead of int *c=new int[size] in line 7, if it was int c[5], the following would happen.

main *z x y

&main 1 2 3 4 5 5 6 7 8 9

ArrMul&ArrMul 5 12 21 32 45 5 5

c[5] i size a[] b[]Before exit from function ArrMul the address represented by c (&c[0]) is returned and all the variables created in ArrMul is destroyed. The control is transferred to main and z is assigned to the address value returned by c of ArrMul. Then the arrays represented by xand y is printed using function PrintArr. Then PrintArr finds an error when trying to print the array z, as the address represented by z has already been destroyed at the exit of the function ArrMul.

main *z x y

CSC 1102 PROGRAMMING LANGUAGE 1 Page 102 of 137

American International University-BangladeshDepartment of Computer Science

&main 1 2 3 4 5 5 6 7 8 9

ArrMul&ArrMul 5 12 21 32 45 5 5

c[5] i size a[] b[]

So, while returning a pointer to any variable or memory area, must make sure that the returned memory area is active or not destroyed after return.

10.10. POINTERS AND INITIALIZATION

Consider the statementint *p; which declares a pointerp, and like any other variable this space will contain garbage (random numbers), because no statement likep = &someint; or p = new int;has yet been encountered which would give it a value.Writing a statement int *p=2000;is syntactically correct as p will point to the 2000th

byte of the memory. But it might fail as byte 2000 might be being used by some other program or may be being used by some other data type variable of the same program. So such initialization or assignment must be avoided unless the address provided is guaranteed to be safe.There is an important difference between these definitions: 12char amsg[] = "now is the time"; /* an array */char *pmsg = "now is the time"; /* a pointer */

amsg is an array, just big enough to hold the sequence of characters and '\0' that initializes it. Individual characters within the array may be changed but amsg will always refer to the same storage. On the other hand, pmsg is a pointer, initialized to point to a string constant; the pointer may subsequently be modified to point elsewhere, but the result is undefined if you try to modify the string contents.

10.11. LABORATORY EXERCISES:10.11.1. PROGRAM WRITING

10.11.1.1. Declare a pointer to a function that accepts three integer arguments and returns a floating-point quantity.

10.11.1.2. Declare a pointer to a function that accepts three pointers to integer quantities as arguments and returns a pointer to a floating-point quantity.

10.11.1.3. Write a program using pointers to read in an array of integers and print its elements in reverse order.

10.11.1.4. Write a function using pointers to add two matrices and to return the resultant matrix to the calling function.

10.11.1.5. Using pointers, write a function that receives a character string and a character as argument and deletes all occurrences of this character in the string. The function should return the corrected string with no holes.

CSC 1102 PROGRAMMING LANGUAGE 1 Page 103 of 137

American International University-BangladeshDepartment of Computer Science

10.11.1.6. Write a structure dynamicArray that has a char pointer type variable stand an int variable maxSizeand lastValue. A function named Constructor takes an integer parameter to initialize maxSize. Also it dynamically allocates enough memory in st to hold upto maxSize number of integers. Another function Destructor should free that dynamically allocated memory. Insert function that takes a character parameter and inserts that after the last element (increase lastValue). Delete function that returns the last character and deletes that from the array (decrease lastValue). Complete the definitions of Constructor, Destructor, Insert and Delete for this program.N.B.Use new and delete

CSC 1102 PROGRAMMING LANGUAGE 1 Page 104 of 137

American International University-BangladeshDepartment of Computer Science

17. DATA STORAGE (III)17.1. OBJECTIVES:To gain experience with – Introduction to String. String declaration, initialization, access. String terminator NULL character. String library functions.

Writing C programs using –

Accessing, manipulating, input, and output of string. Sorting, searching, adding, and deleting element in string.17.2. STRING

Strings are sequence of characters representing a piece of text. In C a string is represented as some characters enclosed by double quotes- "This is a string". A string in C/C++ is mainly declared using an array of characters. The main difference between a simple array of character and an array of character representing string is the end marker given at the end of a string. The standard library functions can recognize this end marker as being the end of the string. The end marker is called the zero (or NULL) byte because it is just a byte which contains the value zero: '\0'. Programs rarely gets to see this end marker as most functions which handle strings use it or add it automatically.

17.2.1. DECLARATION & INITIALIZATION:

Declaration of a string is just an array of characters.

 charmimo [5];But things are different when we initialize during declaration. An array to contain 5 character values ('H','e','l','l','o') of type char called mimo could be represented like this:

 charmimo [5]={'H','e','l','l','o'};0 1 2 3 4

mimo 'H' 'e' 'l' 'l' 'o'

|--char--|

But, to represent the same text as string in C/C++ double quotation (") is used to bound the text. And, a NULL character is added at the end of the text. So, because of this NULL, we need to declare an additional slot in the array.

 charmimo [6]= "Hello";0 1 2 3 4 5

mimo 'H' 'e' 'l' 'l' 'o' '\0'

|--char--|

17.2.2. ACCESS, INPUT, OUTPUT:

Let’s start with an example:1// null-terminated sequences of characters

CSC 1102 PROGRAMMING LANGUAGE 1 Page 105 of 137

American International University-BangladeshDepartment of Computer Science

234567891011

#include <stdio.h>void main (void){charQuestion[] = "Please, enter your first name: ";charGreeting[] = "Hello";charFirstName[80];printf("%s",Question);scanf("%s", FirstName);printf("%s, %s!", Greeting, FirstName);}Please, enter your first name: John

Hello, John!

Lines 5-7declares three arrays of characters. First two are initialized as strings with a NULL character at their end. Normally, we would need a for loop to print each character of these character arrays (with %c and accessing the array elements individually). Let’s take a close look at the two parameters of the printf in line 8. First parameter has a %s (here s for string) instead of %c, and the second parameter is the array name Question (here starting address of the array Question) instead of individual access (ex. Question[i]). The same can be found in line 9, where we have scanf with %s and the array FirstArray.

In all such cases, the %s indicates a string, a continuous group of characters, that will be processed one after another.

The address indicates the location in the memory from where the processing will start.

The NULL character indicates where the processing will stop for printf.

And for scanf, after the processing (i.e, after the string input) a NULL character is automatically added at the end of the string.

Instead of asking for the first name only, if we would have asked for the whole name, this program might not work properly. That is, if we would have given input John Rambo instead of only John the output will be as follows –

Please, enter your first name: John Rambo

Hello, John!

Still it shows John after Hello, not John Rambo. As we know, that scanf always stops at white spaces during taking input. So, after taking John as input scanf receives a space indicating the end of input. So it never even goes for Rambo. To overcome this there is another function gets() which takes only a string as input until a newline (\n) encounters. So just writing –

 gets(FirstName); instead of printf("%s",Question);

will give the following output –Please, enter your first name: John Rambo

Hello, John Rambo!

CSC 1102 PROGRAMMING LANGUAGE 1 Page 106 of 137

American International University-BangladeshDepartment of Computer Science

Just like gets() for reading from the user, there is also puts() which prints the string along with a newline (\n) character at the end of the string.

17.2.3. STRING HANDLING FUNCTIONS

Strings are often needed to be manipulated by programmer according to the need of a problem. All string manipulation can be done manually by the programmer but, this makes programming complex and large. To solve this, the C supports a large number of string handling functions. There are numerous functions defined in "string.h"header file. Few commonly used string handling functions are discussed below:

Function Work Of Function

strlen(str) Calculates the length of stringstr; the total number of characters from the given starting address by str until a NULL encounters.

strcpy(s1, s2)

Copies a string str2to another stringstr1; all the characters starting from the given starting address by str2 until a NULL encounters, will be copied in sequentially from the given address by str1.

strcat(s1, s2)

Concatenates(joins) two strings; all the characters starting from the given starting address by str2 until a NULL encounters, will be copied in sequentially from the NULL character at the end of str1.

strcmp(s1, s2)

Compares two strings; if str1 and str2 are equal strcmp returns 0, if str1 is alphabetically lower than str2 then strcmp returns <0and otherwise returns >0;

For all such library functions a NULL character is assumed to be at the end of the existing string and a NULL character is always included at the end of the new/updated/changed string.

17.3. LABORATORY EXERCISES:17.3.1. PROGRAM WRITING

17.3.1.1.Observe the behaviors of the following program that contains 3 user-defined Functions: xleft( ), xright( ) and xsubstr( ) from the output given below. Define any two user-defined function from the following program, which should give exactly the same output as shown in the example. void main( ) { char msg[ ] = "Vote Sunderban for New7Wonder" char newmsg[35]; xleft(msg, newmsg, 14); printf("\n%s",newmsg); xright(msg, newmsg, 10); printf("\n%s", newmsg); xsubstr(msg, newmsg, 16, 18); printf("\n%s", newmsg); xcat(msg, newmsg, 6, 14, 19, 29); printf("\n%s", newmsg);

xcmp(msg, newmsg, 9, 11, 27, 29); printf("\n%s", newmsg);

CSC 1102 PROGRAMMING LANGUAGE 1 Page 107 of 137

American International University-BangladeshDepartment of Computer Science

xcmp(msg, newmsg, 6, 9, 20, 23); printf("\n%s", newmsg); }The output of this program would be . . . . Vote SunderbanNew7WonderForSunderbanNew7WonderEQUALNOT EQUAL

17.3.1.2.Write a function that will take one string s1and one character chas parameter and return how many times choccurs in s1. For example:s1 = “American International University Bangladesh”ch = ‘a’‘a’ occurs 5 times in “American International University Bangladesh”. So return 5.

17.3.1.3.Write a program that will print out all the rotations of a string typed into it. For example, the rotations of the word “space” are:

space paces acesp cespa espac17.3.1.4.Write a program that replaces two or more consecutive blanks in a string by a single blank.

For Example, if the input is

Grim return to the planet of apes!!

The output should be

Grim return to the planet of apes!!17.3.1.5.Write a program that will input two strings s1 and s2 and output how many times s2

occurs in s1. For example:s1 = “american international university bangladesh”s2 = “er”

“er” occurs 3 times in “american international university bangladesh”. So output is 3.

17.3.1.6.Write a program to find out the number of words and number of characters of an input string.

Note: If the input string is “Brazil is the best team”. The output will be Number of words = 5. Number of characters = 19.

CSC 1102 PROGRAMMING LANGUAGE 1 Page 108 of 137

American International University-BangladeshDepartment of Computer Science

17.3.1.1 Write a program that asks user to input his/her full name and outputs the name in reverse. Hint: Use STRREV()

17.3.1.2 Write a program that asks user to input his/her two favorite subjectsand after concatenating the 1st subject at the end of the 2nd subject gives output. Hint: Use STRCAT()

17.3.1.3 Write a program that stores the name of a food in a string called source but outputs the same name in another string called target . Hint: Use STRCPY()

17.3.1.4 There are two resistors in a circuit. R1=four ohm and R2= four ohm. Write a program that compares R1 and R2 to find out whether they are same or different. Hint: Use STRCMP()

17.3.1.5 There are two resistors in a circuit. R1=four ohm and R2= five ohm. Write a program that compares R1 and R2 to find out whether they are same or different. Hint: Use STRCMP()

17.3.1.6 Write a program that asks user to input his/her full name and outputs the number of characters that are present in the name. Hint: Use STRLEN()

17.3.1.7 There are two resistors in a circuit. R1=four ohm and R2= four ohm. Write a program that compares R1 and R2 to find out whether they are same or different. Hint: Cannot use STRCMP()

17.3.1.8 Write a program that asks user to input his/her full name and outputs the name in reverse. Hint: Cannot use STRREV()

CSC 1102 PROGRAMMING LANGUAGE 1 Page 109 of 137

American International University-BangladeshDepartment of Computer Science

18. PERSISTENCE

18.1. OBJECTIVES:To gain experience with – File input/output File manipulation File access modes

Writing C programs involving – Files

18.2. FILE

A file represents a sequence of bytes, does not matter if it is a text file or binary file. C programming language provides access on high level functions as well as low level (OS level) calls to handle file on storage devices.

18.2.1. DECLARING A FILE POINTER

For C File I/O a FILE pointer is needed which will let the program keep track of the file being accessed. (It can be considered as the memory address of the file or the location of the file).There are types and functions in the library stdio.h that are used for file I/O.

Declaration of a FILE pointer is just like declaration of any other pointer.

  FILE *fp;

18.2.2. OPENING FILES

In order to open a file, we can use the function fopen().The usage is:

  fp = fopen(filename, mode);

Where: filename is a string that holds the name of the file on disk (including a path like

“/cs/course” if necessary). mode is a string representing how you want to open the file. Most often you'll open a

file for reading ("r") or writing ("w").

fopen() returns a FILE* that can then be used to access the file. When the file cannot be opened (e.g., we don't have permission or it doesn't exist when opening for reading), fopen() will return NULL.

Here are examples of opening files:

123456

// opening files#include <stdio.h>void main (void){

FILE *ifp, *ofp;char *mode = "r";

CSC 1102 PROGRAMMING LANGUAGE 1 Page 110 of 137

American International University-BangladeshDepartment of Computer Science

78910111213141516171819202122

char outputFilename[] = "out.list";

ifp = fopen("in.list", mode);

if (ifp == NULL) { fprintf(stderr, "Can't open input file in.list!\n"); exit(1);}

ofp = fopen(outputFilename, "w");

if (ofp == NULL) { fprintf(stderr, "Can't open output file %s!\n", outputFilename); exit(1);}

}

Note that at line 9 the input file that we are opening for reading ("r") must already exist. In contrast, at line16 the output file we are opening for writing ("w") does not have to exist. If it doesn't, it will be created. If this output file does already exist, its previous contents will be thrown away (and will be lost).

There are other modes we can use when opening a file, such as append ("a") to append something to the end of a file without losing its contents...or modes that allow us to both read and write. Here is a list of some common modes while working with files:

Modes Descriptionr open for readingw open for writing (file need not exist)a open for appending (file need not exist)r+ open for reading and writing, start at beginningw+ open for reading and writing (overwrite file)a+ open for reading and writing (append if file exists)

18.2.3. READING FROM OR WRITING TO A FILE

Once a file has been successfully opened, we can read from it using fscanf() or write to it using fprintf(). These functions work just like scanf() and printf(), except they require an extra first parameter, a FILE * for the file to be read/written.

*** There are other functions in stdio.h that can be used to read or write files. Look them up in a good C reference.

Continuing our example from above, suppose the input file consists of lines with a username and an integer test score, e.g.:

CSC 1102 PROGRAMMING LANGUAGE 1 Page 111 of 137

American International University-BangladeshDepartment of Computer Science

We might use the files we opened above by copying each username and score from the input file to the output file. In the process, we'll increase each score by 10 points for the output file:

1234567891011

// reading and writing files#include <stdio.h>void main (void){

char username[9]; /* One extra for nul char. */int score;

while (fscanf(ifp, "%s %d", username, &score) != EOF) {fprintf(ofp, "%s %d\n", username, score+10);

}}

After the execution of above code the file out.list will look like

The function fscanf(), like scanf(), normally returns the number of values it was able to read in. However, when it hits the end of the file, it returns the special value EOF. So, testing the return value against EOF is one way to stop the loop.

The bad thing about testing against EOF is that if the file is not in the right format (e.g., a letter is found when a number is expected):

Then fscanf() will not be able to read that line (since there is no integer to read) and it won't advance to the next line in the file. For this error, fscanf() will not return EOF (it's not at the end of the file).

CSC 1102 PROGRAMMING LANGUAGE 1 Page 112 of 137

American International University-BangladeshDepartment of Computer Science

Errors like that will at least mess up how the rest of the file is read. In some cases, they will cause an infinite loop.

One solution is to test against the number of values we expect to be read by fscanf() each time. Since our format is "%s %d", we expect it to read in 2 values, so our condition could be:

while (fscanf(ifp, "%s %d", username, &score) == 2) {...

}

Now, if we get 2 values, the loop continues. If we don't get 2 values, either because we are at the end of the file or some other problem occurred (e.g., it sees a letter when it is trying to read in a number with %d), then the loop will end.

Another way to test for end of file is with the library function feof(). It just takes a file pointer and returns a true/false value based on whether we are at the end of the file.

To use it in the above example, we would do:

12345678910111213

// reading and writing files#include <stdio.h>void main (void){

char username[9]; /* One extra for nul char. */int score;

while (!feof(ifp)) {if (fscanf(ifp, "%s %d", username, &score) != 2)break;fprintf(ofp, "%s %d", username, score+10);

}}

Note that, like testing != EOF, it might cause an infinite loop if the format of the input file was not as expected. However, we can add code to make sure it reads in 2 values (as we've done above).

*** Note: When you use fscanf(...) != EOF or feof(...), they will not detect the end of the file until they try to read past it. In other words, they won't report end-of-file on the last valid read, only on the one after it.

18.2.4. CLOSING A FILE

When done with a file, it must be closed using the function fclose().To finish our example, we'd want to close our input and output files:

fclose(ifp);fclose(ofp);

Closing a file is very important, especially with output files. The reason is that output is often buffered. This means that when you tell C to write something out, e.g.,

CSC 1102 PROGRAMMING LANGUAGE 1 Page 113 of 137

American International University-BangladeshDepartment of Computer Science

fprintf(ofp, "Whatever!\n");

It doesn't necessary get written to disk right away, but may end up in a buffer in memory. This output buffer would hold the text temporarily:

Sample output buffer:

a b c W h a t e v e r !\n

…………

When the buffer fills up (or when the file is closed), the data is finally written to disk.So, if you forget to close an output file then whatever is still in the buffer may not be written out.

*** Note: There are other kinds of buffering than the one we described here.

18.3. SPECIAL FILE POINTERS

There are 3 special FILE*'s that are always defined for a program. They are stdin (standard input), stdout (standard output) and stderr (standard error).

18.3.1. STANDARD INPUT

Standard input is where things come from when you use scanf(). In other words,

scanf("%d", &val);

is equivalent to the following fscanf():

fscanf(stdin, "%d", &val);

18.3.2. STANDARD OUTPUT

Similarly, standard output is exactly where things go when you use printf(). In other words,

printf("Value = %d\n", val);

is equivalent to the following fprintf():fprintf(stdout, "Value = %d\n", val);

*** Remember that standard input is normally associated with the keyboard and standard output with the screen, unless redirection is used.

18.3.3. STANDARD ERROR

Standard error is where you should display error messages. We've already done that above:

fprintf(stderr, "Can't open input file in.list!\n");

Standard error is normally associated with the same place as standard output; however, redirecting standard output does not redirect standard error.

18.4. LABORATORY EXERCISES18.4.1. PROGRAM WRITING

CSC 1102 PROGRAMMING LANGUAGE 1 Page 114 of 137

American International University-BangladeshDepartment of Computer Science

18.4.1.1.Write a program that removes all empty lines (i.e. lines containing only theend-of-line character) from a text file.

Hint: It is easiest just to copy the text file to another text file leaving the empty lines away. Notice the Windows environment, too, i.e. \r\n.

18.4.1.2.Write a program that counts the number of characters and words in a text file. Use the command-line arguments to read the name of the file from a keyboard.

18.4.1.3.Write a function get_file_length(char* filename) that determines and returns the length of a given file. As file length can never be negative, what sort of return value should you use?

18.4.1.4.Write a function char* load_data(char* filename) that returns the contents of a given file. If the load fails, make sure that you free the memory you have allocated for the data.

CSC 1102 PROGRAMMING LANGUAGE 1 Page 115 of 137

American International University-BangladeshDepartment of Computer Science

19. CUSTOM TYPES(I)19.1. OBJECTIVES:To gain experience with – The keywords structand union The concept of Object Designing user defined custom data types Memory utilization using union and bit fields

Writing C programs using –

Structures Unions Bit Fields

19.2. STRUCTURE

C arrays allow us to define type of variables that can hold several data items of the same kind but structure is another user defined data type available in C programming, which allows us to combine data items of different kinds.

Structures are used to represent a record, suppose you want to keep track of your books in a library. You might want to track the following attributes about each book:

Title Author Subject Book ID

We will see how to organize those data into a single frame in the upcoming sections.

19.2.1. DEFINING A STRUCTURE

To define a structure, we need to use the struct statement. The struct statement defines a new data type, with more than one member for your program. The format of the struct statement is this:

struct [structure tag]{ member definition; member definition; ... member definition;}[one or more structure variables];

The structure tag is optional and each member definition is a normal variable definition, such as int i; or float f; or any other valid variable definition. At the end of the structure's definition, before the final semicolon, you can specify one or more structure variables but it is optional. Here is the way you would declare the Book structure:struct Books{char title[50];char author[50];char subject[100];

CSC 1102 PROGRAMMING LANGUAGE 1 Page 116 of 137

American International University-BangladeshDepartment of Computer Science

int book_id;} book;

19.2.2. ACCESSING STRUCTURE MEMBERS

To access any member of a structure, we use the member access operator (.). The member access operator is coded as a period between the structure variable name and the structure member that we wish to access. You would use struct keyword to define variables of structure type. Following is the example to explain usage of structure:

12345678910111213141516171819202122232425262728293031323334353637383940

#include<stdio.h>#include<string.h>

struct Books{char title[50];char author[50];char subject[100];int book_id;};

int main(){struct Books Book1; /* Declare Book1 of type Book */struct Books Book2; /* Declare Book2 of type Book */

/* book 1 specification */ strcpy( Book1.title, "C Programming"); strcpy( Book1.author, "Nuha Ali"); strcpy( Book1.subject, "C Programming Tutorial"); Book1.book_id = 6495407;

/* book 2 specification */ strcpy( Book2.title, "Telecom Billing"); strcpy( Book2.author, "Zara Ali"); strcpy( Book2.subject, "Telecom Billing Tutorial"); Book2.book_id = 6495700;

/* print Book1 info */ printf( "Book 1 title : %s\n", Book1.title); printf( "Book 1 author : %s\n", Book1.author); printf( "Book 1 subject : %s\n", Book1.subject); printf( "Book 1 book_id : %d\n", Book1.book_id);

/* print Book2 info */ printf( "Book 2 title : %s\n", Book2.title); printf( "Book 2 author : %s\n", Book2.author); printf( "Book 2 subject : %s\n", Book2.subject); printf( "Book 2 book_id : %d\n", Book2.book_id);

return 0;}Book 1 title : C ProgrammingBook 1 author : Nuha AliBook 1 subject : C Programming TutorialBook 1 book_id : 6495407

CSC 1102 PROGRAMMING LANGUAGE 1 Page 117 of 137

American International University-BangladeshDepartment of Computer Science

Book 2 title : Telecom BillingBook 2 author : Zara AliBook 2 subject : Telecom Billing TutorialBook 2 book_id : 6495700

19.3. UNION

A union is a special data type available in C that enables you to store different data types in the same memory location. You can define a union with many members, but only one member can contain a value at any given time. Unions provide an efficient way of using the same memory location for multi-purpose.

19.3.1. DEFINING A UNION

To define a union, you must use the union statement in very similar was as you did while defining structure. The union statement defines a new data type, with more than one member for your program. The format of the union statement is as follows:

union [union tag]{ member definition; member definition; ... member definition;} [one or more union variables];

The union tag is optional and each member definition is a normal variable definition, such as int i; or float f; or any other valid variable definition. At the end of the union's definition, before the final semicolon, you can specify one or more union variables but it is optional. Here is the way you would define a union type named Data which has the three members i, f, and str:

union Data{int i;float f;char str[20];} data;

Now, a variable of Data type can store an integer, a floating-point number, or a string of characters. This means that a single variable ie. same memory location can be used to store multiple types of data. You can use any built-in or user defined data types inside a union based on your requirement.

The memory occupied by a union will be large enough to hold the largest member of the union. For example, in above example Data type will occupy 20 bytes of memory space because this is the maximum space which can be occupied by character string. Following is the example which will display total memory size occupied by the above union:

CSC 1102 PROGRAMMING LANGUAGE 1 Page 118 of 137

American International University-BangladeshDepartment of Computer Science

1234567891011121314

#include<stdio.h>#include<string.h>

union Data{int i;float f;char str[20];};

int main(){union Data data; printf( "Memory size occupied by data : %d\n", sizeof(data));return 0;}Memory size occupied by data : 20

19.3.2. ACCESSING UNION MEMBERS

To access any member of a union, we use the member access operator (.). The member access operator is coded as a period between the union variable name and the union member that we wish to access. You would use union keyword to define variables of union type. Following is the example to explain usage of union:

12345678910111213141516171819202122

#include<stdio.h>#include<string.h>

union Data{int i;float f;char str[20];};

int main(){union Data data;

data.i = 10; data.f = 220.5; strcpy( data.str, "C Programming");

printf( "data.i : %d\n", data.i); printf( "data.f : %f\n", data.f); printf( "data.str : %s\n", data.str);

return 0;}data.i : 1917853763data.f : 4122360580327794860452759994368.000000data.str : C Programming

Here, we can see that values of i and f members of union got corrupted because final value assigned to the variable has occupied the memory location and this is the reason that the value if str member is getting printed very well. Now let's look into the same example once again where we will use one variable at a time which is the main purpose of having union:

CSC 1102 PROGRAMMING LANGUAGE 1 Page 119 of 137

American International University-BangladeshDepartment of Computer Science

1234567891011121314151617181920212223

#include<stdio.h>#include<string.h>

union Data{int i;float f;char str[20];};

int main(){union Data data;

data.i = 10; printf( "data.i : %d\n", data.i);

data.f = 220.5; printf( "data.f : %f\n", data.f);

strcpy( data.str, "C Programming"); printf( "data.str : %s\n", data.str);

return 0;}data.i : 10data.f : 220.500000data.str : C Programming

19.4. BIT FIELD

Suppose your C program contains a number of TRUE/FALSE variables grouped in a structure called status, as follows:struct{unsignedint widthValidated;unsignedint heightValidated;} status;

This structure requires 8 bytes of memory space but in actual we are going to store either 0 or 1 in each of the variables. The C programming language offers a better way to utilize the memory space in such situation. If you are using such variables inside a structure then you can define the width of a variable which tells the C compiler that you are going to use only those number of bytes. For example, above structure can be re-written as follows:struct{unsignedint widthValidated : 1;unsignedint heightValidated : 1;} status;

Now, the above structure will require 4 bytes of memory space for status variable but only 2 bits will be used to store the values. If you will use up to 32 variables each one with a width of 1 bit , then also status structure will use 4 bytes, but as soon as you will have 33 variables,

CSC 1102 PROGRAMMING LANGUAGE 1 Page 120 of 137

American International University-BangladeshDepartment of Computer Science

then it will allocate next slot of the memory and it will start using 8 bytes. Let us check the following example to understand the concept:

123456789101112131415161718192021

#include<stdio.h>#include<string.h>

/* define simple structure */struct{unsignedint widthValidated;unsignedint heightValidated;} status1;

/* define a structure with bit fields */struct{unsignedint widthValidated : 1;unsignedint heightValidated : 1;} status2;

int main(){ printf( "Memory size occupied by status1 : %d\n", sizeof(status1)); printf( "Memory size occupied by status2 : %d\n", sizeof(status2));

return 0;}Memory size occupied by status1 : 8Memory size occupied by status2 : 4

19.4.1. BIT FIELD DECLARATION

The declaration of a bit-field has the form inside a structure:struct{ type [member_name] : width ;};

Below the description of variable elements of a bit field:

Elements Description

type An integer type that determines how the bit-field's value is interpreted. The type may be int, signed int, unsigned int.

member_name The name of the bit-field.

width The number of bits in the bit-field. The width must be less than or equal to the bit width of the specified type.

The variables defined with a predefined width are called bit fields. A bit field can hold more than a single bit for example if you need a variable to store a value from 0 to 7 only then you can define a bit field with a width of 3 bits as follows:struct{unsignedint age : 3;} Age;

CSC 1102 PROGRAMMING LANGUAGE 1 Page 121 of 137

American International University-BangladeshDepartment of Computer Science

The above structure definition instructs C compiler that age variable is going to use only 3 bits to store the value; if you will try to use more than 3 bits then it will not allow you to do so. Let us try the following example:

1234567891011121314151617181920

#include<stdio.h>#include<string.h>

struct{unsignedint age : 3;} Age;

int main(){ Age.age = 4; printf( "Sizeof( Age ) : %d\n", sizeof(Age) ); printf( "Age.age : %d\n", Age.age );

Age.age = 7; printf( "Age.age : %d\n", Age.age );

Age.age = 8; printf( "Age.age : %d\n", Age.age );

return 0;}Sizeof( Age ) : 4Age.age : 4Age.age : 7Age.age : 0

19.5. LABORATORY EXERCISES19.5.1. PROGRAM WRITING

19.5.1.1. Write a program that uses a structure Book to hold the Name, Price, Number of pages and Name of publisher of 3 books.

19.5.1.2. Write a program that uses an array of structure Student to hold the Name, ID, Semester, Age, and CGPA of 10 students. Find the average CGPA of the students, the students who are under probation, the students aged more than 21 years and last semester students.

19.5.1.3. Write a program that uses an array of structures to hold the square and cubes of numbers 1 to 10. Display the contents of the array.

20. CUSTOM TYPES (II)20.1. OBJECTIVES:To gain experience with – The usage of structures

CSC 1102 PROGRAMMING LANGUAGE 1 Page 122 of 137

American International University-BangladeshDepartment of Computer Science

20.2. STRUCTURES AS FUNCTION ARGUMENTS

You can pass a structure as a function argument in very similar way as you pass any other variable or pointer. You would access structure variables in the similar way as you have accessed in the above example:

123456789101112131415161718192021222324252627282930313233343536373839404142

#include<stdio.h>#include<string.h>

struct Books{char title[50];char author[50];char subject[100];int book_id;};

/* function declaration */void printBook(struct Books book);int main(){struct Books Book1; /* Declare Book1 of type Book */struct Books Book2; /* Declare Book2 of type Book */

/* book 1 specification */ strcpy( Book1.title, "C Programming"); strcpy( Book1.author, "Nuha Ali"); strcpy( Book1.subject, "C Programming Tutorial"); Book1.book_id = 6495407;

/* book 2 specification */ strcpy( Book2.title, "Telecom Billing"); strcpy( Book2.author, "Zara Ali"); strcpy( Book2.subject, "Telecom Billing Tutorial"); Book2.book_id = 6495700;

/* print Book1 info */ printBook( Book1 );

/* Print Book2 info */ printBook( Book2 );

return 0;}void printBook(struct Books book){ printf( "Book title : %s\n", book.title); printf( "Book author : %s\n", book.author); printf( "Book subject : %s\n", book.subject); printf( "Book book_id : %d\n", book.book_id);}Book title : C ProgrammingBook author : Nuha AliBook subject : C Programming TutorialBook book_id : 6495407Book title : Telecom BillingBook author : Zara Ali

CSC 1102 PROGRAMMING LANGUAGE 1 Page 123 of 137

American International University-BangladeshDepartment of Computer Science

Book subject : Telecom Billing TutorialBook book_id : 6495700

20.3. POINTERS TO STRUCTURES

You can define pointers to structures in very similar way as you define pointer to any other variable as follows:struct Books *struct_pointer;

Now, you can store the address of a structure variable in the above defined pointer variable. To find the address of a structure variable, place the & operator before the structure's name as follows:struct_pointer = &Book1;

To access the members of a structure using a pointer to that structure, you must use the -> operator as follows:struct_pointer->title;

Let us re-write above example using structure pointer, hope this will be easy for you to understand the concept:

123456789101112131415161718192021222324252627282930

#include<stdio.h>#include<string.h>

struct Books{char title[50];char author[50];char subject[100];int book_id;};

/* function declaration */void printBook(struct Books *book);int main(){struct Books Book1; /* Declare Book1 of type Book */struct Books Book2; /* Declare Book2 of type Book */

/* book 1 specification */ strcpy( Book1.title, "C Programming"); strcpy( Book1.author, "Nuha Ali"); strcpy( Book1.subject, "C Programming Tutorial"); Book1.book_id = 6495407;

/* book 2 specification */ strcpy( Book2.title, "Telecom Billing"); strcpy( Book2.author, "Zara Ali"); strcpy( Book2.subject, "Telecom Billing Tutorial"); Book2.book_id = 6495700;

/* print Book1 info by passing address of Book1 */ printBook( &Book1 );

CSC 1102 PROGRAMMING LANGUAGE 1 Page 124 of 137

American International University-BangladeshDepartment of Computer Science

3132333435363738394041

/* print Book2 info by passing address of Book2 */ printBook( &Book2 );

return 0;}void printBook(struct Books *book){ printf( "Book title : %s\n", book->title); printf( "Book author : %s\n", book->author); printf( "Book subject : %s\n", book->subject); printf( "Book book_id : %d\n", book->book_id);}Book title : C ProgrammingBook author : Nuha AliBook subject : C Programming TutorialBook book_id : 6495407Book title : Telecom BillingBook author : Zara AliBook subject : Telecom Billing TutorialBook book_id : 6495700

20.4. THE typedef KEYWORD

The C programming language provides a keyword called typedef, which you can use to give a type a new name. Following is an example to define a term BYTE for one-byte numbers:

typedefunsignedchar BYTE;After this type definitions, the identifier BYTE can be used as an abbreviation for the type unsigned char, for example:

BYTE b1, b2;By convention, uppercase letters are used for these definitions to remind the user that the type name is really a symbolic abbreviation, but you can use lowercase, as follows:

typedefunsignedchar byte;You can use typedef to give a name to user defined data type as well. For example you can use typedef with structure to define a new data type and then use that data type to define structure variables directly as follows:

12345678910111213

#include<stdio.h>#include<string.h>

typedefstruct Books{char title[50];char author[50];char subject[100];int book_id;} Book;

int main(){ Book book;

CSC 1102 PROGRAMMING LANGUAGE 1 Page 125 of 137

American International University-BangladeshDepartment of Computer Science

141516171819202122232425

strcpy( book.title, "C Programming"); strcpy( book.author, "Nuha Ali"); strcpy( book.subject, "C Programming Tutorial"); book.book_id = 6495407;

printf( "Book title : %s\n", book.title); printf( "Book author : %s\n", book.author); printf( "Book subject : %s\n", book.subject); printf( "Book book_id : %d\n", book.book_id);

return 0;}Book title : C ProgrammingBook author : Nuha AliBook subject : C Programming TutorialBook book_id : 6495407

20.4.1. typedefVS #define

The #define is a C-directive which is also used to define the aliases for various data types similar to typedef but with following differences:

The typedef is limited to giving symbolic names to types only whereas #define can be used to define alias for values as well, like you can define 1 as ONE etc.

The typedef interpretation is performed by the compiler whereas #define statements are processed by the pre-processor.

Following is a simplest usage of #define:

1234567891011

#include<stdio.h>

#define TRUE 1#define FALSE 0

int main(){ printf( "Value of TRUE : %d\n", TRUE); printf( "Value of FALSE : %d\n", FALSE);

return 0;}Value of TRUE : 1Value of FALSE : 0

20.5. NESTED STRUCTURE

Structure written inside another structure is called as nesting of two structures. We can write one Structure inside another structure as member of another structure. This can be done in two ways:

Way 1: Declare two separate structures

CSC 1102 PROGRAMMING LANGUAGE 1 Page 126 of 137

American International University-BangladeshDepartment of Computer Science

struct date{int date;int month;int year; };

struct Employee{char ename[20];int ssn;float salary;struct date doj;}emp1;

Way 2: Declare embedded structuresstruct Employee{char ename[20];int ssn;float salary;struct date{int date;int month;int year; }doj;}emp1;

20.5.1. ACCESSING NESTED MEMBERS :

Structure members are accessed using dot operator. ‘date’ structure is nested within Employee Structure. Members of the ‘date’ can be accessed using ’employee’. emp1 & doj are two structure names (Variables)

emp1.doj.month emp1.doj.dayemp1.doj.year

Here is a complete example of how to access the members of nested structure:

123456789101112131415

#include<stdio.h>

struct Employee{char ename[20];int ssn;float salary;struct date{int date;int month;int year; }doj;}emp = {"John",1000,1000.50,{22,6,1990}};

int main(){printf("\nEmployee Name : %s",emp.ename);

CSC 1102 PROGRAMMING LANGUAGE 1 Page 127 of 137

American International University-BangladeshDepartment of Computer Science

161718192021222324

printf("\nEmployee SSN : %d",emp.ssn); printf("\nEmployee Salary : %f",emp.salary); printf("\nEmployee DOJ :");printf(" %d", emp.doj.date);printf(" /%d", emp.doj.month);printf(" /%d", emp.doj.year);

return 0;}Employee Name : JohnEmployee SSN : 1000Employee Salary : 1000.500000Employee DOJ : 22/6/1990

20.6. BINARY I/O FUNCTIONS

There are following two functions, which can be used for binary input and output:size_t fread(void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file); size_t fwrite(constvoid *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file);

Both of these functions should be used to read or write blocks of memories - usually arrays or structures.

20.7. LABORATORY EXERCISES20.7.1. PROGRAM WRITING

20.7.1.1.//TODO

20.7.1.2.

20.7.1.3.

20.7.1.4.

CSC 1102 PROGRAMMING LANGUAGE 1 Page 128 of 137

American International University-BangladeshDepartment of Computer Science

21. OOP21.1. OBJECTIVES:To gain experience with – The philosophy of OOP OOP features and terminology

Writing C programs using –

class

21.2. THE PHILOSOPHY OF OOP

OOP is a design philosophy. It stands for Object Oriented Programming. Object-Oriented Programming (OOP) uses a different set of programming languages than old procedural programming languages (C, Pascal, etc.). Everything in OOP is grouped as self-sustainable "objects". Hence, you gain reusability by means of four main object-oriented programming concepts.

In order to clearly understand the object orientation model, let’s take your “hand” as an example. The “hand” is a class. Your body has two objects of the type "hand", named "left hand" and "right hand". Their main functions are controlled or managed by a set of electrical signals sent through your shoulders (through an interface). So the shoulder is an interface that your body uses to interact with your hands. The hand is a well-architected class. The hand is being reused to create the left hand and the right hand by slightly changing the properties of it.

21.2.1. WHAT IS AN OBJECT?

An object can be considered a "thing" that can perform a set of related activities. The set of activities that the object performs defines the object's behavior. For example, the Hand (object) can grip something, or a Student (object) can give their name or address.

In pure OOP terms an object is an instance of a class.

21.2.2. WHAT IS A CLASS?

A class is simply a representation of a type of object. It is the blueprint, or plan, or template that describes the details of an object. A class is the blueprint from which the individual objects are created. Class is composed of three things: a name, attributes, and operations.

In real world, you'll often find many individual objects all of the same kind. As an example, there may be thousands of other bicycles in existence, all of the same make and model. Each bicycle has built from the same blueprint. In object-oriented terms, we say that the bicycle is an instance of the class of objects known as bicycles.

21.2.3. OOP PRINCIPLES

A software system may consist of many classes. When you have many classes, it needs to be managed. Think of a big organization, with its work force exceeding several thousand employees (let’s take one employee as one class). In order to manage such a work force, you

CSC 1102 PROGRAMMING LANGUAGE 1 Page 129 of 137

American International University-BangladeshDepartment of Computer Science

need to have proper management policies in place. Same technique can be applied to manage classes of your software system. In order to manage the classes of a software system, and to reduce the complexity, system designers use several techniques, which can be grouped under four main concepts named

a. Encapsulationb. Abstractionc. Inheritanced. Polymorphism.

These concepts are the four main gods of OOP world and in software term, they are called four main Object Oriented Programming (OOP) Concepts.

21.3. C++ CLASS AND OBJECT

A class is used to specify the form of an object and it combines data representation and methods for manipulating that data into one neat package. The data and functions within a class are called members of the class.

21.3.1. CLASS DEFINITIONS

When you define a class, you define a blueprint for a data type. This doesn't actually define any data, but it does define what the class name means, that is, what an object of the class will consist of and what operations can be performed on such an object.

A class definition starts with the keyword class followed by the class name; and the class body, enclosed by a pair of curly braces. A class definition must be followed either by a semicolon or a list of declarations. For example, we defined the Box data type using the keyword class as follows:

class Box{public:double length; // Length of a boxdouble breadth; // Breadth of a boxdouble height; // Height of a box};

The keyword public determines the access attributes of the members of the class that follow it. A public member can be accessed from outside the class anywhere within the scope of the class object. You can also specify the members of a class as private or protected which we will discuss in a sub-section.

21.3.2. DEFINE OBJECTS

A class provides the blueprints for objects, so basically an object is created from a class. We declare objects of a class with exactly the same sort of declaration that we declare variables of basic types. Following statements declare two objects of class Box:

CSC 1102 PROGRAMMING LANGUAGE 1 Page 130 of 137

American International University-BangladeshDepartment of Computer Science

Box Box1; // Declare Box1 of type BoxBox Box2; // Declare Box2 of type Box

Both of the objects Box1 and Box2 will have their own copy of data members.

21.3.3. ACCESSING THE DATA MEMBERS

The public data members of objects of a class can be accessed using the direct member access operator (.). Let us try the following example to make the things clear:

1234567891011121314151617181920212223242526272829303132

#include<stdio.h>

class Box{public:double length; // Length of a boxdouble breadth; // Breadth of a boxdouble height; // Height of a box};

int main(){ Box Box1; // Declare Box1 of type Box Box Box2; // Declare Box2 of type Boxdouble volume = 0.0; // Store the volume of a box here

// box 1 specification Box1.height = 5.0; Box1.length = 6.0; Box1.breadth = 7.0;

// box 2 specification Box2.height = 10.0; Box2.length = 12.0; Box2.breadth = 13.0;// volume of box 1 volume = Box1.height * Box1.length * Box1.breadth; printf("Volume of Box1 : %lg\n", volume);

// volume of box 2 volume = Box2.height * Box2.length * Box2.breadth; printf("Volume of Box2 : %lg\n", volume);return 0;}Volume of Box1 : 210Volume of Box2 : 1560

It is important to note that private and protected members cannot be accessed directly using direct member access operator (.). We will learn how private and protected members can be accessed.

21.3.4. CLASS MEMBER FUNCTIONS

CSC 1102 PROGRAMMING LANGUAGE 1 Page 131 of 137

American International University-BangladeshDepartment of Computer Science

A member function of a class is a function that has its definition or its prototype within the class definition like any other variable. It operates on any object of the class of which it is a member, and has access to all the members of a class for that object.

Let us take previously defined class to access the members of the class using a member function instead of directly accessing them:

class Box{public:double length; // Length of a boxdouble breadth; // Breadth of a boxdouble height; // Height of a boxdouble getVolume(void);// Returns box volume};

Member functions can be defined within the class definition or separately using scope resolution operator, ::. Defining a member function within the class definition declares the function inline, even if you do not use the inline specifier. So either you can define Volume() function as below:

class Box{public:double length; // Length of a boxdouble breadth; // Breadth of a boxdouble height; // Height of a box

double getVolume(void){return length * breadth * height; }};

If you like you can define same function outside the class using scope resolution operator, :: as follows:

double Box::getVolume(void){return length * breadth * height;}

Here, only important point is that you would have to use class name just before :: operator. A member function will be called using a dot operator (.) on a object where it will manipulate data related to that object only as follows:

Box myBox; // Create an objectmyBox.getVolume(); // Call member function for the object

Let us put above concepts to set and get the value of different class members in a class:

123456789

#include<stdio.h>

class Box{public:double length; // Length of a boxdouble breadth; // Breadth of a boxdouble height; // Height of a box

// Member functions declaration

CSC 1102 PROGRAMMING LANGUAGE 1 Page 132 of 137

American International University-BangladeshDepartment of Computer Science

10111213141516171819202122232425262728293031323334353637383940414243444546474849505152

double getVolume(void);void setLength( double len );void setBreadth( double bre );void setHeight( double hei );};// Member functions definitionsdouble Box::getVolume(void){return length * breadth * height;}void Box::setLength(double len){ length = len;}void Box::setBreadth(double bre){ breadth = bre;}void Box::setHeight(double hei){ height = hei;}// Main function for the programint main(){ Box Box1; // Declare Box1 of type Box Box Box2; // Declare Box2 of type Boxdouble volume = 0.0; // Store the volume of a box here

// box 1 specification Box1.setLength(6.0); Box1.setBreadth(7.0); Box1.setHeight(5.0);

// box 2 specification Box2.setLength(12.0); Box2.setBreadth(13.0); Box2.setHeight(10.0);

// volume of box 1 volume = Box1.getVolume(); printf("Volume of Box1 : %lg\n", volume);

// volume of box 2 volume = Box2.getVolume(); printf("Volume of Box2 : %lg\n", volume);return 0;}Volume of Box1 : 210Volume of Box2 : 1560

21.3.5. CLASS ACCESS MODIFIERS

Data hiding is one of the important features of Object Oriented Programming which allows preventing the functions of a program to access directly the internal representation of a class type. The access restriction to the class members is specified by the labeled public, private,andprotected sections within the class body. The keywords public, private, and protected are called access specifiers.

CSC 1102 PROGRAMMING LANGUAGE 1 Page 133 of 137

American International University-BangladeshDepartment of Computer Science

A class can have multiple public, protected, or private labeled sections. Each section remains in effect until either another section label or the closing right brace of the class body is seen. The default access for members and classes is private.

class Base{ public: // public members go here

protected: // protected members go here

private: // private members go here

};

21.3.5.1. THE publicMEMBERS

A public member is accessible from anywhere outside the class but within a program. You can set and get the value of public variables without any member function as shown in the following example:

12345678910111213141516171819202122232425262728293031

#include<stdio.h>

class Line{public:double length;void setLength( double len );double getLength( void );};

// Member functions definitionsdouble Line::getLength(void){return length ;}

void Line::setLength(double len){ length = len;}

// Main function for the programint main(){ Line line;

// set line length line.setLength(6.0); printf("Length of line : %lg\n", line.getLength());

// set line length without member function line.length = 10.0; // OK: because length is public printf("Length of line : %lg\n", line.length);return 0;}Length of line : 6

CSC 1102 PROGRAMMING LANGUAGE 1 Page 134 of 137

American International University-BangladeshDepartment of Computer Science

Length of line : 10

21.3.5.2. THE privateMEMBERS

A private member variable or function cannot be accessed, or even viewed from outside the class. Only the class and friend functions can access private members.

By default all the members of a class would be private, for example in the following class width is a private member, which means until you label a member, it will be assumed a private member:

class Box{double width;public:double length;void setWidth( double wid );double getWidth( void );};

Practically, we define data in private section and related functions in public section so that they can be called from outside of the class as shown in the following program.

1234567891011121314151617181920212223242526272829303132

#include<stdio.h>

class Box{public:double length;void setWidth( double wid );double getWidth( void );private:double width;};// Member functions definitionsdouble Box::getWidth(void){return width ;}void Box::setWidth(double wid){ width = wid;}// Main function for the programint main(){ Box box;

// set box length without member function box.length = 10.0; // OK: because length is public printf("Length of box : %lg\n", box.length);

// set box width without member function// box.width = 10.0; // Error: because width is privatebox.setWidth(10.0); // Use member function to set it. printf("Width of box : %lg\n", box.getWidth());

return 0;}Length of box : 10

CSC 1102 PROGRAMMING LANGUAGE 1 Page 135 of 137

American International University-BangladeshDepartment of Computer Science

Width of box : 10

21.3.5.3. THE protectedMEMBERS

A protected member variable or function is very similar to a private member but it provided one additional benefit that they can be accessed in child classes which are called derived classes.

You will learn derived classes and inheritance in upcoming courses (PL2, OOP1, OOP2 etc.).

21.4. LABORATORY EXERCISES21.4.1. PROGRAM WRITING

21.4.1.1.//TODO

21.4.1.2.

21.4.1.3.

21.4.1.4.

CSC 1102 PROGRAMMING LANGUAGE 1 Page 136 of 137

American International University-BangladeshDepartment of Computer Science

Acknowledgements:1. www.tutorialspoint.com 2. http://www.codeproject.com/Articles/22769/Introduction-to-Object-Oriented-

Programming-Concep3. https://www.cs.bu.edu/teaching/c/file-io/intro/

CSC 1102 PROGRAMMING LANGUAGE 1 Page 137 of 137