You are on page 1of 96
Computer Programming Learning Outcomes Bite oneal CMe =) ae} Computer Ldgey=te- Tenant =§ Ceara E CMe mee ee Te) Cet Tce nila lp Tay Instruction: detailed information about how something should be done or operated, End user is. person or other entity who uses the product. Encompassing: completaly encloses or surrounds something alse. Tangible: able to touching. noticed by Google Play In previous chapters, we have discussed how a computer is very good at following instructions. The collection of instructions a computer executes to perform a specific task is called a program. If any program is designed for the end user to perform a specific task or achieve a specific purpose is called an application. Applications are often created with a user interface that allows users to interoct with the program, providing input and receiving output. Examples of applications include word processors, spreadsheets, web browsers, and media players. All applications are programs but not all programs are applications. for example, there are thousands of programs running in the background of your operating system such as programs that manage network connections, since they are not developed for the end user, they are not applications. The term software also gets confused with the terms program and application. you will encounter people saying a video player software, a document processing software, or an operating system software. Software is an all-encompassing term that is used to describe any part of a computer that is not tangible (hardware). All programs and applications are types of software. But for a computer to run certain instructions, the instructions must be first given by a human being. Without a set of instructions, a computer has nothing todo. As you remember in previous chapters computer understands only ones and zeroes. People used to write different programs by using ones and zeroes, but Microsoft Store Ubuntu Software gs these instructions grow, it becomes very difficult to ema ae alia Subject vocabulary Machine code is 2 collection of Instructions that are used to control a computer’s CPU. Each instruction causes the CPU to perform a very specific task. Cerenrce Nee tT Tay Logic: fs 2 set of underlying arrengements to perform a specified task Itinvolves identifying the structure of aproblem, breaking it down into simpler components, and designing algorithms or programs to solveit Titres a bug isan error, fault, orflaw inary computer program. debug | debugging is 2 mul process that involves identifying a step problem, isolating the source code ‘of the problem and then either correcting the problem or determining away to werk around it, successfully write, read and debug them. So, people created two major things 1. A human-readable language to write the instructions and 2. A program that changes these human-readable instructions to a machine code. These are called programming languages. A technical person who uses human-readable languages @ particular programming language to implement the program logic is called a Coder. The act ot this, technical person is called Coding. But before coding the logic must be created by using critical thinking skills and solving logical problems. The creation of logic and the process of developing fully functioning software is called Programming. Coding is a part of programming. Programming is a broader term that encompasses the entire process of designing, writing, testing, and maintaining computer programs. Programming involves not only writing code, but also designing the software architecture, selecting the appropriate algorithms and data structures, debugging and testing the code, and maintaining the software over time. The individual who does the act of programming is called a programmer. A computer programmer is sometimes referred to as a Software Developer, Software Engineer, and Application Developer. Computer programmers write a set of instructions or steps used to solve a problem or perform a specific task, which are called Algorithms. Ceara Algorithm and Decision making General yocabulary GPS (Global Positioning System) is a satellite-based navigation system that provides location and time information in all weather conditions, anywhere en or near earth’s surface. ‘Traffic refers to the movement of vehicles, pedestrians, and other forms of transportatfon along a route, such as a road, highway, or street Algorithms are simply a set of instructions, used to solve problems or perform tasks, based on the understanding of available alternatives. Algorithms are used in many aspects of our daily lives, often without even realizing it For example, 1. Astep-by-step instruction to cook a Shiro-wot is an algorithm. 2. A step-by-step instruction to drive a car is an algorithm 3. An instruction you give a stranger who asked you for a direction to a hospital is an algorithm. 4. A. step-by-step instruction to multiply binary numbers is an algorithm. The Applications in our devices also use various algorithms. For example, 1. Navigation: When using a GPS or maps app, the algorithm calculates the best route to your destination based on various factors such as traffic, distance, and speed limits. 2. Social Media: Social media sites use various algorithms to personalize your teed by showing you posts that are more relevant to you based on your interest, past interactions and other data. 3. Online Shopping: When you search for a product the algorithm suggests other related products or recommends items based on your past purchases. Cn ieee rd 5 ero] Form a group of more than two students ina class and do the following questions. 1. Listatleast five algorithms you use in your daily life. 2. Listatleast three algorithms used in various appsin your device. 3. Write detailed instructions to do the algorithmsllisted in the 1* question. Different people may use different algorithms to solve the same problem. Solving the same problem efficiently with lower time and resource makes algorithms better and efficient Let's say your English teacher asked you to search the definition of the word “maximum” in a big dictionary? What will you do? The first algorithm that comes to your mind might be to start flipping each page until you reach the word. It may take you a while but you will find it eventually This algorithm might work best it your given word starts with the letter A, but it performs worst if your letter starts with Z Dictionary The second algorithm might be to open the dictionary at the middle. If you're lucky you may find it there. If Bebe : one all dictionaries are sorted alphabetically, if your FA il 9 if iy Ny random page lands you at letter J, you will then flip to q 8 q Q g the middle page to your right side. However, if your random page was landed on letter S, you would tlip to Wi Px] Gi a the middle page to your left side. By repeating such steps, you will find your word much faster than your English Alphabet first algorithm. The second algorithm is much better than the first on many scenarios. However, if you want to search for the word “Abacus” the first algorithm will perform better. Ceara Choosing and designing better algorithms by considering various scenarios is up to the programmer. The quality of an algorithm depends on several factors such as: 1. Accuracy: an algorithm is considered good if it produces correct and accurate results for a given set of inputs. 2. Efficiency: an efficient algorithm is the one that can perform a given task in a reasonable amount of time and resources. A good algorithm should be designed to minimize the time and resources required to complete the task 3. Simpli to understand, implement, and maintain. A good algorithm should be designed to be as simple as ity: A simple algorithm is the one that is easy possible without sacrificing accuracy or efficiency. 4. Scalability: A scalable algorithm is one that can handle large input sizes and still produce results in @ reasonable amount of time and resource. A good algorithm should be able to handle large data sets Edge case refers to 2 scenarfo or without becoming slow or inefficient. input that is outside of the typical or expected range of inputs thats program or algorithm is designed to handle. Edge cases can be crashing or producing incorrect results. A good extreme, unexpected, or rare, and algorithm should be designed to handle a wide they often require special handling to ensure that the program or algorithm works correctly. peta STi) ay 5. Robustness: A robust algorithm is one that can handle unexpected inputs or errors without range of inputs and edge cases to ensure that it produces correct and reliable results in all situations. Overall, a good algorithm is one that is accurate, efficient, simple, scalable, and robust. it should be designed to solve the specific problem at hand and take into account the unique characteristics of the data and the context in which it is being used. ema ae alia Pseudocodes In computer programming, computer programmers and system designers use Pseudocodes to describe an algorithm. Pseudocode is a high-level, informal notation used to describe an algorithm in a way that System designer is 2 professional jg easily understood by humans. It is not a formal who designs and develops Subj Cintra Fogramming language, but rather a way of systems that meet the needs ofa. P79 ie fenguag y business or organization. representing the logic of a program in a format that is easy to understand and communicate. Pseudacade is often used in the early stages of software development to plan and design algorithms betore they are implemented in a specific programming language. Pseudocode typically uses simple English-like statements to describe the logic of the program or algorithm. Examples. 1. For a program that finds the largest number between three distinct numbers, the system designer / computer programmer may write this Algorithm Input three numbers: A, B, and C Compare Ato B: If Ais greater than B, compare Ato C: If Ais greater than C, output A as the largestnumber If Ais less than C, output Cas the largestrumber IfA\is less than B, compare B to C: If Bis greater than C, output B as the largestrumber If Bis less than C, output C as the largest number End ‘The pseudocode for this algorithm may look like Input A, B, C IFA>B HAS Output A. Else ‘Output C Else BoC Output B Else ‘Output C CeCe Note that both the algorithm and pseudocode use - indentation to indicate the structure of the code. The “When writing pseudacodes there fs ne right or wrong. le ‘write Be ety ve por of tre sone bck of ene, TH ‘the same algorithms. not strictly necessary, but can make the code easier statements within each if block is indented to show to read and understand 2. Let's assume a local company's payroll is calculated based on these conditions. the regular work hour for an employee is 40 hours. If an employee works more than 40 hours, the amount of payment per hour will be increased by 50% and then in the total payment 100 birr will be added. The algorithm and the pseudo code may look like this, Algorithm Input the umber of hours worked. If the number of hours worked is greater than 40: Galeulate the regular pay for the first go hours. Calculate the overtime pay for the additional hours. Add 100 birr to the total pay. ‘Output the total pay. If the number of hours workedis less than or equal to 40: Calculate the total pay. ‘Output the total pay. The Pseudocode for this algorithm may look like Input hours_worked Ifhours_worked > 40 regular_pay € 40*hourly rate ‘overtime_pay © (hours_worked- 40) * (hourly rate *15) total_pay € regular_pay + overtime_pay +100 Else total_pay © hours_worked * hourly_rate Output total_pay Co eee ie ard ry Ac ame Create an algorithm and pseudocade for the following cases, 1. To find the average of two numbers. >. To convert Fahrenheit to Celsius 3. To check whether @numberis even or odd. 4. To calculate the area of a circle. Flowcharts A Flowchart is a visual representation of a process or algorithm that uses symbols, arrows, and other graphical elements to show the flow of control and the sequence of steps involved in the process. Flowcharts consists of a series of interconnected shapes or symbols, each of which Tepresents a specific step in the process. The shapes may include rectangles for process, diamond for decision points, ovals for starting and ending points, and other symbols to represent specific operations or data inputs and outputs. There are five basic symbols commonly used in flowcharts. These are ‘Symbol Name Description Terminal Indicates the start and end of the algorithm. Input / Output | Used show taking input and showing output Process Indicates any type of Internal Operations. Decision Used to ask questions that are either True or False. Like Yes or No. Control Flow Show directions of flow. HOOD Ceara 10 Rules for making flowcharts 1. Flowcharts are generally drawn from top to bottom. But you can also draw them from left to right. 2. They must start and end with the Terminal or Process symbol. 3. A Decision must have 2 exit points. One for True and another for False 4. All boxes of flowcharts must be connected with Control flow arrows. Consider the following points while drawing a flowchart. 1. Start with clear goal: Before you start making a flowchart, you should have a. clear idea of what the process or algorithm you are trying to accomplish. This will help you make sure that the flowchart accurately reflects the process you are trying to represent 2. Use the standard symbols consistently to avoid contusion 3. Use clear and concise language. 4. Keep it simple: Flowcharts should be easy to read and understand. Avoid including any unnecessary details thot may confuse the reader. 5. Test the flowchart: Once you have created the flowchart, test it to make sure that it accurately represents the process or algorithm you are trying to describe Following the rules and considerations can help you create effective and accurate flowcharts that accurately represent the process or algorithm you are trying to describe. feat esac tala cr Examples 1. Let's create a flowchart for an algorithm that checks whether a student mark is above 50 or not and decides whether a student fails or not. Start Getstudent ‘Mark is mark more ce olden ss —T Pass 2. Let's create a flowchart for an algorithm that finds the largest among three different numbers. For representation let's call them A, B and C. Ceara 2 Flowcharts can be a useful tool for understanding and communicating complex processes, as they provide a clear and concise visual representation of the process flow. They can also be used to identify potential problems or bottlenecks in a process, or to analyze the effectiveness of a system or algorithm. Flowcharts can be created using specialized software or by hand, depending on the complexity of the process being represented. Computer programmers design and use various algorithms, pseudocodes, and flowcharts to understand the software requirements easily. Form a group of more than two students in 2 class and draw a flowchart for the following, algorithms. 4. To check if the given number is positive or negative. 2. To find the average of two numbers. 3. To convert Fahrenheit to Celsius. 4. To check whether a number's even or odd. 5. To calculate the area ofa circle. Programming Languages In previous chapters, we have discussed how a computer works with ones and zeros For a human being to instruct a computer by using binary code which is composed of only ones and zeros is very hard to understand, time-consuming and error-prone. So, programming languages were created to ease this, human-readable words, characters, and symbols to write code. Then a special program kicks in and Error-prone: 2 tendency to make or cause errors, changes all the human-readable code to a computer- readable format. There are many programming languages available to Subject vocabulary work with. Each programming language has certain Paradigm {s away of organizing, features and paradigms that makes it suitable for structuring, and modeling code, specific task. Just like how doctors’ jobs are divided and it determines how @ into various specialties, and each solves complex programmer thinks about and problems and uses the right tools for their job, the solves problems. same is true for programming, em eit a Various programming languages and technologies Java Python PHP fer eel] putary General purpose: suitable to be used for two or more basic purposes. Abstraction: the quality of dealing with ideas rather than events For your different needs and requirements, you may use different programming languages. For example, if you want to create or develop 1. AWeb-based Application, you may use PHP. 2. AGare you may use C++ and C#. 3. For an artificial intelligence program, you may use Python. 4. For Android apps, you may use Java or Dart. The programming languages listed above are not limited to a single task. Most of them are General purpose. While others are designed for specific tasks like web development, data analysis, or game development. And also, as new hardware and software technologies emerge, new programming languages are developed to take advantages of these advances Most programming languages can be used to create various programs. But each of them has their advantages and disadvantages on certain tasks. Ceara 14 So, it is up to the programmer to choose an appropriate programming language for the project. For example, writing a program in C++ takes a longer time but, the final program will be very fast. While writing a program in python takes a very short time. However, the applications built in python are very slower than programs written in C++. If you want your program to run as fast as possible you C plus plus / C++ / CPP. should choose C++ against python. But if you want to develop an app as fast as possible you should choose Python. This is just a simple scenario. In general, C++ is a lowtevel language that is more powerful and efficient but requires more expertise to use effectively. Python is easier to learn and use, but sacrifices some performance for ease of use. Both languages have their strength and weaknesses and Eyhon are better suited to certain tasks than others You must consider various points before choosing a programming language for your project. This is one of the main reasons why there are many programming languages. Based on the level of abstraction provided by different programming languages they can be divided into three categories, 1. Low-level Languages are programming languages that are designed to interact directly with @ computer's hardware and is closer to machine code. they typically provide little to no abstraction from the hardware. Examples of low-level language include Assembly Language, which provides a symbolic representation of machine code, and machine code itself, which consists of binary instructions that can be executed directly by the computer's CPU 2. High-level Languages are programming languages that are designed to be more abstract and easier to read, write, and understand than low-level languages. They allow a programmer to use English-like words to create programs that are not dependent on the type of computer they are running on. Examples are Python, Java, JavaScript and PHP. em eit a 5 To convert high-level or intermediate-level language source codes to an executable machine code (that can be run on a computer), two types of special programs are needed. Two special programs are 1. Compiler: It takes the whole source code and transforms it into an executable machine code. programming languages who compile themselves into machine code before execution are called compiled languages. ee -<==>-B- The compilation process involves parsing the source code, analyzing it for errors, optimizing the code for performance, and generating machine code that can be executed directly by the computer CPU. Compilers are commonly used in programming languages like Java and C++. 2. Interpreter: It takes a source code line by line and then converts it to a machine code when the program is run. ‘The interpreter reads each line of code, interprets its meaning, and executes the corresponding instructions on the fly. Interpreters are commonly used in programming languages like Python, JavaScript, and PHP. Advantages of using compilers 1. Faster execution speed 2. Better memory management, as compiled code can be optimized for specific hardware and operating system 3. It can generate standalone executable files that can be distributed to other computers without requiring the source code or an interpreter. Advantages of using ferpreters 1. Easier to write and debug, as errors can be identified and corrected in real-time. 2. More portable, as the same code can run on different platforms without requiring recompilation. 3. Very beginner friendly. Ceara 16 3. Intermediate-level Languages are programming languages that are designed to provide a compromise between the low-level control and efficiency of assembly language and the ease of use and higher-level abstraction of high-level languages like Python or Java. Examples of intermediate-level programming languages are C, C++ and Rust. Note: the distinction between programming language levels is not always clear- cut, and some languages can be categorized in different ways depending on how they are used. Code Editors and Integrated Development Environments. Any text editor like Notepad can be used for writing source code. But it is very recommended to use an Integrated Development Environment (IDEs). IDEs offer necessary tools and different features to your code like 1. Autocomplete: it will guess what you want to write 2. Syntax Highlight: it colors different parts of the code for better visualization. 3. Build Automation: they make it easy to directly run the program without any configuration and much more Most Programming Languages have their own IDEs. For example 1. Dev-C++ is a free full-featured IDE to build C and C44, Android studio: 't provides almost everything you need to build an android application by using Java. ar Sublime Text PHP Storm: It provides different tools to build apps with PHP, There are also general-purpose Code Editors that support many programming languages at once. Like Sublime Text ond Visual Studio Code Visual Studio Code PHP Storm — @ complete code of your program is called source Android ft Studio Android Studio it into multiple files. Each file is called a source file » code. You may not be able to write all your program code in a single file because it will become harder to manage as it grows larger. So, you may need to break em eit a 7 Abig project's source code may have hundreds or thousands of source files. In the next chapter, you will learn the C++ programming language. Because 1. C++ teaches fundamental programming concepts: Learning C++ teaches you the fundamentals of programming including variables, data types, control structures and others concepts. These concepts are foundational and can be applied to other programming languages 2. C++ has a large community: C++ has been around for over 40 years and has a large community of developers and users. This means there are a lot of tutorials, resources, documentations and support for beginners. 3. C++ is widely used: C++ is used in wide range of applications, including operating systems, game development, finance, and scientific computing. Learning C++ can open up a lot of opportunities for future career paths. 4. In C++ you have to explain almost everything in the source code, which will give you an even deeper knowledge of the program parts. 5. The syntax of C and C++ is very similar. Learning C will be very easy Overall, Learning C44 as. your first programming language can provide a solid foundation in programming concepts and open up a range of opportunities for future learning and career paths. Ceara 18 Summary ‘The computer technology has become a big part of our daily lite. We use various types of applications in our phones, tablets, and personal computers. While this is o great thing, computer can't just do activities by their own, they need to be told to do so. While computers are very fast and efficient, computer programmers must design their algorithms as simple as possible by considering resource and time. Because even a fraction of seconds in real world application really matters Flowcharts and pseudocodes are very useful techniques to visualize, and understand the algorithms. Well-structured flowcharts and pseudocodes will help the application developers to understand each other and finish projects on time Because it is very hard to communicate with a computer directly by using binary code, human readable programming languages were created to ease this task. The human readable code will then get converted to instructions that a computer understands by using compilers and interpreters. While developing different programs, it is very useful to choose the appropriate programming language by considering the target users, hardware and other functionalities provided by the programming language. There are different tools and integrated development environments that makes it easier to write, build, test and debug our programs. feat Na #include indicates that we would like to use the contents of the iostream library. iostream (Input Output Stream) library is one of many standard libraries that came with C++ by default. This library allows us to write information to the console nd take input from the console. It also contains several functions to perform input and output operations. Without line 1 we cannot use std::cout on line 4. Line 2 is blank (empty), and ignored by the compiler. This line exists only to make the code more readable for programmers. Line 3 tells the compiler we want to define a function 39int main(){ called main. This function is the starting point of every C++ program. Even if you write a thousand lines of code without having the main function, the program will not have a starting point so, it won't even compile. For now, assume a function as a block of code with a name. we'll cover it in later parts of this chapter. the opening curly brace { in line 3 and the closing curly brace } in line 6 tells the compiler the scope of the main function. Everything between lines 3 and 6 is part of the main function. al std::cout << “Hello cH#*; Line 4. std::cout which stands for character output. It will help us print characters to the console by using the << operator which pushes characters to the console. eee ere ma PYG Line 5 is a return statement. When an executable program finished running, the program sends a value to the operating 5| return @; system to indicate whether it ran successfully or not. This particular return statement returns the value 0 to the operating system. Which means everything was Ok. NOTE: After executing the return statement in the main function, the program exits Even if there are other statements, they won't get executed 3 a 5 return 1 ie main r Is this a valid C++ program? what do you think will happen ffyou Compile and run it if itran whatwould be the output? Namespaces. The std::cout is instructing the compiler to use the cout object which is located in the std namespace. This statement is too confusing, to understand namespaces better, consider this situation, let's say there are two students in your class named Nadia When you call their name, you should use additional information like their father's name or something additional. Otherwise, they will both respond which is not good ‘The same situation can arise in prograrnming too. As you remember earlier the cout object is located in the iostream library. what if in the future another library you imported has the cout object? The compiler will now be confused about which cout it should use. So, it will bring on error and stops compiling, A namespace is designed to overcome such difficulty. It is used to provide additional information to differentiate similar functions and others types. By using namespaces, you can define the context in which names are defined. We can summarize that Y. std is the name of the namespace, v is a scope resolution operator and Y cout is one of the objects located inside the std namespace. em acacia yi To summarize, namespaces are used to group related identifiers together, and avoid naming conflicts between parts of a program. without namespaces, it would be difficult to write large programs that use multiple libraries or modules, because naming conflicts could arise if different parts of the program defined identifiers with the same name. C++ has a standard library that contains the common functionality of C++ to build applications. you can use std:: to access everything defined in the std namespace The semicolon ; is used to terminate a single staternent. Every statement in C++ must end with ; The << (insertion) operator job is to push text to the console. You can join multiple << to push text to the console. ineluae Sera Sp Am natn > Brainstorming Let's print the name of three of your friends Can you guess the output of this coda? Seine maining ? Escape Sequence De dnt main(t 6] Stazscowt ce *rftu"s The program works correctly but you may want the names to be displayed in their ‘own single line. Like this. Ceara 28 To achieve this in C++, you must also print or push a new line. To do that push \n' to the console by using the << (insertion) operator. eint mint Sta:seout ¢¢ “Nnsia” CoN Hasseout ce RAW" The ‘\' is called an escape sequence. Escape sequen provide a way to include special characters in C++ code that cannot be represented directly using normal characters. There are also other escape sequence characters such as 1. \t to create a horizontal tab (about 4 white s 28) 2. \" to insert a double quote 3. \\to insert backslash \ character. You can use escape sequence characters inside a text. eine mine 4)" Stats cout << snat\erae2 ns 5] Starseout ce -Nactatn” 6) stasseout ce Mer\re\nars 3] retuen8: You can also use stdziendI which stands for end line to insert a new line character 39 int maint Shavicout ce “Ratnael” int main(){ // declaring a variable int height; return 6; warnNaunawne } This tells the compiler that there is a variable named height of type int. but it doesn't actually create the variable in memory yet. Variables must be declared before they can be used to store values Data Types There are common built-in types of data C++ can work with such as int, double, float, and char. these are called Data Types. After a variable is declared, you can give it value to store. Using the = operator. This is called a definition. 1 #include 2 3h int main(){ 4 5 // declaring a variable 6 int height; 7 8 // defining a variable 9 height = 15; 10 return 95 ‘y The variable height now has a value of 15. The = operator assigns the value on its fight side to the variable. The = operator is called the Assignment Operator. Ceara G Le's assign the height to another value. 1 #include 2 aaant main()( 4 5 // declaring « variable. 6] ant height; 7 8 9 // assigning @ value. height = 155 108 Ul] —_-//_re assigning on changing the value 12| height = 22; 3 1a] return 2; asl) A variable definition required that a value be assigned to the variable. This value could be assigned at the time of declaration, or it could be assigned later in the code. Variable Declaration and Definition The variable declaration and definition steps can be combined into one. 1 #include 2 36 int main(){ 4 5 int height 6 z /* 8B this is a short form for 9 both declaration and definition 18 of a variable. ae vs 12 return 5 13} NOTE: Once you declare ¢ variable you can update its value but you cannot redeclare the same variable again. eau) Cae te ys 37 1 include 2 35 Ant main(){ 4 5 int height = 155 6 7 height = 105 // changing to 16 8 height = 83 // changing to 8 9 18 Cnr Perea ay 12 return 0; a3} The compiler will show the following error. Which explains where the error happens and why. Compiler "4 Resources dhCompile Log ¥ Debug [8 Find Results Close uC file Message CAUsers\QelemMeda\Docume... In function ‘int maing) 10 6 CAUseis\GelemMeda\Documents... [Error] redeclaration of int height” 5G CAUcers\GelemMeds\Documents... [Note] int height previously declared here Keywords in C++ Keywords are reserved words that have special meanings to the C++ compiler. Like int, using, and return. here is the list of common keywords int return do const using if else break true false for float void continue While char switch case default function namespace Ceara 8 Variable Names (Identifiers) Identifiers are unique names given to variables or other entities like functions. It is used to identify and distinguish one element from another. Identifiers must follow some rules to be considered valid 1. C++ is case sensitive, that is, upper case and lower-case letters are different 1 tinenude ostream 2 Using nanespace sti; AGare maine G 5 8) Ane hedgne = 295 7) Ge Helen = 17) | ane Hexor =aty a Lt vorieates are different, Bl ov s sa] return 0: aly 2. The first character must be a letter or underscore (_) 2X ineaude 2 Using namespace sty Spine maint 5 8] 17 these ane vatta Cov vertabe naes 8) ane netgne = 22) 8) ine vnedave = 23: ao) ine Stortroune = a5 2 a s ry 16!) 3. There are no restrictions on the length of a name. 4. C++ keywords are significant and cannot be used as names. 2 Using namespace std; 3 pane nainond 6] 1/ these are EWALD Cot identfers 3 8] Ane 2redght = 12) // can't start with mers | ane start point © 2: 7/ cant use space 30 ine ines 3) U7 can't te esword n aly To improve the readability of your programs you should use self-explanatory variable names, ema ae alia 42 Winctude 2 , dcant waine 5] metewe v= man; // nett « peture = wlan ta] cout' Greater Than 5 >6returnO < ess Than 4<5retum1 Greater Than or ° 4>= 6 retum 0 < Less Than or Equal To 6 return 1 Examples 1 include ciestrean> pnt naka &| ane murtera = 225 3) Ane nuntera = 9 8) boot results 16] // returns 1 for true ond 0 for False 15] Seautt = (numbert o= nmterd)y 2) Gout 3 are true returns 1 Ceara 46 W Logical or Returns true at least one of the] 1<2||2>4 statements is true. otherwise it] returns 1 retums false. ! Logical not Returns true if the statement is | (1>2) false and returns false if the | Returns 1 statement is true As comparison operators, you can also test for true or false with logical operators. Apint maint &) book steterents = trues 4) deol statesents = False; 12] cout > extraction operator. em acacia 47 Whenever we use cin, the console will show us a blinking cursor which indicates the console is ready to take input. Then you should type your value and press Enter. sqeincie ciate S 7 SpimatoC 7 fepiring a variate to stare tne og; 10] // this will salt for the user input and assions it ti ie) ceut << "You Wild graduate at the age Of ¢ "<< age + 65 faly a Line 12 will display a blinking cursor, then whatever the user typed the value will be given to the age variable For o better experience, it is recommended to displ y Some information using cout about your input before receiving it. such as "Please enter your age?” and "How old are you?” 1 eisciute ciostren Anant maint é) ine sees 3] 77 te ts nese praceter to atentey we] cout ce “Mow eld are your? "y 12] cin > oges sly ‘ More examples Let's creat returns their sum. imple program that takes two numbers ar Ceara 48 een pers and returns thet sus, Ane munborss 1/6 Ant rumber2) 77 aeftntrg " um = number + runbonz: 11 oetng the murders snd assigns then 0 the wartable sum cout <¢ "The sum oF " ce runberd ce "and * €¢ numer? ce" S81" ce sum (peace Sk Write a C++ program which takes three numbers from the user and retums thelr sum, Control flow Not all programs are straightforward. They do not take the same path as taking two numbers and adding them. What will you do if you want your program to let the user choose the arithmetic operation to operate on the numbers? You will be forced to of code that will get exe: write different blo uted on certain conditions. Such as if the user wants to add, subtract, multiply, and divide em acacia ey Example 4p ane masnore 16 | cout ce "De you want mbdStton (4) oF subtraction (39) 4) 13] Ein >> openetion 132 arcoperstton se +94 B ersten == *=){ a ecules nimbert * ru L sats 2a] return 8: Your program might do some tasks when some event happens. For example, you may as the user of your program his/her age and check if they are above the age of 18. Ceara 50 The algorithm might be Ask the user's age If the user's age is less than 18 Print you're not allowed Else if the user is 18 years old or more Print you're allowed to use this program. C++ provides several different Control flow statements which allow the programmer to change the normal path of execution. 1. if to specify a block of code to be executed if a specified condition is true 2. if- else to specify a block of code to be executed if the same condition is false 3. else if to specify a new condition to test, if the first condition is false 4. switch to specity many alternative blocks of code to be executed If statement ‘Syntax if( condition ) { // code to be executed if the condition is true t Example Here is a program which checks if the number is positive steele 0) ( 2 out Ce number <<" 8 8 Positive number”; sl You can use multiple if statements in your program. you can run the following program with various input to see how your program behaves em acacia T Example 2 The following program will check if a number is positive, negative or neither ts ne 7) cout <¢ “Enter a number : “; 5] cin >> pumers 1p Atenumer == 296 a ‘ait ce "Dero ts nether PosStive or Neentive ul oy ie 15) AACoumber > 9) pty = fs Se at oy : Bly i Example 3 A program that checks whether a number is even or odd Note: Any number that can exactly divide itself by 2 with no remainder is an even number sisi steers seienemmeneneeanmmmmemunenien as | This program achieved this by checking if there is no remainder, after dividing the number by 2. Note: You can use multiple if statements as you want. Ceara cod If... else Syntax if( condition ) { // code to be executed if the condition is true }else{ // code to be executed if the condition is false t Example 1 Here is a program which checks whether the user is a Child or Young out ce “You 04 a you? , Example 2 Here is a program which takes password from the user and checks its validity 2 sang namespace sa) asamt satn00( 7) tout muons else if(oinber 9 0) ( else if(oumber « 0)¢ ) Example 3 Zero is nekther Positive or Negative"; a a Negative Minter"; at A program which takes a letter and checks if the letter is a Vowel or Consonant. 1 inelise chostowans 2 using namespace st Aoane wince ein >> letters cout ce ‘Novel; pense ifCetser ease HeCletver pease 1ecierzer cout ce Novel; pease te etcer e re) else no) . if(letter == 1A" || latter letter e= ‘2 Letter aeteer == 0) Cen eerie Write a C++ program for the following conditions 1. Receive height and width of a rectangle from a user and check ff itisa square ornot, 2. Receive anumber of days astudent attends a class. thanif the number of daysis greater than’ andless then 16, print they are legitimate to take the test. 3. Receive'a salary of an employee and categorize inone of these canditions. Monthly salary range Category Less than 1000 Nery Bios Between 1oo0 and3a00 Poor Between 3000 and 6000 Moderate Between 6o00 and 10000 Standard Between 10000 and 15000 High Between 15000 25000 Rich More than 25000 Very Rich Ternary Operator There is @ shorthand method to use if else statements. It is known as the ternary operator because it consists of three operands (condition, expression2) Syntax (condition) ? expression1 : expression2: expression1, and Ceara 56 Example This program assigns a value to a string by comparing a condition. 2 Ging raneoace ed, sean noi This same program can also be shortened as. 2 include > gender; F ‘ Leh atgener == 9X Be) pene tgetere a Ceara You can nest as many conditions as you want. Switch statements Syntax switch (expression) { case constant: 1] code to be executed if expression is equal to constant1; breal case constant2: code to be executed if expression Is equal to constant2; breaks it can heve many cases. default: J code to be executed if expression doesn't match any constant 58 Pe eee eye ed Example 1 45 ame masncne 8] tnt dey « 45 7 suiteh (day) ¢ 5 ‘cout << "onda": ie break 7 cout, ¢¢ “Thursday's 5 treat be z ‘cout ‘ Example 2 Alternatively, we con share some block of code that got executed different values. Ceara 1) reled eT cee) takes three numbers fr ns the biggest number. 3. Write 2 program tha ich takes a pumber and checks if the number's even or odd. 2. Writs 2 program wh h statement, write a program which takes age of the user and retums if the 3. Byusing swit user is Teenager, Young, and Old. 4. Weite 3 program that takes 3 mark of ead subject in your current class and prints the average 5- Write 2 program that changes te! perature in degree Celsfus into Fahre! Loops A loop is a sequence of instructions that is continually repeated until a certain condition is reached. Loops help us to repeat a certain block of code for @ specil number of times or forever While loops The while loop repeats a code block as long as the specified condition is true. before the execution of the body the condition must be true. then after executing it’s body, it eration (a repetition of a process) will re-check the condition before it starts the ne ‘Syntax ubile¢ condition ){ // a block of code which will be repeated // forever if the condition is true 61 em acacia Example sane rere Hl tnt anin(ot while (ape =2 12) ( 16 Fe wtih print ny Note: The condition will always be checked before the block of code got executed execution. The above example will not stop the execution because the condition is not changing through time which makes it always True. However, we can use a while loop to do tasks for a certain number of times by changing the condition through time. Example 2 using namespace st 3 ‘Apint wain() 5 8) while (3e 10) 6 e Senve // this will add 1 to the ope verte Fy ‘the condition will pot be fullfittea sp) aly i If you want to see the current value of age in each iteration, just print its value. Ceara Co 2 include 2 sing manespace sta ce age «ends hese program shows that the value of age was incrementing in every iteration. Do while loop The do while loop is a variant of the while loop. This loop will execute the code block and then it checks the condition. Syntax do { ” This block will be executed and then the concition gets checked Therefore, this block is guaranteed to run at Least once " } while ( condition ); he do block will always get executed betore the condition got checked. Example 1 ae ia} Whalecace > 5) The current value of the variable age is 0 which is does not qualify the condition age > 5. However, the do while loop will allow the code block to run at least once. Because do while loop run the code block once before checking the condition. em acacia Cy Example 2 A program which prints age between 0 and 5 (inclusive) Ce te as Dkdeage ow a8 age oe 35 , Example 3 The following program has a special case. At the beginning the specified condition was not fulfilled, but because the do block got executed at least once, the statements Inside the do block altered the condition to be true for the next iteration. Bw Dhidelore 992 88 ae hy he parent loop iterates 5 times, in each of its iteration it executes its child loop and prints new line statement. The child loop in the other hand, push a star fori times then it prints @ new line. PieraeeoamTaNe Ress tC Create this shape using nested for loops Break and Continue In any type of loop, you may find yourself wanting to stop the execution of the loop or skip the iteration on some conditions. In this case, you will use the break and continue keywords. They n alter the normal flow of execution in loop he break keyword will stop the loop execution immediately, and the continue keyword will skip the current iteration and goes to the next iteration. Both of them are used commonly in conjunction with conditional statements to exit or skip the loop when a certain condition is met. Then the program continues executing from the statement following the loop, en attr 7 Example 1 41 Hircluae clostrese> te ane mate fe for Gane 6 52 See) # se a= 21 :| breaks // Witt stop / terminate the Looe 6 Bey : te) ° The code block will stop at the 4"" iteration because of the break statement. But if we wanted to skip the 4" iteration, we can use the continue keyword Example 2 2 using nanespace st) " ant naia(t x 20 ) a 2 cont 4 4 ee onal) 3} sly : The code block skipped the 4" iteration which is when the counter i becomes 3. Note: the update statement doesn't always need to be incremented by one. You can modify it to increment or decrement by any amount. Example 2 sine nnespace sa Sy tne natn, Stor ee 5 6; 1 205 Seen 3 - ny P you can also make the loop count backward by changing the initializer, condition, and update statement CeCe Cr Example 1 minciuae ctestre 2 ring namespace etd apne mince ; Mapai w Btn Iteration | Variable} Condition| Code block | Action after code block Is iro Action finished i a 5 | True Prints 5 deduce 1 from i, which makes it 4 a 4 | True Prints 4 deduce 1 toi, which makes it 3 3 s True Prints 3 deduce 1 toi, which makes it 2 an True Prints 2 deduce 1 toi, which makes it 1 sm 1 [true Prints 1 deduce 1 toi, which makes it 0 oe False Cha Arrays An array is a variable that can store multiple values of the same type. For example, if we want to store the name of 5 colors, we do not have to create 5 separate variables instead we can simply use an array Syntax dateType name[n]; Here, + dataType: type of element to be stored. + name: name of the array «nthe size of the array. em acacia ) #include using namespace std; jint main(){ string colors[5]; 1 2 3 4 5 6 // defining an array to hold 5 values 7 8 9 return 0; 1@ 1 Each element in an array is associated with a number. The number is known as an array index. We can access elements of an array by using those indices. Inserting items into the array one by one. pane nekaoll ‘tein colers{s}: colorsfe] = “Re colorsti] = "oreen"s felore(i] = ‘Netiow"; Colorst] = “orange”; coloreté] = “antes cout €¢ calorst0ls // printing the first element 18) return ¢; Array indices start with 0. Meaning colors{0] is the first element stored at the index 0. In most programming languages counting is started from 0. When you are trying to access arrays or any collections, the first item is going to have a index number of 0. It is also possible to initialize an array during definition Syntax string colors[n] = { "elementi", “element2", "element3", Ceara 7o Example 3 eng mamarpace 2 ning namergace aa Artint since 5 G) sting eoterafs] = ( *Ro#", "creon”, "Ventew, “Orange”, "uhdee")s 3 pe tan use for Loupe ta {terete throwgh each index: ef hear LAP for (Ant redex = 0; Sader ¢ 55 indexee)é 2 coat ¢€ colorstindexd << endl; BL) asl : Because the value of the index is changing with in the iteration, we can use it to access different elements in the given array. Practi See) 4. Display all the elements of the colors array in reverse order. 2. Store all elements of the colors array into another variable in reverse order. 3. Create new array called fruits which hold so frutts, Multidimensional Arrays sing the same syntax, In the previous section, you have seen an array of strings. By you can create an array of any data type. Multidimensional arrays are the same but their elements are arrays. In simple terms, a multidimensional array is an array of arrays Syntax datatype name(n]{m]; em acacia a + dataType: type of element to be stored + name: name of the array «nthe size of the parent array m: the size of the child array. Example Apint int) 7 string stucents(2](: . (skatneed", "yorise", "Mohanwed", "Seifet, “Tela }, : {onadia’, “retur, “neskeren, "Beteanen", “Dognanit’) aay aly . Accessing elements in a multidimensional array syntax name[n][m] ; Here, © n: index of parent. © m:index of child Example 8 ut <¢ stuenesf@][2] endl; $6) cage cater) can; Goals Ceara PR You can also use loops to display all items in multidimensional arrays. For example, by nested for loop we can access both the parent array and elements of each of its elements Example 2 Using namespace st: apane natn(oe String stacemts(21(5)"= {{vkatnsed”, "Syoriae", “Mohanned", "Seite", 4 chadias, “IFEU", “heaxeren”, b etelhen", “Damnanst”) b for tint Vn; fe 25 dbedt 7 2 teeratione for the ponent: elenmnt for (int 5 = 05 5 < Sy Jealt 17 5 steroti sits orra . cout << staents[ 0/9 << ends sly ey Example Detailed 2 include Ep Ane mati PE string. stucentsicI05) = : ‘suatened", "eyosiae”, “Mohamed”, "Seifs", “Tot wt: Ap for (int k= 65 4.25 Son // 2 tterations ror the parent etonent vy cont “Parent £7 661 66 exch; ry for (tae 4 #05 J.< 55 Joent “7 § treractons from che ene cntua arrays] 0 Gout fe OME ening ee 5 ce" ce stadt S113] ce ene; oD 21 return 6; aly 1. Display all the elements of the student's array in reverse order. 2. Store all elements of the student's array into another varfable in reverse order eau) Cae te ys 2B Functions A function is a reusable sequence of statements designed to do a particular job. In previous sections, we have covered a C++ program should contain a function called main. Which is where the program starts execution when it is run. However, as your program starts to get bigger and bigger, putting all the code inside the main function becomes increasingly hard to manage. Functions provide a way for us to split our programs into small, modular chunks that are easier to organize, test, and use. Most real-world programs use too many functions in which each of them handles a specific task to make them as reusable as possible which will decrease the repetition of code and makes it more manageable. C++ comes with plenty of very useful built-in functions which will ease your work. For example, instead of using an if statement to find the maximum of two numbers, you can use the built-in max function. Example 2 45 using maneszace std) Spant maine 5) 7] cout €e man(23yii) <« endl; // returns the maximum oF 38 a6 11 5] coue ex min(azsnay 3 ing namespace st, 4 Spine aain0l ® 8) cour €¢ Square rat af 8" ce aqet(e) ce anfls a tars. the 3 smuired (3 to the: newer A 2) 12) cout ("9 te the pover 21" << pomJs2) <© endl) 3 15) cout (math.h) SREINN —— cumeriehibary = vs tons ee Furetions However, it is very common and useful to be able to write your own functions. The functions that you write yourself are called user-defined functions. Creating user-defined functions. As you recall functions are just blocks of code designed to do a particular job. To create a simple user-defined function you need a few things. 1. Aname of your function 2. The statements you want it to execute Pe eee eye vb) 3. A return type. Which tells a compiler the data type of the function output, in case if there is anything the function returns after it finished execution. Syntax returntype function_name(){ // code block to be executed } Example Hf deftotng 0 function whieh returns nothing (votd) vei capo lo(t . cau €¢ "Mello & endl; ) eine maint 14) return 6; ashy This sayHello function is just a definition. We can define as many functions as we can. But when we want to use them, we must call them somewhere in the script. To call a function use the name of the function and brace (). ‘Syntax name); Note: you can call a function inside another function But, you cannot define its definition inside another function. Example 2 Using namespace sta) 3 Se void Sayietla()¢ . | cout s+ helio? < endls os ay Sap tov aan rr) © ie retarn os aly Ceara 76 You can also use/call the same function multiple times. 2 using manespace std; Sp yold saybel 0036 6] cout xe *HelLe” <¢ ends on ay 2 1e_// tne nety punecion Meine asin 13] 17 colLing the savtella function muttible times. ta) Seytetie(); 15) Saynenioc) 16) Soyletled); 1) saywelle(); may ° Once a function is defined, you can use it as multiple times as you want. Even if you want to change its internal behavior, you will only need to update it in one place. But you need to be careful to create your functions into smaller and manageable way. To make them easier to read, understand, and modify. Functions can be tested and debugged independently, making it easier to find and fix errors Function Parameters and Arguments In C++ built-in functions you have seen most of them take an input and return an output. This can also be achieved in user-defined functions. It is very useful to pass information for a function to work with it. For example, If you want the sayHello function to say hello to a specified name, you can pass and receive information using parameters and arguments. Parameters are variables used in the header (definition) of the function. While nction when it is called, arguments are the actual values passed to a Syntax returntype function_nane(dataTypeofParancter parametertiame){ Jf code block to be executed Pe eee eye vr Example 1 2 sing nanespace #86; Spvold saytelio(sering toe) é 15 ayhuatocerera"y, ely Example 2 {Spine nino i) Syrctise Bevan 0 Pe he user his[her name and then pass 4. Macify the ahove program to ask provided by the user to the sayHelio() function as an argument. Taking multiple parameters. If you want your function to take more than one parameter you can separate them with a comma , Ceara 78 Sees terelisgriy sews tere lee Boars ino ey nme: If you want your parameters to have a default value when no argument get passed to the function during the call, you can assign a default value on the function definition. Syntax peturntype name(dataTypeofParameter paramaterllame = defaultValue){ // code block to be executed } Example 1 enue a 2 using namespace st ap ane main 8] i this wit print the wonary adress of the aoe variable 5] cove ce Sages 16 ia| Bly the age 0 12, & will return the address of any variable including a pointer variable In the above example, we just printed the address of the age variable. But if we want to store this address on a variable for future use, we will use pointers Syntax dataType* name;

You might also like