0% found this document useful (0 votes)
41 views

Python Tricks and Tips

Trucos y técnicas de Python, 2020

Uploaded by

Ramon
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
41 views

Python Tricks and Tips

Trucos y técnicas de Python, 2020

Uploaded by

Ramon
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 80
Gain Insider STI Discover more of our guides... Mac Tricks and Tips Black & White Photography Tricks and Tips Photoshop Android Ue ENT MI Tricks and Tips C++ & Python Tricks ren Cloud Computing Tricks and Tips eee nT FRITZ!Box + CEU Mee Tricks and Tips Ses _ C ae Instagram iPhone. Landscape Tricks and Tips Tricks and Tips Photography ri Python Tricks and Tips Weel d eee eee te Rel aca ele el ey (elie eae (eee aR aa EL AV UEeh Orie ily Clete al an ie eee Lael Agua ag NCU ae aU ee reece eu tacud a cu oar eer ese Ea Rc at ON aL eke mele ARB y ole iy Aes ean eA Eee ele Cae ae Steel ear cM EU eo POEM e enue ann €-1 Bale Wre Et vacte mace WRU cay cael Ng Een A Relea eee nM UL UO R oem Mee aaa US cube ere eee nam Ck UE (net Ogu se tg Mecano a RCE PE aT Rk US MEU Loe aces en Uc ED con: Doe [oor 7y et Deere Co a ae a cs cad Vd) aah Ci SI Rely SL bla eV EL) 8 Why C++? 50 = While Loop 10 — Equipment You Will Need 52 For Loop 12 Howto Set Up C++ in Windows. 54 Do... While Loop 14 Howto Set Up C++ on a Mac 56 If Statement 16 — How to Set Up C++ in Linux. 58 If... Else Statement 18 — Other C++ IDEs to Install 60 Combining All You Know 22 = Your First C++ Program 66 — Python File Manager 26 = Compile and Execute 70 = Random Number Generator 28 =~ Using Comments 71 Random Password Generator 30 Variables 72 ~~ Text Adventure Script 32 Data Types 74 ~~ Hangman Game Script 36 C++ Maths 38) C++ Input/Output 40. User interaction 42 ~~ Character Literals 44 Defining Constants 46 File Input/Output Contents “The most important single aspect of software developmentis to be clear about what you are trying to build.” = Biame Stroustrup (Developer and creator of C+4) wor bpublications com Say Hello to C+) - = CAR Hoare (Computer scientist, developer of Quicksort) a Say Hello to C++ eee Ue UA ne Cer) Peet ed bee tells os UT cel Reece aera ic Eee ee iene De a Toe ese ia Ba ee rece eo C++ is the driving force behind most of what you Pear eur ae cecil extraordinarily powerful language to get to grips with. In this section, we look at how to installa C++ I CRUN tects ce z= Say Hello toct ) Why C++? reqs eC cc eateries et ACN ICY called C with Classes, the language was renamed C++ in 1983. t's an extension of the original C language and is a general purpose object-oriented (OOP) environment. C EVERYTHING Due to how complex the language can be, and its power and performance, C++ is often used to develop games, programs, device drivers and even entire operating systems. GB cr set meat Dating back to 1979, the stat ofthe golden era of home computing, C++, oF rather C with Clases, was the brainchild of Danish computer scientist Bjarne Stroustrup while working on his PhD thesis. Stroustrup's plan wasto further the original C language, which was widely used since the early seventies. C++ proved to be popular among the developers ofthe 80s, since it was a much easier environment to get to grips with and ‘more importantiy, it was 99% compatible with the orginal C language. This meant that i could be used beyond the mainstream ‘computing labs and by regular people who didn't have access tothe mainframes and large computing data centres. C44's impact inthe daital world is immense, Many of the programs, applications, games and even operating systems are coded using Cr+.For example, all of Adobe's major applications, such as Photoshop, InDesign and so on, are developed in C++. You will find that the browser you surf the internet with is written in C++, as ‘well as Windaws 10, Microsoft Office and the backbone to Google's search engine. Apple's macOS i written largely in C++ (with some. Wonoade Inds components Language packs ton) summary ~ Delo development wth > ‘Rites isan ng PME. ASPET Coe MM, We ier pec dtpg cud print ‘Microsoft's Visual Studio isa great, Free environment to learn C++ in. ‘other languages mixed in depending on the function) andthe kes begin with Python and spend some time getting to grips with ‘of NASA, SpaceX and even CERN use C++ For various applications, __programming structure and the many ways and means in which ‘programs, controls and umpteen other computing task. you Find a solution to a problem through programming. Once you can happily power up your computer and whip ‘outa Python program with one hand ted behind your back, then move on to C++. OF course, there's nothing stopping you from jumping straight into C+; if you Feel up tothe task, go fort. C++ salso extremely efficent and performs well across the board as well as being an easier addition tothe core C language. This higher level of performance over ‘other languages, such as Python, BASIC and such, makes it an ideal development environment For modern computing, hence the aforementioned companies Using itso widely Getting to use C+ is as easy as Python, all you need isthe right set of tools in which to-communicate with the computer in (C++ and you can start your journey. A C++ IDEs Free of charge, even the immensely powerful Visual Studio from Microsoft 's freely avalable to download and use. You can get into C+ from any operating system, be it macOS, Linux, Windows or even mobile platforms. While Python sa great programming language to learn, C++ puts the developer Ina much wider world of coding. By ‘mastering C++, you can find yourself developing code forthe likes of Microsoft, Apple {and so.0n. Generally, C++ developers enjoy a higher salary than programmers of some other languages and due toitsversatliy, the C++ programmer can move between Justlke Python, to answer the question of Why C+ isthe Jobs and companies without the need to relearn anything specific. answer is because it’s fast, efficient and developed by most ofthe However, Python is an easier language to begin with. f you're applications you regularly use e's cutting edge and a fantastic completely new to programming then we would recommend you language to master. using is written in C+. wk © @ Windows 10 Mac debian ubuntu CS Indeed, the operating system you're . Say Helloto C++ ) Equipment You Will Need Sor Meee eee ee MMM ol Kem Nill don’t need an entire computing lab at your disposal either. Providing you have a fairly modern computer, everything else is Freely available. C++ SETUPS ‘Most, if nt al, operating systems have C++ in their code, so it stands to reason that you can learn to program in C++ no matter what OS you're currently using. | COMPUTER Unless you Fancy writing out your C++ code by hand on a sheet of paper (whichis something many older coders used to do), 2 computer isan absolute must have component, PC users can have any recent Linux distro or Windows OS, Macusers the latest macOS. |_| AN IDE - code. Many IDEs come with extensions and plugins that help make os it work better, oradd an extra level of Functionality. Often, an DE provides enhancements depending onthe core OSbeing Used, such as being enhanced For Windows 10 | COMPILER — ‘compiler isa program that converts the C++ language into binary, so thatthe computer can understand, While some IDEs come with 3 compiler builtin, others don't. Code: Blockss our Favourite IDE that comes ith a C++ compiler as part ofthe package. More on this late. [_] TEXT EDITOR Some programmers much prefer to use atext editor to assemble thelr C++ code before running itthrough a compiler Essentially you can Use any text editor to write code, just save t with a.cpp extension. However, Notepad+ is one ofthe best code text editors available. |_| INTERNET ACCESS While it's entirely possible to learn how to code on a computer that's not attached to the Internet, it’s extraordinarily difficult. Youneed to install relevant software, keep it up to date install any extras or extensions and look for help when coding, All of these require access to the internet. |_| TIME AND PATIENCE Yes, as wth Python, you're going to need to set aside significant tie tospend on laming how to code in Cr+. Sadly unless ue a genus itsnot going to happen overnight, orevena week. A good C+ coder has spent many yearshoning ther crf, so be patient start small and keep leaning. ( Equipment You will Need cl OS SPECIFIC NEEDS C++ will workin any operating system but getting all the necessary pieces together can be confusing to a newcomer, Here are some OS specifics for C++. DNL NEy We have mentioned previously that a good IDE is Microsoft's Visual Studio. However, a better IDE and compilers Code:Blocks, which is regularly kept up to date with a new release twice a year. Otherwise Windows users can enter their code in Notepads, then compile it with MinGW as used by Code:Blocks. Mac owners will need to download and install Xcode tobe able tocompile their C++ code natively, Other ‘options For the macoS include Netbeans, Eclipse o Code:Blocks. Note: the latest CodesBlocks isn’t available For Mac due toa lack ‘of Mac developers. uy Linux users are Lucky in that they already have a compiler and text editor butt into their operating system. Any text editor allows you to type out your C++ cade, when i's saved with a “cpp extension, use g¢+to compile it. MAC RASPBERRY PI The Raspberry Pi's operating system is Raspbian, which isLinux based, Therefore, you're able to write your code } outusing a text editor, then E compile twith g++ as you would in any other Linux distro. . Say Helloto C++ ) How to Set Up C++ in Windows Tate MR ere R Wr eakelRe nee AO aN eel A COM Tee CUT eT Cea IK are plenty of IDEs and compilers available, including Visual Studio from Microsoft. However, in our opinion, the best C++ IDE to begin with is Code::Blocks. CODE::BLOCKS Code:Blocks is a free C++, C and Fortran IDE that’s Feature rich and easily extendible with plug-ins. It's easy to use, comes with a compiler and has a vibrant community behind it. FETED S2'tby visting the Code:locks download site, at EIEEM when you've located the file, click on the worw.codeblocks.org/downtoads, From there, click Sourceforge.net link atthe end of the line and a ‘on the ‘Download the binary releases’ ink to be taken to the latest download notification window appears; click on Save File to start downloadable version for Windows. the download and save the executable to your PC. Locate the downloaded CodeBlocks installer and double-click ta start. Follow . = the on-screen instructions to begin the installation. @ Welcome to CodeBlocks Setup Seng nt ge you tru ean of Coste Re reonnede ato ce sete etry fuestrg Sune sre pm uote ‘Severo detest wre PEPTPD) You cansee that there are several Windows versions [E™AWFB once you've agreed to the licencing terms, thereis a available. The one you want to download has choice of installation options avalable. You can opt ‘mingw-setup.exe’ atthe end of the current version number. At fora smaller install, missing out on some of the components but we the time of writing this is: odeblocks-17.12mingwesetup.exe. The would recommend you opt forthe Full option as default difference s that the mingw-setup version includes a C++ compiler and debugger from TDM-GCC (a compiler suite), @ ‘sone Conparnts ays Gonestin oer of Caco ar ea tet econ " — ‘creat: 25488 Next choose an install location forthe Code:Blacks files. t's your choice, but the default will generally suffice, unless of course you have any special requirements. When you click Next, the install begins; when it’s finished a notification ops up asking you iF you want to start CodeBlocks now, so click Yes. eae wat we abd berg rete ete rt ts ante osneg Mews at ar os) ometeene® il Bent ga eeatgt ean Conca » | Sancta Jr Gene snes rian eva Raera oooRiranaathen.. y ( How to Set Up C++ in Windows Cl Before you star using Code:Blocksi’s worth S18 ‘explaining exactly why you need the added ‘compiler. First, a compiler isa separate program that reads through your C#+ code and checksit against the latest acceptable programming standards: this is why you need the most recently ‘available compiler. This is currently C++17, with C++20 underway. The First time CodeBlocks loadsitruns an auto-detect for any C++ compilers you may already have installed on you system. you don’t have any, click on the first detected option, GNU GCC Compiler, and clckthe Default button to set it as the systems C++ compiler. Click OK when you're ready to continve. See SSS ees Serenata cre oe ES TeGE AD When the program starts another message appears, informing you that Code:Blacks is currently not the default application For C++ files. You a couple of options: to leave everything ast sor allow Code:Blocks to associate all C++ fle types. Again, we would recommend you opt forthe last choice to ‘associate CodeBlocks with every supported file typ. BETISEDD Essentials, computers work and understand only binary, ones and zeros, or Machine Language. Programming in binary isn't effective For human beings. For ‘example, to output the words Hello World!" tothe screen in C++ ‘would appear in binary as: 1100011 01101111 01110101 21110100 e0100000 00111100 0111100 00100000 20100010 01001000 1100101 01101100 01101100 @1101111 @0100000 1010111 91101111 01110010 e1101100 01100100 00100001 00100010 @0111011 Select TERED The compiler therefore takes what youve entered as C++ code and translates that to Machine Language. To execute C++ code the IDE builds the code, ‘checking for errors, then pass it through the compiler to check standardisation and convert it to ones and zeros For the computer tozact upon. It's rather clever stuff, when you stop to think about . @) Say Helloto C++ ) How to Set Up C++ ona Mac To begin C++ coding on a Mac you first need to install Apple’s Xcode. This is a Free, Full featured IDE that’s designed to create native Apple apps. However, you can also use it to create C++ code relatively easily. XCODE Apple's Xcode is primarily designed for users to develop apps For macOS, iOS, tvOS and watchOS applications in Swift or ‘Objective-C but you can use it for C++ too. BETTER Se2ttbyopening the App Store on your Mac, Apple ERNIE when you're ready, click onthe Get button which "Menu > App Store. inthe Search box enter Xcode’ then tums into install Ap. Enter your Apple ID {and press Return There are many suggestions filing the App Store and Xcode begins to download and install It may take some time ‘window butts the First option, Xcode, that youneed toclickon. depending on the speed af your internet connection FRED These ioscn nah tes EER, nsatnsns ogo sone 10.126 or later to install and work. changes tothe system. When that is done, Xcode begins to install, ‘additional components, (How to Set Up C++ on a Mac Cl Mihernthrorovinale inte ERIS) The esta whee toe atest Suz additional components, Xcode launches, displaying laa forall your Future code. Choose a location on your the version number along with three choices and any recent projects Mac, ora network location, and click the Create button. When that you've worked on; with afresh install though, this is blank you've done all that, you can start to code. The left-hand pane a —— ‘details the files used in the C++ program you're coding Click on the main.cpp file inthe list FETED S2rtby clicking on Create New Xcode Project; this ENIEBM Youcan see that xcode has automaticaly ‘opens a template window to choose which platform completed a basic Hello World program for you you're developing code For. Clck the macOS tab, then click the ‘hile it may not make much sense at present, you wil discover Command Line Tool option. Click Next to continue. more as you progress, the content is just Xcode utlising what's ‘available on the Mac. (EERE Teen Oe PEPPED Flin the various fields but ensure that the BETEEEE RD When you wantto run the code, click on Product > Language option atthe bottom i set to C++; simply un, You may be asked to enable Developer Mode choose it from the drop-down list. When you've filedinthe fields, on the Mac; thisis to authorise Xcode to perform functions without ‘and made sure that C++ isthe chosen language, clickon the Next’ _ needing your password every session, When the program executes, button to continue, the output is displayed at the bottom of the Xcode window. BE) site. How to Set Up C++ in Linux ae endo tC ne eee eect Ceol eee el re ene Reon | MN Ae el Coe aa (nace entering code into, including colour coding. There’s also tons of extra software available to help you out. LINUX++ IF you're not familiar with Linux, then we recommend taking a look at one of our Linux titles From the BOM Publications range. IF you have a Raspberry Pi, the commands used below work just fine and for this example we're using Linux Mint. ESTEE The firststepisto ensure Linuxisreadyforyour ++ EMM Amazinoly, cat'sit, Everything is already for you code, so check the system and software are up to tostart coding. Here's how to get your First C++ date. Open a Terminal and enter: sudo apt-get update && sudo apt- _proaram up and running In Linux Mint the main text editor is xed, ‘get upgrade. Then press Return and enter your password. These which you can launch by clicking on the Menu and typing Xed into commands update the entie system and any installed software. _the search bar. Click onthe Text Editor button in the right-hand pane toopen it. ie Ct Yew Sear Trib —] a ' k PEPER ost Linux distros come preinstalled with all FETS '2%ed, or any other text editor you may be usin, the necessary components to start coding in enter the lines of code that make up your C++ Hello C++;however, it’ always worth checking to see if everything ‘World program. t'sa little efferent to what the Mac produced 's present, Stil within the Terminal, enter: ude apt-get install build-essential and press Return. you have the right components nothing installed; Fyou'remissingsomethen they intmain() are installed by the command, { 71M first C+ program ‘cout << “Hello Norld!\n"; include ‘asemsnee std: ¥ peajn~ xeon aa vowtoseuncrninx CR FETTER) When youve enteredyourcode,cickFile>Saveas SIMI sefore you can execute the C++ file you need to and choose a folder in which to save your program. compile. In Linux t's common to use g++, an open Name the File ashelloworld.cpp (it can be any name as ong asithas source C++ compiler, as you're now inthe same folder asthe C++ pas the extension), Click Save to continue, file, enter: g++ helloworld.cpp in the Terminal and press Return in bdcialeeamininias Fie 66 von tach Teri He FETTER The Fist thing to notice is that Xed has FSTTSEDD i t2kesa short time while the code is compiled by automatically recognised this asa C++ file, since the {r+ but providing there are no mistakes or errors in File extension is now set to cpp. The colour coding is present in the the code you are returned to the command prompt. The compiling code and iF you open up the file manager you can also see that file's of the cade has created a new file. If you enter into the Terminal icon has C++ stamped onit. you can see that alongside your C++ ile is aout. BERTI D) with your code now saved, drap into the Terminal IIMB the aout file isthe compiled C++ code. Torun again, You need to navigate to the location of the code enter: fa.out and press Return. The the C++fileyou'vejust saved. Our exampleisin the Documents words ‘Hello World! appear on the screen. However, .out ist Folder, so we can navigate to it by entering: ed Documents, very friendly. To name it something else postcompiling, you can Remember, the Linux Terminals case sensitive, so any capitals recompile with: g++ helloworld.cpp-0 helloworld, This creates an ‘must be entered correctly output file called helloworld which can be run with: fhelloworld, Fett Vow Seach Teri Hp Fit Yon tach Ti ee Other C++ IDEs to Install Tana NEL Cue cl neRN geet Meese enous cc k a at Ue urmuss aolie etry con enea| =o deer cus iom escuela atte DEVELOPING C++ Here are ten great C++ IDEs that are worth looking into. You can install one or all of ther /ou like, but find the one that works best For you. ren Ste Eclnseisahugely popular C++ IDE that offers the programmer a wealth of Features. thas 3 ‘reat, clean interface, is easy to use and available For Windows, Linux and Mac. Head over to wwwelipse.org/downloads/ to download the latest version. If you'te stuck, click the Need Help link for more information, ‘The GNAT Programming Studio (GPS) isa powerful ‘and intuitive IDE that supports testing, debugging and code analysis. The Community Edition is free, whereas the roversion costs; however, the Community Edition is available for \windows, Mac Linux and even the Raspberry P.You can find tat wwrwadacore.com/downtoad. PRS TEMTTER odelite isa free and open source IDE that's regularly updated and available for Windows, Linux and macOS. t's lightweight, uncomplicated and extremely powerful. You can find out more information as well as howto ‘download and installit at www.codelite.ora/. ‘Another popular choice is NetBeans. This is another excellent IDE that’s packed with Features anda pleasure to use. NetBeans IDE includes project based templates for C++ that give you the ability to build applications with ‘dynamic and statc libraries, Find out more at www.netbeans.org/ Features/cpp/index.html. (C XX RTE) Microsoft's Visual Studioisa mammoth C++ IDE that allows you to.create applications for Windows, Android, iOS and the web. The Community version is Free to download and install but the other versions allow 2 ree tral period, Go to www.visualstudio.com/ to see what itcando For you. ERSTE Ts Save File As. Create or find 2 (on File> New > Empty File or press CurisShift#+N on the keyboard. suitable location on your hard drive and inthe ile Name box, call ithelloworld.cpp. Click the Save as type box and select C/C++ Files. ‘lick the Save button. ESTEE ow you can see a blank screen, withthe tab Bea You can see that Code:Blocks has now changed labelied *Untitiedt, and the number one inthe top the colour coding, recognising thatthe file's now left of the main Code:Blocks window. Begin by clicking in the main C++ cade. This means that code can be auto-selected from the window, so the cursors nextto the number ane, and entering Codes.Blocks repository, Delete the include line and re-enter it. You can see the auto-select boxes appearing, #include C Your First C++ Program CH ‘Auto-selection of commands fs extremely handy and cuts out potential mistyping, Press Return to getto line 3,then enter: int mainQ "Note: there's no space between the brackets, Peimncig gl ine hie, G-sien- FETE) onthe nextline below int maind, enter a curty bracket: { ‘This canbe done by pressing Shift and the key tothe right of Pon an English UK keyboard layout. Trelis all vcesitgdeoy wadeacasea fore My first C+ program [ewig wine mie. [Note again the colour coding change. Press Return at the end of the previous stepsline, and then enter ‘cout << “Hello, world!\n?; std: COPIED Gale Gee zecn «emia Besta m oar: Just. as before, Coder-Blocks auto-completes the Code you're entering, including placing a closing Siar) speech mark as soon as you enter the first. Dont forget the semicolon atthe end of the line; this sone ofthe most important ‘elements to a C++ program and wel tell you why in the next section. For now, move the cursor down to the closing curly bracket and press Return. aaejors. ioe ire ia Sits he e Learning the basics of programming, you begin to understand the structure of a program. The commands may be different from one language to the next, but you wil start to see how the code works. on #INCLUDE Stxthere | “helloworld.cyp The structure ofa Ces program CrewasimentedbyDansh saute pecs. Evry Cre code studentGlaneStousrupin begins witha directive: include 1979, sapartoFhis PAD. ‘©. Te directive instuctsthe thesis. initially C++ was called C pre-processor to include a. vith Clases which added Section ofthe standard Gre Features to the already popular code. For example: #include programing anguace incudesthe iterating more iostreamheader to support user-friendly environment: input/output operations. through anew structure Bjame Stroustruy INT MAIN() “Starthere —-X *helloworld.cpp {nt main) intiates the ‘Finclude declaration ofa function, which isa group of code statements int main() under the name ‘main’. All (C++.code begins at the main function, regardless of where it ‘actually ies within the code. Stathere | *helloworkd.cpp Ee ‘The open brace (curly brackets) is something #include that you may not have come across before, ‘especialy if you're used to Python, The ‘open brace indicates the beginning of the main function and contain allthe code that belongs to that Function int main() a COMMENTS Lines that begin with a double slash are comments.This means they won't be executed in the code and are ignored by the compiler, Comments are designed to help you, or another programmer looking at your code, explain what's going on, There are two types (of comment: /* covers multiple line comments, // single line. Lines that begin with a double slash are comments. This means they won't be executed in the code and are ignored by the compier. Comments are designed tohelp you, or another programmer looking at your code, explain what's ‘going on. There are two types of comment: /* covers ‘multiple ine comments, // 3 single ine, ant main) lev (Structure of a C++ Program CH << ‘The two chevrons used here are insertion operators. This means that whatever Follows the chevrons isto be inserted into the std:cout statement. In this case they're the words Hello, world, hich are to be displayed on the screen when you compile and execute the code, STD \while std stands for something quite different, in C++ it means Standard. 's part ofthe Standard Namespace in C+, which covers. ‘a number of ifferent statements and commands. You can leave the stds part out of the code but it must be declared atthe start with: using namespace std; not both. For example: #include using namespace std; COUT Inthis example we're using cout, which isa part of the Standard "Namespace, hence why t's there, as you're asking C++ to use itfrom that particular namespace. Cout means Character OUTput, which displays, or prints, something to the screen. If we leave std: out we have to declare it atthe start of the code, as mentioned previously. [Bathe] “hetoworidcop > 1] #include 20 OUTPUTS Leading on, the “Hello, wari” partis what we want to appear on the screen when the code is executed. You can enter whatever you lke, as long asits inside the quotation marks. The brackets aren't needed but some compilers insist on them, The \n partindicates a new line isto be inserted //My first C++ program cout << “Hello, world! n” ; AND} Finally you can see that lines within a Function cade block (except comments) end with a semicolon. This marks the end of the statement and all statements in C++ must have one at the end or the compiler Fails to build the code. The very last ine has the closing brace to indicate the end of the main Function. [[Bethee ST “hetowerideon _%) 7] Hnciude 2 | using namespace sta: 4 | int ming) s ‘ 7 cout << *Hello, world! \n"; Be) C++ Fundamentals ) Compile and Execute Senha esere tue NM ech eet nis Rte om eer eau uke crake Marts you prefer, the program and see how it looks. GREETINGS FROM C++ Compiling and executing C++ code from Code::Blocks is extraordi result, Here's how it's done. FETTER open code:Blocks,ifyouhaven't already, and load up the previously saved Hello World code you created. Ensure that there are no visible errors, such as missing semicolons at the end of the std:cout lin, PEPPER i yourcode is looking similar tothe one in our screenshot, then look to the menu bar along the top of the screen. Under the Fortran entry in the topmost menu you can see a group of cons: a yellow cog, green play button and a cog/play button together. These are Build, Run, Build and Run functions. ly easy; just a matter of clicking an icon and seeing the STEED t2ttby clicking onthe Build icon, the yellow cog Acthis point, your code has now been run through the CodeBlocks compiler and checked For any errors. You can see the results of the Build by looking to the bottom window pane. Any messages regarding the quality ofthe code are displayed here. [Now click on the Run icon, the green play button. ‘Acommand line box appears on your screen displaying the words: Hello, world, followed by the time it’s taken. toceecute the code, and asking you press akey to continue. Well using namespace std; cout << a; cout << "\n"; fnematn bs 7 The cout <<"\n'spart simply places anew line between the output of toands. int main() q I FEED Se2ttsimple by creating two variables, aandb, with [ESSAI Naturally you can declare a new variable, call it ‘one having avalue of 10 and the other S. You can result and output some simple arithmetic: use the data type int to declare these variables. Within the curly brackets, enter: int resuli result = a +b; int a; int lb: cout << result; ame: fomon sins Insert the above into the cade as per the screenshot. Eas sant masn() posi <1 You can sssign avalueto variable ass00n as ou SUPE declare it. The code you've typed in could look like this, instead: int a = 10; int b = 5: int result = a +b; cout << result FETTER Seecificto C++, you can also use the following to.assign values to a variable as soon as you declare them: Bee The previous step creates the variable StartLives, which is a global variable. Ina game, For example, {players lives go up or down depending on how wel or how bad they're doing, When the player restarts the game, the StartLives| returns to its default state: 3. Here we've assigned 3 lives, then subtracted 1, leaving? lves lft. FETED The modern c++ compiler is far more inteligent than most programmers give it credit. While there ‘are numerous datatypes you can declare For variables, you can in fact use the auto Feature: include using namespace std; ‘auto pi = 3.141593; int mainc) { double area, radius = 1.5; int @ (0); . oo int 6G); area = pi * radius * radius; Then, from the C++ 2011 standard, using curly brackets: cout << area; int result {a+b}; t = Gather x werencay FETS You can create global variables, which are variables that are declared outside any Function and used in any Function within the entire code, What you've used so far are local variables: variables used inside the Function. For example: #include using namespace std; int StartLives = 3; int main © { startLives = StartLives - cout << Startlives; FEPETR) courte of new elements here: first, auto won't work unless you go to Settings > Compiler and tick the box labelled ‘Have G++ Follow the C++11 ISO C++ Language Standard [std=c++1J. Then, the new data type, double, which means double-precision floating point value. Enable C++, then build and run the code, The result should be 7.06858, C++ Fundamentals Data Types THE VALUE OF DATA There are many different datatypes avaliable forthe programmer in Ces, such as an integer, floating point, Boolean, character and so cn. I's widely accepted that there are seven basic datatypes, often called Primitive Bultin Types; however, you can create your Own, data types should the need ever arise within your code, ‘The seven basic data types are: Integer oat eran) oot double wchor-t void These basic types can also be extended using the Following modifiers Long, Short, Signed and Unsigned, Basically this means the modifiers can expand the minimum and maximum range values for each data ‘ype. For example, the int datatype has a default value range of 2147483648 to 2147483647, a fair value, you would agree. Now, ifyouwere to use one ofthe modifiers, the range alters: 00 4294967295 2147483648 to 2147483647 Unsigned int Signed int 2768 to 32767 ‘ong int = 2147483647 to 2147483647 Signed Long int =-2147483647 to 2147483647 Unsigned Long int = Oto 4284967295 Naturally you can get away with using the basic type without the ‘modifier, as there's plenty of range provided with each datatype. However, it’s considered good C++ programming practise to use the ‘modifiers when possible. ‘There are isues when using the modifiers though. Double represents a double-floating point value, which you can use For incredibly accurate numbers but those numbers are only accurate upto the fifteenth decimal place. There's also the problem when displaying such numbers in C++ using the cout Function, in that cout by default only outputs the First five decimal places. You can combat that by adding a cout precision () Function and adding a valve inside the brackets, but even then you're stil imited by the accuracy ofthe double data type. For example, try this code: #include using namespace std; double PI = 3.141592653589793238463; int mainQ) { t cout << PI; Storthere + 2 using namespace sta: 3. | double Pr 4 5 int main ef » | \Weer devi Documert\C+ DatTypeno Build and run the cade and as you can see the outputis only 3.14158, representing cout’ limitations inthis example You can alter the code including the aforementioned cout:precision Function, For greater accuracy. Take precision allthe way up to 22 ‘decimal places, wth the Following code: #include using namespace std; double PI = 3,141592653589793238463; int mainQ) { cout .precision(22); cout << PI; a 3 4 Sint main) 6 7 cout precision (22); ® cout << PIs ‘Again, build and run the code; as you can see from the command line window, the number represented by the variable Plis diferent to the number you've told C++ to use in the variable. The output reads the value of Plas 3.141502653589793115998, with the ‘numbers going awry from the fifteenth decimal place. Calculator - x Scientific Dd 15.142857142857142857142857142857 bec We FE Me Ms “a sin cos tan 10 fogs Exp Mod ae ae: c a ™1|7i]8s | 9 Ix mo] 4]5 | 6 |= =] 1] 2|3 ee ( ) oO . = ‘This is mainly due to the conversion from binary in the compiler and that the IEEE 754 double precision standard occupies 64-its ‘of data, oF which 52-bits are dedicated to the significant (the significant digitsin a floating-point number) and roughly 3.5-bits are taken holding the values 0 to 9. IFyou divide 53 by 35, then you artive at 15.142857 recurring, which is 15-cigits of precision ‘To be honest, iF you're creating code that needs to be accurate to more than fifteen decimal places, then you would’ be using C+, you would use some scientific specific language with C++ as the ‘connective tissue between the two languages, You can create your own data types, using an alias-lke system called typedef. For example: =i wed BI crvetee tov oecear include using namespace std; ‘typedef int metres; int main) { metres distance; distance = 15; cout << “distance in metres is: << distance; This code when executed creates a new int datatype called metres Then, in the main code block, there's a new variable called distance, which isan integer; so you'e basically telling the compiler that there's another name forint. We assigned the value 15 to distance ‘and displayed the output: distance in metres i 15. Iemight sound a ittle confusing to begin with but the more you use C++ and create your awn code, the easier it becomes. =~ Zz 2 ) C++ Fundamentals ) Strings Sacer cae Rte kiki ecea ce cunt TT EV EM ele Coe eR ole sce MVOC MUO fe are ee Eee co Cellet Ra NRO Ma ence STRING THEORY There are different ways in which you can create a string of characters, which historically are all carried over From the original Clanguage, and are still supported by C++. ‘Tocreate astring you use the char function. Open a new C+ file and begin with the usual header: #include using namespace std; int main © { } wealvaporson gaye ec os [rv using namespace std; int main © les easy to confuse a string with an array. Here's an array, which can be terminated with a null character: char greet[8] = {'W’, ‘e’, ‘1’, ‘c’, ‘0%, ‘m’, EETTSEDD cud andrun the cade, and Welcome’ appears fon the screen. While thisis perfectly fine, it's nota string, A string i a class, which defines objects that can be represented asa stream of characters and doesn't need to be terminated lke an array. The code can therefore be represented as: #include using namespace std; int main © { char greet{] = “Welcome”; cout << greet << “\n"; you can enter: In C++ there’ alco a string Function, which works in ‘much the same way. Using the greeting code again, #include using namespace std; int main © i *e, 0s string greet = “Welcome”; cout << greet << “\n"; cout << greet << “\n"; 3 } ks FEED) There are also many different operations that you can apply with the string Function. For instance, to getthe length ofa string you can use #include using namespace std; int main © { string greet = “Welcome”; cout << “The Length of the string is: cout << greet.size() << “\n"; You can see that we used greet size()to output the length, the number of characters there are, ofthe Contents ofthe string. Natural, if you call your string something ‘other than greet, then you need ta change the cammmand to reflect this. It's always stringname.operation. Build and run the code to see the resus. You can of course add strings together, or rather combine them to Form longer strings: STEP7 #include Using namespace std; int main © { string greet = “Hello”; string greet2 = “, world!”; string greet3 = greet + greet2; cout << greet3 << “\n"; ‘example, we created int length, which stores the result of string, sizeQ and outputs ito the user: #include using namespace std; int main © { ‘int Length; string greet = “Hello”; string greet2 = “, world!"; string greet3 = greet + greet2; Length = greet3.sizeQ; cout << “The Length of the combined strings is: << length << “\n"; Using the available operations that come with the string Function, you can manipulate the contents of 2 string. For example, to remove characters froma string you could use: #include using namespace std; int main © a string strg (“Here is a long sentence in a string.”); cout << strg << "\n’; strg.erase (10,5): cout << strg << ‘\n"; strg.erase (strg.begin()+8); cout << strg << ‘\n’; strg.erase (strg.begin()#9, strg.end()-9); cout << strg << ‘\n’; FETS ER Es worth spending some time playing around with the numbers, which are the character positions in the string, Occasionally, it can be hit and miss whether you gett right, so practice makes perfect. Take a look at the screenshot to see the result of the code. C++ Maths Se ED UE eu e EEN UIT ster see caso Pence Senet encanta ge ed eer old elie eae er Cenc ce icines een tu Rct as ioc venaG The basic mathematical symbols apply in C++ as they do in most other programming languages. However, by using the C++ ‘Math Library, you can also calculate square roots, powers, trig and more. FR matnenatl operations foow he Matipleaton addin canbe ape 2 50h same pater asthe ought in scoe nthat #include ‘multiplication and division take precedence over addition and 7 subtraction, You can alter that though. For now, create a new file Using mmesracenstay and enter int main © { #include float numbers = 100; using namespace std; IIe runbers = nunbers * 10; // This multiplies 100 : by 10 float numbers = 100; cout << numbers << “\n"; numbers = nunbers +10; // This adds 10 to the nunbers = nunbers / 10; // And this divides initial 100 1000 by 10) cout << numbers << “\n"; cout << nunbers << “\n"; numbers = numbers - 10; // This subtracts 10 } from the new 110 cout << numbers << “\n"; PEED wile simple, does get the old maths muscle ‘numbers variable. While you can happily use an integer, iF you FID 2, execute the simple code ad see the resus suddenly started to use decimals, you would need to change toa While not particulary interesting, it's start into Crs Float or double, depending on the accuracy needed. Run the code maths. We used afloat here, so you can play around with the code and see the results. ‘and multiply by decimal places, as well as divide, add and subtract. (cones CH Everything From computing cosine to arc tangent with two parameters, to the value of Pl, You can call the header with: #include #include using namespace std; int main © Bird Start by getting the square root ofa number: #include #include using namespace std; int main © { float nunber 134; cout << “The square root of “ << number << “ is: << sqrtCnumber) << “\n"; } Here we rested anew ost cle number and Suzy used the sqrt(number) Function to display the square rotof 134, the value ofthe varbe number Bul and run the code, and your answer reads 11.5758. PEED 2lculating powers of numbers can be done with: include ifinclude using namespace std; int main © { float nunber = 12; cout << number << “ to the poner of 2 is “ << Pow(number, 2) << “\n"; ‘cout << number << “ to the poner of 3 is “ << Pow(nunber, 3) << “\n"; cout << number << “ to the power of .08 is << pow(nunber, 0.8) << “\n FETED ere we created a float called number withthe value of 12, and the pow(variable, power) is where the calculation happens. Of course, you can calculate powers and ‘square roots without using variables. For example, pow (12,2) ‘outputs the same value as the frst cout line in the code. The value of Plis also stored in the cmath header library. tcan be called up with the M_Pl function. Enter cout << M_Ptinto the code and you get 3.14159; ar you can use it to calculate: #include #include using namespace std; int main © i double area, radius = 1.5; ‘area = MPI * radius * radius; cout << area << “\n": => C++ Input/Output “Measuring programming progress by lines of code is like Measuring aircraft building progress by weight.” ~ Bill Gates (Co-founder of Microsoft) iC) aa laeleies Output Sees one ce Ran Pc eee tas auntie nia ed acer te eines gene ean) iFit’s simply asking for someone's name Soe eee een ec ce De ee nc Serer cs Mere Me Pee Uc lcd EUR UR Ren ame our iy Ene eee eee ats Following pages. All of which will help Ret seme eres Pree es coo _ => C++ Input/Output ) User Interaction See nek Mice ee San eee aCe Trica ccs eR TORIES Penta tetsu nec ecto macau hens SUoVEK elo heReo Maeno Men MES Re Koa an eC Loe HELLO, DAVE You have already used cout, the standard output stream, throughout our code. Now you're going to be using cin, the standard put stream, to prompt a user response. ESTEE RED 7ything that you want the user to input into the program needs tobe stored somewhere in the system memory, soit can be retrieved and used. Therefore, any input must fist be declared asa variable, so it’s ready to be used by the user. Start by creating a blank Ce+ file with headers. Winclude using namespace sta; int main () FETED The date type ofthe variable must also match the type of input you want from the user. For example, toaska user their age, you would use an integer like this: #include using namespace std; int main © { ‘int age; cout << “what is your age: cin >> ages cout <<”\nYou are “ << age << * years old.\n”; EERE the cin command works in the opposite way from the cout command, With the fist cout line you're ‘outputting Whats your age’ to the screen, as indicated with the ‘chevrons. Cin uses opposite Facing chevrons, indicating an input. The input is put into the integer age and called up in the second cout ‘command. Build and run the code. yore asking a question, you needa store the suas) input asa string; to ask the user their name, you would use: #include using namespace std; int main © { string nane; cout << “what is your name cout << “\nHello, “ << name << * well today?\n"; E aia Sa «ble Felon + T hope you're The principal works the same as the previous code. The user's input, their name, is stored in a string, ‘because it contains multiple characters, and retrieved in the second cout line, As long as the variable ‘name’ doesn't change, then you can recalit wherever you liken your code. You can chain input requests to the user butjust ‘make sure you have a valid variable to store the input to begin with. Lets assume you want the user to enter two whole numbers: #include using namespace std; int main © ‘int num, num2s cout << “Enter tno whole nunbers: cin >> num >> num2; and “ << cout << “you entered “ << num << ‘aun << “\n"; BETISE RD Uicwise, inputted data can be manipulated once youhaveit stored in a variable. Fer instance, ask the ser For two numbers and do sore maths on them #include using namespace std; int main © { float num nun2; cout << “Enter two nunbers: \n"; cin >> num >> numa; cout << num << “+ using namespace std; int main © { string mystr; cout << “Enter a sentence: \n"; getline(cin, mystr: cout << “Your sentence is characters Long.\n"; } “ << mystr.sizeQ << ud and execute the code, then enter a sentence with spaces. When you're done the code reads the number of characters. IF you remove the getline line and replace it ‘with cin >> mystr and try again, the result displays the number of characters upto the First space, Getine is usually a command that new C++ programmers forget to include. The terminating white space is annoying when you can't figure out why your code isnt working. In shot, it’s best to use getline(cin, variable) in Future: #include using namespace std; int main © i string name; cout << “Enter your full name: \n"; getlineCcin, name); cout << “\nHello, “ << name <<“ User Interaction cl Na AVAXHOME? nee cd providing you various content: LC eC ao Ee ee eS mea eas ces Unlimited satisfaction one low price Cheap constant access to piping hot media Protect your downloadings from Big brother Safer, than torrent-trackers 18 years of seamless operation and our users' satisfaction PRE Uys ETC emer ol Tei AvaxHome - Your End Place We have everything for all of your needs. Just open https://avxlive.icu _ => C++ Input/Output) Character Literals In C++ a literal is an object or variable that once defined remains the same throughout lent Keele Ma Renee ere eRe eek ED orec Ch IeenEcen AUR ol RC eee ureg teeters renee Ue ESCAPE SEQUENCE When used in something like a cout statement, character literals are also called escape sequence codes. They allow you to insert a quote, an alert, new ‘and much more. PETTSEDD reate anew c++ file and enter the relevant headers: Hinclude using namespace std; ‘int main ‘include ant main 0) You've already experienced the \n character literal placing anew tine wherever i’ called. The line: cout -<<"Hello\n” << "I'ma C+4\n" << "Program\n"; outputs three lines of text, each starting after the last x errrcr) a IF you wanted to insert speech quotes inside a cout already uses quotes: #include using nanespace std; int main © { cout << “Hello, user. This is how to use Vequotes\”.”5 ‘There's even a character literal that can trigger an Bary alarm. In Windows 10, t's the notification sound that chimes when you use \a Try this code, and turn up your sound, #include using namespace std; int main © i cout << “ALARM! \o"; } Rie s[r* C++ Input/Output ) Defining Constants Constants are fixed values in your code. They can be any basic data type but as the ened ieee ccna nett nto Menta) Seek ie ound keene ca perce thous #DEFINE The pre-processors are instructions to the compiler to pre-process the information before it goes ahead and compiles the code. clude isa pre-processor ass #define. BEPTSEDD You can use the itdefine pre-processor to define any constants you want in aur code, Start by creating a new C+ file complete with the usual headers: #include using namespace std; int main Q { } t Gis ther with besansennil Now les assume your code has three different constants: lenoth, width and height. You can define #include Using namespace std; define LENGTH 50 define WIDTH 40 define HEIGHT 60 int main © i PETS DD Note the capitals for defined constants, it’s considered good programming practise to define all constants in capitals, Here, the assigned values are 50, 40 and 60, so let'scallthem up: #include using namespace std; ‘define LENGTH 50 define WIDTH 40 define HEIGHT 60 int main © i cout << “Length is: << LENGTH << \n"; cout << “Width is: “ << WIDTH << “\n"; cout << “Height is: “ << HEIGHT << “\n"; EETISE DD Guild andrun the code, Just as expected, it displays the values for each of the constants created. 's ‘worth noting that you don't need a semicolon when you're defining ‘constant withthe #define keyword. 1 ehedestOmanel imams - Defining Constants Cl You can also define other elements asa constant For example, instead of using \n for a newline in the cout statement, ou can define it at the start ofthe code: #include using namespace std; define LENGTH 50 Hdefine WIDTH 40 define HEIGHT 60 define NEWLINE ‘\n? int main © i cout << “Length is: “ << LENGTH << NEWLINE; cout << “Width is: “ << WIDTH << NEWLINE; cout << “Height is: “ << HEIGHT << NEWLINE; The code, when built and executed, does exactly the same as before, using the new constant NEWLINE to insert a newline in the cout statement. Incidentally, creating @ ‘newline constant isn'ta good idea unless you're making it smaller than \n or even the endl command. FETED Defining a constant isa good way of iitaising your base values atthe stat of your code. You can define that your game has three lives, or even the value of Pl without hhaving to call up the C++ math ibrary #include using namespace std; define PL 3.14159 ‘int main © cout << “The value of Pi i “ ce PI << endl; ‘Another method of defining a constants with the const keyword. Use const together with a datatype, variable and value: const type variable = value. Using Pias an example: #include using namespace std; int main © { const double PI = 3.14159; cout << “The value of Pi is: “ << PI <« end ¥ Because you're using const within the main block of code, you need to finish the line witha semicolon You can use either, as long asthe names and values don't clash, but it’s worth mentioning that #define requires no memory, so if you're ‘coding toa set amount of memory, #define is your best bet. Const works in much the same way as define, STEP 10 You can create static integers and even newlines: #include using namespace std; int mainQ) i const int LENGTH = 50; const int WIOTH = 40; const char NEWLINE = ‘\n"; int area; ‘rea = LENGTH * WIDTH; cout << “Area is: “ << area << NEWLINE; File Input/Output The standard iostream library provides C++ coders with the cin and cout input and output Functionality. However, to be able to read and write froma file you need to ieee a Gee ODI eer FSTREAMS There are two ms data types within the Fstream library that are used to open ale, read From it and write to it, ofstream and stream. Here's how they work, FETTER The First taskisto create anew C++ file and along with the usual headers you need to include the new fstream header: #include #include Using namespace std; int main © ‘finciude fanclude #include using namespace std; int main © { string none; ofstream nenfile; nnewfile.open(“nane. txt"); cout << “Enter your name: “ << endl; getlineccin, none); nenfile << name << endl; nenfile.close(); ESTISED) We've included comments in the screenshot of step 2 tohelp you understand the process. You created astring called name, to store the user's inputted name, You also created a text file called name.txt (with the ofstream newfie and newfile.open lines), asked the user for their name and stored itand then writen the data to the fle. Toread the contents of afile, and output itto the screen, you need to do things slightly differently. First you need to create a string variable to store the file's contents {line by line), then open the fle, use getline to read the file line by, line and output those ines to the screen. Finally, close the File string Line; ifstream newfie (name. txt”); cout << “Contents of the file: “ << endl; getlineCnenfile, Line); cout << Line << endl; nenfile.closeQ; The cade above s great For opening afte with one ortwo lines but what if there are multiple lines? Here xt file of the poem Cimmeria, by Robert E Howard steps we openedal string Line; ifstream newfile (*c:\\users\\davia\\, Documertts\\Cinmeria, txt”); cout << “Cimmeria, by Robert E Howard: \n? << endl; virile CgetlineCnewfile, Line)) cout << line << endl; newfle.closeQ); FEED Youcanno doubt see that we've included a while loop which we cover in 3 Few pages Lume, le means that while there ate lines to be read from the text file, C+ getlines them. ‘Once all the lines are read, the outputis displayed on the screen and the fief closed. FPTIEDD You can also see thatthe location ofthe text Fle Cimmeria.txt isnt inthe same Folder asthe C++ gram, When we created the First name txt fle, it was written to the same folder where the code was located; this is done by default To specify another Folder, you need to use double-back slashes, as per the character iteralslescape sequence code. Fiero CRE Just. as you might expect, you can write almost S18 anything you like to a file, for reading either in. Notepad or va the console through the C++ code: string name; ‘int age; ofstream newfile; newfile.openC‘name txt” cout << “Enter your none: “ << endl; getline¢cin, nane); nenfile << nane << endl; cout << “\nHow old are you: “ << endl; cin >> age; newfile << age << endl; newfile.closeQ); FEED The code from step 8 differs again, But only where itcomes to adding the age integer. Notice that ‘we used cin >» age, instead of the previous getine(cn, variable), he reason For this is thatthe getline Function handles string integers; so when you're using a data type other than a sti the standard cin, SEP TD write several different elements to a text File, You can have a user's name, age, phone number ete. Maybe even the value of Pi and various mathematical elements t's all good practic, Loops and Decision Making _) —Pamela Zave (Developer, scientist and telecommunications expert) Loops and Decision Making eee ee ed ed important Factors of any programming language. Good use of a loop will create a eee eas it to and delivers the desired outcome Reet ence ‘Without loops and decision-making Seu ers RE ce eRe Pee eC ica ae crn is Tec U Ree Ld Sete reer e neat) ue kc Ce zx Loops and Decision Making While Loop Pees ne eee cuca et Rages em Ce Tecreli eon eu ECR una iiel ooe um aecle a celiac Contd een ee cue net aiaaamtcl els TRUE OR FALSE? While loops are one of the most popular Form of C++ code looping. They repeatedly run the code contained within the loop while the condition is true. Once it proves false, the code continues as normal Clear what you've doneso fr andcrete anew C++ nar) file. Ther weno ad For any extra headers at the SIEPS need to moment, so add the standard headers as per usual reate a condition, o use a variable called num and give ithe valve 1. Now create the while oop, stating that #include using namespace std; ‘int main © slong as num sess than 30, the loopistrue. within ' the loop the value of num ¥ is displayed and adds t until its more than 30. FETPD Were introducing afew new elements here, The Fist are the opening and closing braces for the hile loop. This is because our loop isa compound staternent, meaning a group of statements; note also, there's no semicolon after the while statement, You now also have return 0, which is clean and preferred way of ending the code, FETED cate asimple while loop. Enter the code below, build and run (we've added comments to the screen shot: t - int num = 15 sie ~ while (num < 30) - { cout << “Number: “ << num << endl; run = num 41; : Ep coed PPI you didn't needto se the continual increasing return 05 value of num, you could have done away wth the ¥ compound while statement and instead just added num by selh: Lntilit reached 30, and then displayed the value { ‘int num = —_ while Crum < 30.) cout << “Number: “ << num << endl; return 0; you place one atthe end ofa while statement, your loop will be permanently stuck until you close the program. Inour example fwevwere to execute thecode usr the value of num would be 1, as set by the int staernent. when the code hits the wile statement reads thot wil the condition of 1 being ss than 30's velop. The semicolon closes then, the oop repeats but never adds 1 tum. a5 Ron conte Brough the compound statement wiietcon GE FeTeeE DD) You cen further expand the code to enable each word of the poem to appear every second, To do 50, you need to pullin anewlibrary, «windows h>, This isa Windows only library and within you can use the SleepQ Function: #include #include using namespace std; int main © { string word; ‘ifstream newfie (*C:\\users\\david\\, Documents\\Cimmeria. txt" cout << “Cinmeria, by Robert E Honarc endl; While Cnewfile >> word) \n” << { cout << word << endl; Sleep(1000); } return 0; the loop. For example, to read the poem, Cimmeria, word by word, you would enter: #include #include > word) { cout << word << endl + return Q; BERT Sicep0] works in milseconds, so Sleep(1000) is ‘one second, Sleep(10000) is ten seconds and so €on, Combining the sleep function (along with the header it needs), ‘anda while loop enables you to come up with some interesting countdown code. #include include using namespace std; int main © i int a= 10; while (a != 0) { cout << a << endl; a=a-1; Sleep(1000): cout << “\nBlast OFFI” << endl; return 0; Insome respects, a for loop works in a very similar way to that of a while loop, although it's structure is different. A for loop is split into three stages: an initialiser, a condition and an incremental step. Once set up, the loop repeats itself until the condition becomes False. LOOPY LOOPS The initialise stage of a For loop is executed only once and this sets the point reference for the loop. The condition is evaluated by the loop to see iF it’s true or False and then the increment is executed. The loop then repeats the second and thi stage. PEPTIEDD create anew C++ ile with the standard headers: #include using namespace std; int main Q i | Gis Start simple and create a for loop that counts from 1 to 30, displaying the value to the sereen with teach increment: t //For Loop Begins for€ int num = 1; num < 30; num = num +2) { cout << “Number: “ << num << endl; 3 return 0; ESTER Working through the process ofthe for loop, begin, by creating an integer called num and assigning ita value of 1. Next, set the condition, in this case num being less than 30. The last stage is where you create the increments; here it's the value of num being added by 1 et li eaten ) After the loop, you created a compound statement inbraces (curly brackets, that displays the current valve ofthe integer num. Every time the for loop repeats itself, the second and third stages ofthe loop, it adds 1 untilthe condition <30 isfalse. The loop then ends and the code continues, ending neatly Siar with return 0. i for( int num = 1; num < 90; num = num +1) cout << "Number: " << num << endl; return 0; ‘Aforloopis quite ane package ines, al ear contained within its own brackets, while the other ‘elements outside of the oop are displayed below Ifyou want to create a 10-second countdown, you could use #include #include using namespace std; int main © i 7/For Loop Begins for( int a= 10; a { cout << a << endl; Sleep(1000); cout << “\nBlast OFFI” << endl; return 0; F th the countdown code, don forgettoinclude r'san example of for loop displaying the EPS the windows.h library, so you can use the Sleep SuaPe) multiplication tables of a user inpx number, command. Buldandrun the codeinthe command conoleyoucan andy fr stents seethermber Toto | ountdowninonesecondincementsunth reaches and Blast Of peas int ny 1 cuneate cout << “Enter @ nunber to view its times table: “; cin >> nj for Cint i= 1; i <= 125 +i) { cout using namespace std; int main © { the body ofthe loop is executed a least once, checked for either true or false } ot a= tha simple number count Seep 2" iemtnecmnisnts EZD ecowtenne te — continues until the condition is do jonas been expressed as False, the { fe conti cout << “Number: continues until the user ent run = num + 1; fecuted. This ie. When the sminates and the were the code << num << endl; ¥ while Cnun < 30); return 0; Do..hietoor CREE IF you want code to add up user inputted numbers BED ally, the while statement checks the condition UEP until the user enters zero: Sar) of the variable number. If the user has entered foot nae, = 0.0 ae oe While loop continuously ****” << endl; dot ‘cout<<"\nPlease enter a number: cimsnunber; sun += numbers wwhileCnumber = 0.0); ) a s ai ‘ cout << a << end a=a-1; } while Ca = 0); = . cout << “\nBlast OFFI” << endl; return 0; BETES The code from Step 5 works as follows: two floating E mrt point variables are assigned, number and sum, bath with the value of 0.0, There sa brief set of instructions forthe user, then the do... while loop begins. : cesses EERE sree cease oF waa. whietop BED [2<0,-\hleloopintisinstaceasisthe user rieloop san etrycontolloop. Therefore, your code requires ater numb eek arunber which you ssined tothe fest oop that needs tobe excated at east once (or example to check point variable, sum, which adds the value of number everytime the the number of les in agame), then ado... while loop is perfec IF Statement FO eee Ure ecard te keen TY Pre CUM ute emer eM nae emma) SOR Ta BOM acse or ce stdout Mera atone out meet iet og tla eC meORur le IF ONLY {fuses a Boolean expression within its statement. If the Boolean expression is true, the code within the statement is executed. If not, then the code after the statement is executed instead. PEPER Fist create anew C++ file and enter the relevant standard headers, as usual: #include using namespace std; int main © t } FETS EE If isbest explained when you use a number based condition: { int num = if (mum < 30) t cout << “The number is less than 30.” << endl; 2 cout << “Value of number is: “ << num << endl; return Q; 1 ‘include ‘using namespace std; int main ( What's going on here? To begin, an integer called ‘num was created and assigned with the value of 1 ‘The Fstatement comes next, and in this case we've instructed the ‘ode thatif the concition the value, of numislessthan 1, then the ‘code within the braces should be executed, The second cout statement csplasthe rent cus? value of num and the program terminates safely. It's 2s toate how te statement works you were change the iil vale of rum from 18933. ——— #include sing namespace sta? int main () int num Woeryoucangetbewietomntingskoe —— ETRERER) The coining Fate Suze +30, then build and run the code, you can see that Sart created a floating point integer called temp, then 2 theoniytne tobe outputted tothesceenisthesecond cost _-do..wlelop that ass the user tener the crent temperature Sttement delaying the caren vlve of ru, Tiss becouse inal statement sabe, sot gnares the code thin the races PEP The firstif statement checksto see ifthe user's da . . inputted value isles than or equal to zero. IFitis, FR canincude ani statement withinad,.whte ten the outputs rr isrealy col Otherwise ithe nots loon For eamnpl areater than zero, the code outputs ‘Atleast i's not Freezing! ¢ float temp; i ie me a cout << “\nEnter the tenperature Cor ‘eo -10000 to exit): * << endi cin >> temp; ee “ iF Ctem <= 0) f ally, if the user enters the value -10000, which is cout cc oberrey it's reoty cota” ESTES << endl; 178) impossibly cold so is therefore a unrealistic value, the do... while loop is terminated anda friendly Good bye" is if Ctem > 0) displayed to the screen. cout << “\nAt least it’s not freezing!” << endl; ? hile C temp != -10000 >; cout << “\nGood bye\n” << endl; return 0; man = ror — FETS EREOD Usa tfis quite powerful if t's used correctly. Just remember that ifthe condition i true then the ‘executes what'sin the braces, I not, continues on its merry way. See what else you can come up with using if and a combination oF loops. IF... Else Statement See Me tte e lau geo AUT eco eC Me Se Oech nice asec etme ete casemate Renate tod meee IF YES, ELSE NO There are two sections of code that can be executed depending on the outcome in an if... else statement. It's quite easy to visualise once you get used to its structure, ESTED Becin with anew c++ fle and the standard headers: ENE he first line in the code creates the integer called ‘num and givesita value of 1. The iFstatement using namespace std; | sr!" sasermace acs: ‘outputs "The numbers ess than 30! to the console, int main © a ‘ | ere :P areca ; The else companion to if checks f the number BETEEE (22s 230end the code rom the FStatement onthe Ha aD eee ee i oerhe — number is greater than 30!" to the console; and finally, the code is 4 terminated satisfactorily int num = 15 see oo tna Se OF Ta war DoE era if Crum < 30) : { cout << “The number is less than 30!” << LL ENS SE Es ST endl; 3 as PIR vo. can change the value of nmin the code or cout > nun; ‘if C num < 30) t cout << “The number is less than 301” << endl; ¥ else { cout << “The number is greater than 30!” << endl; Y return 0; user entered the number 30? Try this: { int num; if (mum < 30) { cout << “The number is Less than 30!” << endl; i else if num > 30) { cout << “The number is greater than 30!” << endl; else if ( num == 30) { cout << “The number is exactly 30!” << endl; } return 0; : The new addon tothe code whats known asa ua nested if... else statement. This allows you to check for mulpe conditions inthis case, the user enters arumber less han 30, rete than 30 or actualy 30 tel a ierent outcomes presented totem, FED vo ccicicwarnscenstosie cin >> num; cout << string(50, FRPP The cout <> guess; triest+; if (guess > num) { cout << “\nToo High!\n” << endl; else if (guess < num) cout << “\aToo Low!\n" << endl; else if (guess == nun) { cout << “Well don tries << guesses!” << endl You got it in“ << 7 } while Cquess: return 0; pun); Grab a second player, then build and run the code, Player One enters the rnumber to be guessed, then Player Two can take ‘as many guesses as they need to get the right number. Want to make itharder? Maybe use imal numbers Combining All You Know Pee ace Reeacune ace a tM s i td Me in ease ied cee as ali power of C++ is what makes it such a spectacular language to learn. Now, how about combining all you've learned so far. REACH FOR THE STARS We're going to mix many elements of what we've looked at so Far to create code that will animate a rocket blasting off into space, There's alot than can be done with this code, so Feel Free to play with it. BED iscesewinainina terete ERAEB ven ete sina toceneacupea a processor, tnele sestream, but abo acs new Seng thal contin AS mages hat we can se fone: include this is or that provides access inthe code. You can oF course ch artistically othe P fre going touse it inclined, however, ifyoure eh For x = Fes 3 using nanespace sta: sl PEED the ascitar messy to beg) Remember though, ecognised anda ‘att ine to signify 2 new ln ime to get right. You c esults by entering Int mainQ { cout << background << “\n" << rocket; f continingl'vou now COX cout statements and enter the Following: string greet int x05 cout << background; cout << “\n"; hile Cgreet [x] !="\0") { cout << greet[x]; usleep(95000); } string nae; cout << “\n® << “\n” << “What is your name, brave astronaut? “; cin >> nane; cout << flush; cout << “Press Enter for take off, “ << nane << “An; cin. ignore}; cin.getO; ESTEE) What you've done heres z create a simple greeting string, displayed the background ASCII artand asked the user for their name. Notice there's a While loop that will display the greet string, one letter at atime, untilit reaches the end of the string, The cout <« flush statement clears the screen and cin.get pauses, until the user its Enter, BEPTD For the last section of the code, ente for Cint i = 0; i < 50; i ++) cout << “\n?; cout << rocket; int j = 300000; for Cint i = 0; { i < 50; i +4) usleep(3)i 5 = GnbdG cout << “\n” + 0.9: ¥ cout << “Boldly go, return 0; ‘<< name << “1\n"5 When you've sorted the ASCI art out, remove the “Are you ready to explore the stars?”; fi cout << greet(xl: ror (int i = 0 cout << rocket; int 5 for (int i cout << *\n" usleep (3); a= (int) (3 cont << ™\n } cout << "Boldly go, return Loops and Decision Making Compl the code ensuring that al racetsare G1 closed off and there's a semicolon at the end of theappropriaelines when yuri through, you wil be ase or your name, ress Enter oleate sceen and wath the Brimaton (heating animation, but animation al the same) take of win afl Bold) go, NAME message tthe ed PEPTSEDD The previous code displays and animates the rocket ASC art Ibusesa For loop to add an extra ine under the rocket a increasing steps; using the Usleep Function to lessen the amount of time ‘each new line, thus giving the ‘appearance ofthe racket speeding up into space, Finally, there's a message to the user at the end of the code, With the correct tools, you can combine graphics and ‘animations with C++ routines, A Sadly, C++ in itself doesr't provide graphics. To get better graphics ‘and animations, you will need to use some ofthe avaliable libraries {and full development engines. Much lke Python, in some respects, youwill ned to apply the relevant extras (modules in the case oF Python, braries for ++) and lean how to cade them into you ‘own programs ‘what you need to understands that C++ developmentin the console, the command line if you wil is completely different to ‘game development. Yeas ago, using Borland C+, you could easly Utilise the Graphics brary then display and animate EGA and VGA graphics. If you're looking to stretch your C++ graphics and animations learning, then youre probably best learning the basics frst, such asthis section of the book, before movinginta the more complex. areas of C++. Then when you've gota grasp on the more advanced concepts of Cr+, the next step would be to gethold of a game engine, such as CryEngine, Unreal Engine, or AppGamekit. Each of Game engines, together with C++ code, can be used to create ‘anything from a top-selling game, to something personal. these are used to create some ofthe mostimpressive games, with ‘AppGamekit probably being the easiest ofthe bunch to begin with However to reiterate as with most aspects of coding, building a ‘good Foundation First is essential before delving into the inner workings ofa graphical or game engine. ‘The Unreal Engine helps you develop rich environments and. allows you to add C++ code behind the scenes. ESTED Here'sthe code ints entirety include include using namespace std; const char backgroundt]= > ony + NN “+ —\n\ . " 1 Vay . to ZX 1 NaN AM v= 1=1\n\ BEANE wir 1 1\n\ 22 GEA\NWNNAY, WWIII NNN TN $ BREEREAWNYANY WWIII LA LT IN esaeeaees- 1 ow Los tet Way = ee epee} (NI/ 1a TN lel eeseoseos___ | (\NI/ TTS =I __ l= eee 088, i ' Her 11 1 Nn —-0__\\|/__986@_26@___ IENNIZEIE AIA. const char rocket(] = a A\n\ HHEREEENON, HERERERENDN. HHEREANN, AN CN #ANNN int mainc) { string greet = “Are you ready to explore the stars?”; ‘int x=05 cout << background; cout << “\n"; ( Combining All You Know CH while Coreet[x] !="\0") { cout << greet(x]; usLeep(95000); HS 3 string none; cout << “\n” << “\n” << “What is your nane, brave astronaut? “; cout << fshs cout << “Press Enter for take off, “<< none << “An; cin.ignoreQs cin.getO; for Cint i = 0; i < 50; i++) cout << “\n"; cout << rocket; int j = 300000; for Cint i= 0; t < 50; i +4) i usteepC3)5 J = Cint)Gj * 0.9); ? ‘cout << “Boldly 90, <¢ name << “!\n"; ‘The only major issue that can be time-consuming is getting the ASCIartto be displayed correctly. As you can see from the screenshots, it doesn't display corectly in the IDE, but when ‘executed it displays perfectly Fine in the console window. Take the time to play around with it, remember the slashes Y, and new lines, A. See what other art you can come up with, n : “i food . « ore [eel +A daph E ES]. estan 7 vt In i My ryooiN = [Pere nT

You might also like