Lab Manual Programming Fundamental PDF
Document Details
Uploaded by DelightedVuvuzela1703
GSCWU BWP
Ms Sidra Khalid
Tags
Related
Summary
This document is a lab manual for programming fundamentals, focusing on C++. It covers installation, basic concepts, and working of programs, potentially suited for an introductory computer science course.
Full Transcript
Lab Manual Programming Fundamental Ms Sidra Khalid GSCWU BWP Lab Manual Contents Week 01: Installation & overview................................................................................................................. 6 Wh...
Lab Manual Programming Fundamental Ms Sidra Khalid GSCWU BWP Lab Manual Contents Week 01: Installation & overview................................................................................................................. 6 What is programming?............................................................................................................................. 6 What is computer language?.................................................................................................................... 6 Installation Of IDE.................................................................................................................................... 7 Download and Install Code Blocks C & C++ IDE on Windows 10.............................................................. 7 How to install Code Blocks........................................................................................................................ 7 Installation Steps....................................................................................................................................... 8 C++ Introduction.................................................................................................................................... 15 Week 02: Introduction to problem solving & variables & Keywords......................................................... 17 Introduction to Algorithm....................................................................................................................... 17 C++ Variables, Literals and Constants..................................................................................................... 18 C++ Variables........................................................................................................................................... 18 C++ Literals.............................................................................................................................................. 19 C++ Constants......................................................................................................................................... 21 Week 03: Data Types & Comments............................................................................................................ 22 C++ Data Types........................................................................................................................................ 22 C++ Type Modifiers................................................................................................................................. 24 C++ Comments........................................................................................................................................ 25 Week 04: Basic Structure of program &Working of program.................................................................... 26 Structure of a Program/Syntax............................................................................................................... 26 How does Program work........................................................................................................................ 27 C++ Basic Input/Output........................................................................................................................... 28 Example for C++ Output.......................................................................................................................... 29 Example for C++ Input............................................................................................................................. 30 Examples................................................................................................................................................. 31 Lab Manual Programming Fundamental By Ms Sidra Khalid Page 2 Practice Questions.................................................................................................................................. 32 Week 05: Operators & Directives............................................................................................................... 32 Operators in C++..................................................................................................................................... 32 Relational Operator................................................................................................................................ 33 Logical Operator...................................................................................................................................... 34 Increment and Decrement Operators.................................................................................................... 35 Practice Questions With Solution........................................................................................................... 36 Practice Question Home Task................................................................................................................. 39 Week 06: Flow Control............................................................................................................................... 40 Decisions................................................................................................................................................. 40 Forms of if-else statement in C++........................................................................................................... 40 C++ if Statement................................................................................................................................. 40 C++ if...else Statement....................................................................................................................... 41 C++ if...else...else if statement............................................................................................................ 43 C++ Nested if...else............................................................................................................................. 44 Practice Questions.................................................................................................................................. 46 Practice Question If-Else......................................................................................................................... 46 Week 07: Loops.......................................................................................................................................... 48 Introduction to Loops............................................................................................................................. 48 For Loop.................................................................................................................................................. 48 While Loops............................................................................................................................................. 49 Do-While Loop........................................................................................................................................ 50 Examples:................................................................................................................................................ 51 Practice Question.................................................................................................................................... 56 Week 08: Break &Continue & Switch Statement & GOTO Statement....................................................... 56 C++ break Statement.............................................................................................................................. 56 C++ continue Statement......................................................................................................................... 57 C++ Switch..Case Statement................................................................................................................... 58 GOTO Statement.................................................................................................................................... 61 Week 09: C++ Functions............................................................................................................................. 63 Functions................................................................................................................................................. 63 Types of function.................................................................................................................................... 63 Lab Manual Programming Fundamental By Ms Sidra Khalid Page 3 C++ User-defined Function..................................................................................................................... 63 C++ Function Declaration.................................................................................................................... 64 Calling a Function.................................................................................................................................... 64 Examples................................................................................................................................................. 65 Function Parameters............................................................................................................................... 66 Return Statement................................................................................................................................... 67 Function Prototype................................................................................................................................. 69 Benefits of Using User-Defined Functions.............................................................................................. 71 C++ Library Functions.............................................................................................................................. 71 Week 10: C++ User define Function Types & Overloading......................................................................... 72 User-defined Function Types.................................................................................................................. 72 Examples:................................................................................................................................................ 73 Which method is better?........................................................................................................................ 77 Overloading............................................................................................................................................. 77 C++ Function Overloading................................................................................................................... 77 Examples:................................................................................................................................................ 78 Week 11: C++Default Arguments, Storage Class and Recursion................................................................ 81 C++ Programming Default Arguments (Parameters).............................................................................. 81 Example: Default Argument................................................................................................................ 83 C++ Storage Class.................................................................................................................................... 86 Local Variable.......................................................................................................................................... 86 Example 1: Local variable.................................................................................................................... 86 Global Variable........................................................................................................................................ 87 Example 2: Global variable.................................................................................................................. 87 Static Local variable................................................................................................................................ 88 Example 3: Static local variable........................................................................................................... 89 C++ Recursion......................................................................................................................................... 90 Week 12: C++ Return Reference, Strings.................................................................................................... 94 C++ Return by Reference........................................................................................................................ 94 Example: Return by Reference............................................................................................................... 94 C++ Strings.............................................................................................................................................. 95 C - Strings................................................................................................................................................ 95 Lab Manual Programming Fundamental By Ms Sidra Khalid Page 4 String Object........................................................................................................................................... 97 Passing String to a Function.................................................................................................................... 98 C++ Stack................................................................................................................................................. 99 Create a Stack....................................................................................................................................... 100 Example: C++ STL Stack................................................................................................................. 100 Stack Methods....................................................................................................................................... 101 Week 13: Arrays, Multidimensional array, Function and array................................................................ 109 C++ Arrays............................................................................................................................................. 109 C++ Array Declaration....................................................................................................................... 109 Access Elements in C++ Array........................................................................................................... 109 C++ Array Initialization...................................................................................................................... 110 C++ Array With Empty Members...................................................................................................... 110 Examples............................................................................................................................................... 112 C++ Multidimensional Arrays................................................................................................................ 115 Multidimensional Array Initialization................................................................................................... 116 Example................................................................................................................................................. 117 Example 3: Three Dimensional Array............................................................................................. 119 Passing Array to a Function in C++ Programming................................................................................. 121 Examples............................................................................................................................................... 121 Week 14: Pointers, Pointers and arrays, Pointer and function................................................................ 124 C++ Pointers.......................................................................................................................................... 124 Address in C++................................................................................................................................... 124 Assigning Addresses to Pointers....................................................................................................... 126 C++ Pointers and Arrays........................................................................................................................ 129 Example 1: C++ Pointers and Arrays..................................................................................................... 131 C++ Call by Reference: Using pointers.................................................................................................. 132 Week 15: Memory Management and File................................................................................................ 136 C++ Memory Management: new and delete........................................................................................ 136 C++ new Operator................................................................................................................................. 136 Delete Operator.................................................................................................................................... 137 Examples:.............................................................................................................................................. 138 C++ File Handling.................................................................................................................................... 140 Lab Manual Programming Fundamental By Ms Sidra Khalid Page 5 Read From a File............................................................................................................................... 143 Write to a File................................................................................................................................... 145 Append to a Text File....................................................................................................................... 147 File Handling With fstream............................................................................................................... 149 Week 16 : Revision, Presentation and Quiz.............................................................................................. 151 Week 01: Installation & overview What is programming? Programming is the process of creating sets of instructions that tell a computer what to do. It involves writing code in a programming language to solve problems or automate tasks. Key Elements of Programming Instructions: Creating step-by-step instructions to guide the computer's actions. Language: Using a programming language to communicate with the computer. Problem Solving: Analyzing problems and designing solutions using logical thinking. Programming Languages Definition: Programming languages are formal languages designed to communicate instructions to a computer. Examples: Python, Java, C++, Kotlin What is computer language? The computer language is defined as code or syntax which is used to write programs. Low level language Machine Language Assembly Language High Level Language C, C++, java, C# etc Language processors: Lab Manual Programming Fundamental By Ms Sidra Khalid Page 6 Assembler Compiler Interpreter Assembler converts program written in assembly language into machine language. Compilers and interpreters are program that help convert the high-level language into machine code. Compiler Vs Interpreter Compiler convert the whole high level language program to machine language at a time while Interpreter converts high level language program to machine language line by line. C++ Compiler: GCC stands for GNU Compilers Collections is used to compile mainly C and C++ language. Installation Of IDE Download and Install Code Blocks C & C++ IDE on Windows 10 Code Blocks is a free and cross platform IDE for C, C++, and Fortran. Here is the list of features available in Code Blocks IDE – How to install Code Blocks Download the latest version of Code Blocks for your Operating System from here http://www.codeblocks.org/downloads 'OR' You can also download the latest version for Windows directly from the following download button if the above method doesn't work - DOWNLOAD CODE BLOCKS Run the downloaded.exe file to install Code Blocks in your system. Follow the setup instructions. You can watch the following video to check how to download and install Code Blocks IDE for Windows – https://www.youtube.com/watch?v=eXx2bmHm7ZQ Lab Manual Programming Fundamental By Ms Sidra Khalid Page 7 Installation Steps Lab Manual Programming Fundamental By Ms Sidra Khalid Page 8 Lab Manual Programming Fundamental By Ms Sidra Khalid Page 9 Lab Manual Programming Fundamental By Ms Sidra Khalid Page 10 Lab Manual Programming Fundamental By Ms Sidra Khalid Page 11 Lab Manual Programming Fundamental By Ms Sidra Khalid Page 12 Lab Manual Programming Fundamental By Ms Sidra Khalid Page 13 Lab Manual Programming Fundamental By Ms Sidra Khalid Page 14 C++ Introduction What is C++? C++ is a cross-platform language that can be used to create high-performance applications. C++ was developed by Bjarne Stroustrup, as an extension to the C language. C++ gives programmers a high level of control over system resources and memory. The language was updated 4 major times in 2011, 2014, 2017, and 2020 to C++11, C++14, C++17, C++20. Why Use C++ C++ is one of the world's most popular programming languages. C++ can be found in today's operating systems, Graphical User Interfaces, and embedded systems. C++ is an object-oriented programming language which gives a clear structure to programs and allows code to be reused, lowering development costs. C++ is portable and can be used to develop applications that can be adapted to multiple platforms. C++ is fun and easy to learn! As C++ is close to C, C# and Java, it makes it easy for programmers to switch to C++ or vice versa. Difference between C and C++ C++ was developed as an extension of C, and both languages have almost the same syntax. The main difference between C and C++ is that C++ support classes and objects, while C does not. C++ Quickstart Let's create our first C++ file. Open Codeblocks and go to File > New > Empty File. Lab Manual Programming Fundamental By Ms Sidra Khalid Page 15 Write the following C++ code and save the file as myfirstprogram.cpp (File > Save File as): myfirstprogram.cpp #include using namespace std; int main() { cout Build and Run to run (execute) the program. The result will look something to this: Output: Hello World! Process returned 0 (0x0) execution time : 0.011 s Press any key to continue. Congratulations! You have now written and executed your first C++ program. Lab Manual Programming Fundamental By Ms Sidra Khalid Page 16 Week 02: Introduction to problem solving & variables & Keywords Introduction to Algorithm Algorithm:- It is a method of representing the step by step process for solving a problem. Each step is called an instruction. What are the Characteristics of an Algorithm? Example 01 Write a C++ algorithm to write a program to add two numbers. Algorithm Steps are given below: Lab Manual Programming Fundamental By Ms Sidra Khalid Page 17 Start Accept num1, num 2 Sum= num1+ num2 Display sum Stop Example 02 C++ Variables, Literals and Constants C++ Variables In programming, a variable is a container (storage area) to hold data. To indicate the storage area, each variable should be given a unique name (identifier). For example, int age = 14; Here, age is a variable of the int data type, and we have assigned an integer value 14 to it. Note: The int data type suggests that the variable can only hold integers. Similarly, we can use the double data type if we have to store decimals and exponentials. We will learn about all the data types in detail in the next tutorial. Lab Manual Programming Fundamental By Ms Sidra Khalid Page 18 The value of a variable can be changed, hence the name variable. int age = 14; // age is 14 age = 17; // age is 17 Rules for naming a variable A variable name can only have alphabets, numbers, and the underscore _. A variable name cannot begin with a number. It is a preferred practice to begin variable names with a lowercase character. For example, name is preferable to Name. A variable name cannot be a keyword. For example, int is a keyword that is used to denote integers. A variable name can start with an underscore. However, it's not considered a good practice. Note: We should try to give meaningful names to variables. For example, first_name is a better variable name than fn. C++ Literals Literals are data used for representing fixed values. They can be used directly in the code. For example: 1, 2.5, 'c' etc. Here, 1, 2.5 and 'c' are literals. Why? You cannot assign different values to these terms. Here's a list of different literals in C++ programming. 1. Integers An integer is a numeric literal(associated with numbers) without any fractional or exponential part. There are three types of integer literals in C programming: decimal (base 10) octal (base 8) Lab Manual Programming Fundamental By Ms Sidra Khalid Page 19 hexadecimal (base 16) For example: Decimal: 0, -9, 22 etc Octal: 021, 077, 033 etc Hexadecimal: 0x7f, 0x2a, 0x521 etc In C++ programming, octal starts with a 0, and hexadecimal starts with a 0x. 2. Floating-point Literals A floating-point literal is a numeric literal that has either a fractional form or an exponent form. For example: -2.0 0.0000234 -0.22E-5 Note: E-5 = 10-5 3. Characters A character literal is created by enclosing a single character inside single quotation marks. For example: 'a', 'm', 'F', '2', '}' etc. 4. Escape Sequences Sometimes, it is necessary to use characters that cannot be typed or has special meaning in C++ programming. For example, newline (enter), tab, question mark, etc. In order to use these characters, escape sequences are used. Escape Sequences Characters \b Backspace Lab Manual Programming Fundamental By Ms Sidra Khalid Page 20 \f Form feed \n Newline \r Return \t Horizontal tab \v Vertical tab \\ Backslash \' Single quotation mark \" Double quotation mark \? Question mark \0 Null Character 5. String Literals "good" string constant "" null string constant "" string constant of six white space "x" string constant having a single character "Earth is round\n" prints string with a newline A string literal is a sequence of characters enclosed in double-quote marks. For example: C++ Constants In C++, we can create variables whose value cannot be changed. For that, we use the const keyword. Here's an example: const int LIGHT_SPEED = 299792458; LIGHT_SPEED = 2500 // Error! LIGHT_SPEED is a constant. Here, we have used the keyword const to declare a constant named LIGHT_SPEED. If we try to change the value of LIGHT_SPEED, we will get an error. Lab Manual Programming Fundamental By Ms Sidra Khalid Page 21 A constant can also be created using the #define preprocessor directive. We will learn about it in detail in the C++ Macros tutorial. Week 03: Data Types & Comments C++ Data Types In C++, data types are declarations for variables. This determines the type and size of data associated with variables. For example, int age = 13; Here, age is a variable of type int. Meaning, the variable can only store integers of either 2 or 4 bytes. C++ Fundamental Data Types The table below shows the fundamental data types, their meaning, and their sizes (in bytes): Data Type Meaning Size (in Bytes) Int Integer 2 or 4 Float Floating-point 4 Double Double Floating-point 8 char Character 1 wchar_t Wide Character 2 bool Boolean 1 void Empty 0 Now, let us discuss these fundamental data types in more detail. 1. C++ int The int keyword is used to indicate integers. Its size is usually 4 bytes. Meaning, it can store values from -2147483648 to 2147483647. Lab Manual Programming Fundamental By Ms Sidra Khalid Page 22 For example, int salary = 85000; 2. C++ float and double float and double are used to store floating-point numbers (decimals and exponentials). The size of float is 4 bytes and the size of double is 8 bytes. Hence, double has two times the precision of float. To learn more, visit C++ float and double. For example, float area = 64.74; double volume = 134.64534; As mentioned above, these two data types are also used for exponentials. For example, double distance = 45E12 // 45E12 is equal to 45*10^12 3. C++ char Keyword char is used for characters. Its size is 1 byte. Characters in C++ are enclosed inside single quotes ' '. For example, char test = 'h'; 4. C++ wchar_t Wide character wchar_t is similar to the char data type, except its size is 2 bytes instead of 1. It is used to represent characters that require more memory to represent them than a single char. Lab Manual Programming Fundamental By Ms Sidra Khalid Page 23 For example, wchar_t test = L' 'ם// storing Hebrew character; Notice the letter L before the quotation marks. 5. C++ bool The bool data type has one of two possible values: true or false. Booleans are used in conditional statements and loops (which we will learn in later chapters). For example, bool cond = false; 6. C++ void The void keyword indicates an absence of data. It means "nothing" or "no value". We will use void when we learn about functions and pointers. Note: We cannot declare variables of the void type. C++ Type Modifiers We can further modify some of the fundamental data types by using type modifiers. There are 4 type modifiers in C++. They are: 1. signed 2. unsigned 3. short 4. long We can modify the following data types with the above modifiers: Lab Manual Programming Fundamental By Ms Sidra Khalid Page 24 int double char C++ Modified Data Types List Data Type Size (in Meaning Bytes) signed int 4 used for integers (equivalent to int) unsigned int 4 can only store positive integers Short 2 used for small integers (range -32768 to 32767) unsigned short 2 used for small positive integers (range 0 to 65,535) Long at least 4 used for large integers (equivalent to long int) unsigned long 4 used for large positive integers or 0 (equivalent to unsigned long int) long long 8 used for very large integers (equivalent to long long int). unsigned long 8 used for very large positive integers or 0 (equivalent to unsigned long long long int) long double 12 used for large floating-point numbers signed char 1 used for characters (guaranteed range -127 to 127) unsigned char 1 used for characters (range 0 to 255) Let's see a few examples. long b = 4523232; long int c = 2345342; long double d = 233434.56343; short d = 3434233; // Error! out of range unsigned int a = -5; // Error! can only store positive numbers or 0 C++ Comments Comments can be used to explain C++ code, and to make it more readable. It can also be used to prevent execution when testing alternative code. Comments can Lab Manual Programming Fundamental By Ms Sidra Khalid Page 25 be singled-lined or multi-lined. Single-line Comments Single-line comments start with two forward slashes (//). Any text between // and the end of the line is ignored by the compiler (will not be executed). This example uses a single-line comment before a line of code: Example // This is a comment cout age; cout