SlideShare a Scribd company logo
1 of 19
Download to read offline
Introduction to Programming using C++
Copyright © N & R Technology rev 1.3.03302008 1
Introduction to
C++ Programming Language
Language
Programming for Teens
NR Computer Learning Center
1835 W. Orangewood . #200
Orange . CA 92868
www.nrclc.com
Phone: (714) 505-3475
Copyright © NR Computer Learning Center ver 1.5.06082015 2
For more information contact:
NR Computer Learning Center
1835 W. Orangewood, #200
Orange, CA 92780
www.nrclc.com
(714) 505-3475
All rights reserved. This publication is protected by federal copyright law. No part of this publication
may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, electronic,
mechanical, photocopying, recording, or otherwise, or be used to make a derivative work (such as
translation or adaption), without permission in writing from N&R Technology.
Trademarks
NR Computer Learning Center logos are trademarks of NR Computer Learning Center.
Some of the product names and company names used in this book have been used for identification
purposes only and may be trademarks or registered trademarks of their respective manufacturers and
resellers.
Disclaimer
NR Computer Learning Center reserves the right to revise this publication and make changes in its
content from time to time, without notice.
Copyright © NR Computer Learning Center ver 1.5.06082015 3
Contents
Contents
Objective.................................................................................................................................................10
History of C++ Language .........................................................................................................................11
The C++ development cycle....................................................................................................................11
Source Code............................................................................................................................................11
Compiler..................................................................................................................................................12
The Library ..............................................................................................................................................12
The Linker................................................................................................................................................12
Installing Visual C++ Software.................................................................................................................13
Writing and Compiling C++ Code (using Visual Studio) ..........................................................................15
Writing and Compiling C++ Code (using Notepad) .................................................................................17
Worksheet 1............................................................................................................................................18
Quiz 1 ......................................................................................................................................................20
Lesson 2: Coding Style & Flow Chart...........................................................................................................23
Objective.................................................................................................................................................23
Sample Coding Styles..............................................................................................................................24
Header.....................................................................................................................................................25
Comment ................................................................................................................................................26
Messages.................................................................................................................................................26
Declaring variables..................................................................................................................................27
Easy Readability ......................................................................................................................................27
Flowchart ................................................................................................................................................29
Examples on Flowcharting......................................................................................................................30
Worksheet 2............................................................................................................................................32
Answers...................................................................................................................................................34
Lesson 3: Expression ...................................................................................................................................35
Objective.................................................................................................................................................35
Statements..............................................................................................................................................36
Expression...............................................................................................................................................36
Variable...................................................................................................................................................37
Copyright © NR Computer Learning Center ver 1.5.06082015 4
Data Types...............................................................................................................................................37
Numerical Variable..................................................................................................................................38
Arithmetic Operators..............................................................................................................................38
Assignment Operators ............................................................................................................................38
Escape Sequence.....................................................................................................................................39
Worksheet 3............................................................................................................................................40
Answers...................................................................................................................................................45
Quiz .........................................................................................................................................................47
Lesson 4: Condition.....................................................................................................................................50
Objective.................................................................................................................................................50
Relational Operation...............................................................................................................................51
Logical Operators & Expression ..............................................................................................................51
The if statement......................................................................................................................................52
The Conditional Operator .......................................................................................................................54
The keyword "switch".............................................................................................................................55
Worksheet 4............................................................................................................................................56
Answers...................................................................................................................................................64
Quiz .........................................................................................................................................................70
Lesson 5: For loop.......................................................................................................................................73
Objective.................................................................................................................................................73
For statement .........................................................................................................................................74
The Comma Operator .............................................................................................................................75
Worksheet 5............................................................................................................................................76
Answers...................................................................................................................................................81
Quiz .........................................................................................................................................................83
Lesson 6: While loop...................................................................................................................................85
Objective.................................................................................................................................................85
The while statement ...............................................................................................................................86
The do … while statement.......................................................................................................................87
Program Jumps .......................................................................................................................................88
The break Command...............................................................................................................................88
The continue Command..........................................................................................................................89
Worksheet 6............................................................................................................................................90
Answers...................................................................................................................................................95
Quiz .........................................................................................................................................................97
Copyright © NR Computer Learning Center ver 1.5.06082015 5
Lesson 7: Functions...................................................................................................................................105
Objective...............................................................................................................................................105
Functions...............................................................................................................................................106
Arguments.............................................................................................................................................107
Local vs Global Variables.......................................................................................................................107
Scope of Variables.................................................................................................................................108
Worksheet 7..........................................................................................................................................109
Answers.................................................................................................................................................118
Quiz .......................................................................................................................................................120
Lesson 8: Array..........................................................................................................................................122
Objective...............................................................................................................................................122
Introduction to an Array .......................................................................................................................123
Declaring an Array.................................................................................................................................124
Initializing Arrays...................................................................................................................................124
Accessing Array Elements .....................................................................................................................125
Using An Array ......................................................................................................................................126
Multidimensional Arrays.......................................................................................................................127
Worksheet 8..........................................................................................................................................128
Answers.................................................................................................................................................129
Lesson 9: String.........................................................................................................................................130
Objective...............................................................................................................................................130
Introduction to String............................................................................................................................131
The String Class in C++ ..........................................................................................................................133
Quiz .......................................................................................................................................................135
Lesson 10: Exception Handling .................................................................................................................136
Objective...............................................................................................................................................136
An Exception .........................................................................................................................................137
Throwing Exceptions.............................................................................................................................138
Catching Exceptions..............................................................................................................................138
C++ Standard Exceptions ......................................................................................................................140
Define New Exceptions.........................................................................................................................141
Lesson 11: File Input & Output .................................................................................................................142
Introduction to File Input/Output.........................................................................................................143
Opening a File .......................................................................................................................................143
Closing a File .........................................................................................................................................144
Copyright © NR Computer Learning Center ver 1.5.06082015 6
Writing to a File.....................................................................................................................................144
Reading from a File ...............................................................................................................................145
File Writing & Reading Example............................................................................................................145
Answer: .....................................................................................................................................................147
Copyright © NR Computer Learning Center ver 1.5.06082015 7
Course Description
Introduction
This course is of great help to learners who want to learning Programming using C++.
Learning Objectives
Following are the objective of this course:
 Introduce the modern programming concepts and other design methodologies using
C++
 Discuss the concepts of good software design and methods.
 Design programs using modular problem solving techniques.
 Use the concepts of different types of structured programming.
 Develop pseudo-code to a problem.
 Demonstrate a knowledge of programming.
 Develop algorithms using different methods.
Assumptions
 The course assumes that the learner is familiar with Internet and Windows.
 This course depends on the student's commitment to work independently at his/her own
time schedule on project assigned to them that will require access to the computer.
Learning Resources and Tools
The course consists of 8 units of study. The work load of each unit varies and uses some of the
following tools:
On -Line Reading: Each unit has one on-lEach unit has one on-line lecture. The lecture covers
topics with examples applicable to real life scenarios. To keep the students up-to-date with
the latest information, they are provided in the lectures notes with hyperlinks to current
resources, such as, articles, books and helpful websites.
Text Book Readings: Reading assignments consist of readings from the textbook, magazines and
web sites.
Discussion (e-mail): The discussions take place on topics relevant to the course via email. These
topics are chosen to expand the further understanding and application of concepts, theories,
or ideas related to the lecture. Most often single answer to a problem does not suffice. Each
student’s response will differ based on his or her own experience.
Assignments: Assignments consist Assignments consist of a variety of programming activities
and exercises. All the assignment are submitted via email before the end of the course. To
Copyright © NR Computer Learning Center ver 1.5.06082015 8
complete the work for each unit, the student must follow the instructions listed in the lecture
unit.
Perquisite
None
Required Text
Introduction to C++ Language by N&R Technology.
Technical Requirements:
Basic knowledge of starting an Window application, managing Folder and files and browsing
Internet for information.
Instructor:
TBA
For further information and help contact: info@nrclc.com.
Topic
 Introduction to C++ Language
 History of C++ Language
 The C++ development cycle
 Source Code, Compiler, The Library, The Linker
 Installing Visual C++ Software
 Writing and Compiling C++ Code
 Coding Style & Flow Chart
 Sample Coding Styles
 Header, Comment, Messages
 Declaring variables
 Easy Readability
 Flowchart
 Statements, Expression, Variable
 Data Types
 Numerical Variable
 Mathematical Operators
 Assignment Operators
 Escape Sequence
 Condition
 Relational Operation
 Logical Operators & Expression
 The if statement
 The Conditional Operator
Copyright © NR Computer Learning Center ver 1.5.06082015 9
 The keyword "switch"
 For statement
 The Comma Operator
 The while statement
 The do … while statement
 Jump command
 Break Command
 Continue Command
 Functions
 Arguments
 Local and Global Variables
 Scope of Variables
 Introduction to an Array
 Declaring an Array
 Initializing Arrays
 Accessing Array Elements
 Using An Array
 Multidimensional Arrays
 C++ Arrays in Detail
 The String Class in C++
 Exception Handling
 Throwing Exceptions
 Catching Exceptions
 C++ Standard Exceptions
 Define New Exceptions
 File Input/Output
 Opening & Closing a File
 Writing to & Reading from a File
Copyright © NR Computer Learning Center ver 1.5.06082015 10
Lesson 1: Introduction to C++ Language
Objective
This unit will cover following topics:
 History of C++ Language.
 C++ Development Life Cycle.
 Source Code
 Compiler
 The Library
 The Linker
 Installing C++ Compiler
 Writing and Compiling C++ code
 Flow Chart
 Example of Flow Charting
At the completion of this unit the learner will be able to:
 Develop and compile small application in C++ Language
Copyright © NR Computer Learning Center ver 1.5.06082015 11
History of C++ Language
C++ was developed by Bjarne Stroustrup of AT&T Bell Laboratories in the early 1980's, and is based on
the C language. C was created by Dennis Ritchie at AT&T Bell Labs in the early ‘70s. At the time, Bell Labs
had a programming language called B -- B for Bell. C++ is intended as an incremental improvement of C.
The C++ development cycle
The cycle for developing code in C++ language includes following steps:
1. Use editor to write source code.
2. Compile program by using C++ compiler.
3. Link program to libraries of object code using C++ linker.
4. Execute the program and verify the output.
Source Code
A programmer uses a text editor such as notepad, Visual C++ or vi to write a program. The program file
created by the text editor is called the source or source code. All the source code for C++ programs are
written in English like text format readable by human. A code should be written clear, concise, and easy
to understand. Basically, the code is a set of instruction that tells the machine what to do and the
comments included in the source code tell the programmer about the code. The name of C++ source
files must always end with the extension .cpp.
For example, following is the source code for the HelloWorld.cpp:
#include <iostream>
using namespace std;
int main() {
cout << "Hello Worldn";
}
The first line include headers for iostream. The first one is needed to build applications. This includes
the support code that needed to turn a .obj file into a fully executable file. Every program must have a
main. The main indicate the starting point of the code.
using namespace std;
This tells the C++ compiler that it should use identifiers from the std library namespace. Without it,
the first line in the main() block would need to be prefixed with std::.
std::cout << "Hello World";
Without the namespace line, every instance of cout would need a std:: or else it will not compile.
cout << "Hello World";
The statement cout is used to print the content within the double quotes.
Copyright © NR Computer Learning Center ver 1.5.06082015 12
Compiler
A compiler’s job is to translate the source code, which contains human-readable instructions, into object
code, which contains machine-readable instructions, to be executed by the computer.
When the C++ file is compiled, the compiler check for semantic and syntactic errors in the source
code. If the compiler find any error, then it displays the error message, otherwise, it transforms the
source code into individual object code files. Each file holds just the object code from the associated
.cpp file.
The Library
A library is a set of object code with predefined functions such as cout for printing data to the consol,
exit to exit the program, and cin to get a data from the screen. A programmer can use a set of standard
functions that are defined in the library.
The Linker
The linker takes the object file and combines it with the standard functions from the library to produce
the final result, an executable program with an extension *.exe or *.com. The linker does this by
scanning the standard library, selecting the needed functions, and linking them into the object file. The
final output is a program file that can be executed by the user.
Then a linker program runs, which takes all the object files, adds any system files and outputs a fully
functioning executable.
Copyright © NR Computer Learning Center ver 1.5.06082015 13
Installing Visual C++ Software
http://www.microsoft.com/express/2005/download/default.aspx#
Click on Download button for visiual C++ .
Click on Next button.
Check the box and click on the Next button.
Copyright © NR Computer Learning Center ver 1.5.06082015 14
Check the Graphical IDE and click on the Next button.
Click on Install button to start installing the Visual C++ software.
Wait until it is done downloading the software.
Copyright © NR Computer Learning Center ver 1.5.06082015 15
Writing and Compiling C++ Code (using Visual Studio)
Step 1: Create a Project Folder. Go to Start button > Select Programs > Visual C++ 2005 Express Edition >
Microsoft Visual C++ Express Edition.
Step 2: Go to File Menu> select New Project …. This will open up a New Project window similar to the
one displayed below.
*
Step 3: In New Project Window, select Win32 on left panel and Win32 Console Application.
In the Name field, enter HelloWorld for the name of the project.
Copyright © NR Computer Learning Center ver 1.5.06082015 16
Step 4: In the Win32 Application Wizard window,
select Application Settings on the left panel and
then select Console application and Empty project
on the right panel. When done, click Finish button.
You now have project created on your system.
Step 5: Add a file to the project for typing your
source code. In the Project Menu > select Add New
Item…
Step 6: In the Add New item, select Code in the
Categories and C++ File in the Templates window.
In the Name field, type HelloWord for the name of
the C++ file.
Click on Add button to continue to the next step.
Step 7: In the work area, type following code:
#include <iostream>
using namespace std;
int main() {
cout << "Hello Worldn";
}
Step 8: Press Ctrl+S to save the source code.
Step 9: To compile the program, go to Debug
Menu, and select start without Debugging (ctrl +
F5)
Once all the errors are fixed, the code will be automatically linked and executed. During execution of the
program following window will pop up with the output message “Hello World”:
Note: The Output window at the bottom of the work area will display any error the
syntax or semantic error that may be discover by the compiler. You need to make sure
that there are 0 error(s).
In case there is any compilation error, then you need go back to the working window
and fix the code.
Every time you make a change to the code, you must save and recompile before
executing the code there is 0 compilation error.
Copyright © NR Computer Learning Center ver 1.5.06082015 17
Writing and Compiling C++ Code (using Notepad)
1. In Windows, click on Start button and select Notepad.
2. In the "Untitled" notepad, type the following simple C program:
#include <iostream>
using namespace std;
int main()
{
cout<<"HEY, you, I'm alive! Oh, and Hello World!n";
}
3. Go to File menu, select Save As... to save your source code with extension *.cpp. In this case,
name the file as lesson1a.cpp.
4. In Windows, click on Start button and the select Run ...
5. Type cmd and click OK
6. Use cd command to change the directory to the working directory
7. To compile the file, use following command:
c++ lesson1a.cpp -o lesson1a.exe
where lesson1a.cpp is the input file and lesson1a.exe is the output file.
8. Type hello at the command line to see the output of the program.
Copyright © NR Computer Learning Center ver 1.5.06082015 18
Worksheet 1
1.0 Follow the steps given below to develop a program in C++ that prints rules for C++ language.
1) Start Visual C++ software (Go to Start button > Select Programs > Visual C++ 2005 Express Edition >
Microsoft Visual C++ Express Edition).
2) Go to File Menu> select New Project …. This will open up a New Project window.
3) In New Project Window, select Win32 on left panel and Win32 Console Application.
4) In the Name field, enter CPlusPlusRules for the name of the project.
5) In the Win32 Application Wizard window, select Application Settings on the left panel and then
select Console application and Empty project on the right panel. When done, click Finish button.
You now have project created on your system.
6) Add a file to the project for typing your source code. In the Project Menu > select Add New Item…
7) In the Add New item, select Code in the Categories and C++ File in the Templates window.
8) In the Name field, type CPlusPlusRules for the name of the C++ file.
9) Click on Add button to continue to the next step.
In the Workspace area for CPlusPlusRules’s window, type the following C++ code:
#include <iostream>
using namespace std;
int main()
{
cout << "All statements end with a semicolon!n";
cout << "Spaces are optional!n";
cout << "Must have a main function!n";
cout << "C is done mostly in lowercase. It’s a case- sensitive language.n";
cout << "Declare variables before you use them!n";
}
10) Press Ctrl+S to save the source code with extension *.cpp. In this case, it should be
CPlusPlusRules.cpp for the filename.
11) To compile and execute the program, go to Debug Menu, and select start without Debugging (ctrl +
F5)
12) Once all the errors are fixed, the code will be automatically linked and executed. During execution of
the program following window should pop up with the output output:
All statements end with a semicolon!
Spaces are optional!
Must have a main function!
C is done mostly in lowercase. It’s a case- sensitive language.
Declare variables before you use them!
Copyright © NR Computer Learning Center ver 1.5.06082015 19
2.0 Modify the CPlusPlusRules.cpp to print following 3 additional rules:
The function main must always have an int before it;
The function main should have an return 0;
The file should always include iostream.cpp;
3.0 Write the following program in Visual C++ that prints the square of a number that is entered by the
user. The Source code is given below:
#include <iostream>
using namespace std;
int square()
{
int answer;
int num;
cout <<"nSQUARE: n";
cout << "Enter the number:";
cin >> num;
answer = num * num;
cout << "The sqaure of " << num << " is " << answer <<".n";
return 0;
}
int main() {
square();
return 0;
}
4.0 Write the following program in Visual C++ that prints the message with the name. The Source code is
given below:
#include <iostream>
using namespace std;
int main()
{
int answer;
char Name[20];
cout <<"First Name: n";
cin >> Name;
cout << "Hello " << Name;
cout << “n”;
}

More Related Content

More from NR Computer Learning Center

App Development with Apple Swift Certification at Certiport Centers
App Development with Apple Swift Certification at Certiport CentersApp Development with Apple Swift Certification at Certiport Centers
App Development with Apple Swift Certification at Certiport CentersNR Computer Learning Center
 
Building a Dashboard in an hour with Power Pivot and Power BI
Building a Dashboard in an hour with Power Pivot and Power BIBuilding a Dashboard in an hour with Power Pivot and Power BI
Building a Dashboard in an hour with Power Pivot and Power BINR Computer Learning Center
 
Introduction to the basic mathematical concept with Python Turtle.
Introduction to the basic mathematical concept with Python Turtle.Introduction to the basic mathematical concept with Python Turtle.
Introduction to the basic mathematical concept with Python Turtle.NR Computer Learning Center
 
Stem presentation - Pathways to Technology Oriented Careers
Stem presentation - Pathways to Technology Oriented CareersStem presentation - Pathways to Technology Oriented Careers
Stem presentation - Pathways to Technology Oriented CareersNR Computer Learning Center
 
Building a Dashboard in an Hour using Microsoft PowerPivot & Power BI
Building a Dashboard in an Hour using Microsoft PowerPivot & Power BIBuilding a Dashboard in an Hour using Microsoft PowerPivot & Power BI
Building a Dashboard in an Hour using Microsoft PowerPivot & Power BINR Computer Learning Center
 
Microsoft Office Specialist (MOS) Excel 2013 certification pathway
Microsoft Office Specialist (MOS) Excel 2013 certification pathwayMicrosoft Office Specialist (MOS) Excel 2013 certification pathway
Microsoft Office Specialist (MOS) Excel 2013 certification pathwayNR Computer Learning Center
 
AP Computer Science Test Prep - Part 2 - Object Oriented Programming
AP Computer Science Test Prep - Part 2 - Object Oriented ProgrammingAP Computer Science Test Prep - Part 2 - Object Oriented Programming
AP Computer Science Test Prep - Part 2 - Object Oriented ProgrammingNR Computer Learning Center
 

More from NR Computer Learning Center (20)

Introduction to SQL
Introduction to SQLIntroduction to SQL
Introduction to SQL
 
Office 2019 tips & tricks
Office 2019 tips & tricksOffice 2019 tips & tricks
Office 2019 tips & tricks
 
App Development with Apple Swift Certification at Certiport Centers
App Development with Apple Swift Certification at Certiport CentersApp Development with Apple Swift Certification at Certiport Centers
App Development with Apple Swift Certification at Certiport Centers
 
Project management fundamentals
Project management fundamentalsProject management fundamentals
Project management fundamentals
 
National College Testing Association (NCTA)
National College Testing Association (NCTA)National College Testing Association (NCTA)
National College Testing Association (NCTA)
 
National College Testing Association (NCTA)
National College Testing Association (NCTA)National College Testing Association (NCTA)
National College Testing Association (NCTA)
 
Building a Dashboard in an hour with Power Pivot and Power BI
Building a Dashboard in an hour with Power Pivot and Power BIBuilding a Dashboard in an hour with Power Pivot and Power BI
Building a Dashboard in an hour with Power Pivot and Power BI
 
Introduction to the basic mathematical concept with Python Turtle.
Introduction to the basic mathematical concept with Python Turtle.Introduction to the basic mathematical concept with Python Turtle.
Introduction to the basic mathematical concept with Python Turtle.
 
Stem presentation - Pathways to Technology Oriented Careers
Stem presentation - Pathways to Technology Oriented CareersStem presentation - Pathways to Technology Oriented Careers
Stem presentation - Pathways to Technology Oriented Careers
 
MTA 98 364 - database fundamentals
MTA 98 364 - database fundamentalsMTA 98 364 - database fundamentals
MTA 98 364 - database fundamentals
 
MTA 361 software development fundamentals
MTA 361   software development fundamentalsMTA 361   software development fundamentals
MTA 361 software development fundamentals
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Introduction to c++
Introduction to c++Introduction to c++
Introduction to c++
 
Executive dashboard for small business
Executive dashboard for small businessExecutive dashboard for small business
Executive dashboard for small business
 
Building a Dashboard in an Hour using Microsoft PowerPivot & Power BI
Building a Dashboard in an Hour using Microsoft PowerPivot & Power BIBuilding a Dashboard in an Hour using Microsoft PowerPivot & Power BI
Building a Dashboard in an Hour using Microsoft PowerPivot & Power BI
 
Arduino for teens
Arduino for teensArduino for teens
Arduino for teens
 
Microsoft Office Specialist (MOS) Excel 2013 certification pathway
Microsoft Office Specialist (MOS) Excel 2013 certification pathwayMicrosoft Office Specialist (MOS) Excel 2013 certification pathway
Microsoft Office Specialist (MOS) Excel 2013 certification pathway
 
Computer Summer Camp for Kids and Teens
Computer Summer Camp for Kids and TeensComputer Summer Camp for Kids and Teens
Computer Summer Camp for Kids and Teens
 
MTA Database Certification Prep Training
MTA Database Certification Prep TrainingMTA Database Certification Prep Training
MTA Database Certification Prep Training
 
AP Computer Science Test Prep - Part 2 - Object Oriented Programming
AP Computer Science Test Prep - Part 2 - Object Oriented ProgrammingAP Computer Science Test Prep - Part 2 - Object Oriented Programming
AP Computer Science Test Prep - Part 2 - Object Oriented Programming
 

Recently uploaded

Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxCeline George
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Pooja Bhuva
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...Amil baba
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxUmeshTimilsina1
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxPooja Bhuva
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxPooja Bhuva
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxPooja Bhuva
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxannathomasp01
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 

Recently uploaded (20)

Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 

C plus plus

  • 1. Introduction to Programming using C++ Copyright © N & R Technology rev 1.3.03302008 1 Introduction to C++ Programming Language Language Programming for Teens NR Computer Learning Center 1835 W. Orangewood . #200 Orange . CA 92868 www.nrclc.com Phone: (714) 505-3475
  • 2. Copyright © NR Computer Learning Center ver 1.5.06082015 2 For more information contact: NR Computer Learning Center 1835 W. Orangewood, #200 Orange, CA 92780 www.nrclc.com (714) 505-3475 All rights reserved. This publication is protected by federal copyright law. No part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, or be used to make a derivative work (such as translation or adaption), without permission in writing from N&R Technology. Trademarks NR Computer Learning Center logos are trademarks of NR Computer Learning Center. Some of the product names and company names used in this book have been used for identification purposes only and may be trademarks or registered trademarks of their respective manufacturers and resellers. Disclaimer NR Computer Learning Center reserves the right to revise this publication and make changes in its content from time to time, without notice.
  • 3. Copyright © NR Computer Learning Center ver 1.5.06082015 3 Contents Contents Objective.................................................................................................................................................10 History of C++ Language .........................................................................................................................11 The C++ development cycle....................................................................................................................11 Source Code............................................................................................................................................11 Compiler..................................................................................................................................................12 The Library ..............................................................................................................................................12 The Linker................................................................................................................................................12 Installing Visual C++ Software.................................................................................................................13 Writing and Compiling C++ Code (using Visual Studio) ..........................................................................15 Writing and Compiling C++ Code (using Notepad) .................................................................................17 Worksheet 1............................................................................................................................................18 Quiz 1 ......................................................................................................................................................20 Lesson 2: Coding Style & Flow Chart...........................................................................................................23 Objective.................................................................................................................................................23 Sample Coding Styles..............................................................................................................................24 Header.....................................................................................................................................................25 Comment ................................................................................................................................................26 Messages.................................................................................................................................................26 Declaring variables..................................................................................................................................27 Easy Readability ......................................................................................................................................27 Flowchart ................................................................................................................................................29 Examples on Flowcharting......................................................................................................................30 Worksheet 2............................................................................................................................................32 Answers...................................................................................................................................................34 Lesson 3: Expression ...................................................................................................................................35 Objective.................................................................................................................................................35 Statements..............................................................................................................................................36 Expression...............................................................................................................................................36 Variable...................................................................................................................................................37
  • 4. Copyright © NR Computer Learning Center ver 1.5.06082015 4 Data Types...............................................................................................................................................37 Numerical Variable..................................................................................................................................38 Arithmetic Operators..............................................................................................................................38 Assignment Operators ............................................................................................................................38 Escape Sequence.....................................................................................................................................39 Worksheet 3............................................................................................................................................40 Answers...................................................................................................................................................45 Quiz .........................................................................................................................................................47 Lesson 4: Condition.....................................................................................................................................50 Objective.................................................................................................................................................50 Relational Operation...............................................................................................................................51 Logical Operators & Expression ..............................................................................................................51 The if statement......................................................................................................................................52 The Conditional Operator .......................................................................................................................54 The keyword "switch".............................................................................................................................55 Worksheet 4............................................................................................................................................56 Answers...................................................................................................................................................64 Quiz .........................................................................................................................................................70 Lesson 5: For loop.......................................................................................................................................73 Objective.................................................................................................................................................73 For statement .........................................................................................................................................74 The Comma Operator .............................................................................................................................75 Worksheet 5............................................................................................................................................76 Answers...................................................................................................................................................81 Quiz .........................................................................................................................................................83 Lesson 6: While loop...................................................................................................................................85 Objective.................................................................................................................................................85 The while statement ...............................................................................................................................86 The do … while statement.......................................................................................................................87 Program Jumps .......................................................................................................................................88 The break Command...............................................................................................................................88 The continue Command..........................................................................................................................89 Worksheet 6............................................................................................................................................90 Answers...................................................................................................................................................95 Quiz .........................................................................................................................................................97
  • 5. Copyright © NR Computer Learning Center ver 1.5.06082015 5 Lesson 7: Functions...................................................................................................................................105 Objective...............................................................................................................................................105 Functions...............................................................................................................................................106 Arguments.............................................................................................................................................107 Local vs Global Variables.......................................................................................................................107 Scope of Variables.................................................................................................................................108 Worksheet 7..........................................................................................................................................109 Answers.................................................................................................................................................118 Quiz .......................................................................................................................................................120 Lesson 8: Array..........................................................................................................................................122 Objective...............................................................................................................................................122 Introduction to an Array .......................................................................................................................123 Declaring an Array.................................................................................................................................124 Initializing Arrays...................................................................................................................................124 Accessing Array Elements .....................................................................................................................125 Using An Array ......................................................................................................................................126 Multidimensional Arrays.......................................................................................................................127 Worksheet 8..........................................................................................................................................128 Answers.................................................................................................................................................129 Lesson 9: String.........................................................................................................................................130 Objective...............................................................................................................................................130 Introduction to String............................................................................................................................131 The String Class in C++ ..........................................................................................................................133 Quiz .......................................................................................................................................................135 Lesson 10: Exception Handling .................................................................................................................136 Objective...............................................................................................................................................136 An Exception .........................................................................................................................................137 Throwing Exceptions.............................................................................................................................138 Catching Exceptions..............................................................................................................................138 C++ Standard Exceptions ......................................................................................................................140 Define New Exceptions.........................................................................................................................141 Lesson 11: File Input & Output .................................................................................................................142 Introduction to File Input/Output.........................................................................................................143 Opening a File .......................................................................................................................................143 Closing a File .........................................................................................................................................144
  • 6. Copyright © NR Computer Learning Center ver 1.5.06082015 6 Writing to a File.....................................................................................................................................144 Reading from a File ...............................................................................................................................145 File Writing & Reading Example............................................................................................................145 Answer: .....................................................................................................................................................147
  • 7. Copyright © NR Computer Learning Center ver 1.5.06082015 7 Course Description Introduction This course is of great help to learners who want to learning Programming using C++. Learning Objectives Following are the objective of this course:  Introduce the modern programming concepts and other design methodologies using C++  Discuss the concepts of good software design and methods.  Design programs using modular problem solving techniques.  Use the concepts of different types of structured programming.  Develop pseudo-code to a problem.  Demonstrate a knowledge of programming.  Develop algorithms using different methods. Assumptions  The course assumes that the learner is familiar with Internet and Windows.  This course depends on the student's commitment to work independently at his/her own time schedule on project assigned to them that will require access to the computer. Learning Resources and Tools The course consists of 8 units of study. The work load of each unit varies and uses some of the following tools: On -Line Reading: Each unit has one on-lEach unit has one on-line lecture. The lecture covers topics with examples applicable to real life scenarios. To keep the students up-to-date with the latest information, they are provided in the lectures notes with hyperlinks to current resources, such as, articles, books and helpful websites. Text Book Readings: Reading assignments consist of readings from the textbook, magazines and web sites. Discussion (e-mail): The discussions take place on topics relevant to the course via email. These topics are chosen to expand the further understanding and application of concepts, theories, or ideas related to the lecture. Most often single answer to a problem does not suffice. Each student’s response will differ based on his or her own experience. Assignments: Assignments consist Assignments consist of a variety of programming activities and exercises. All the assignment are submitted via email before the end of the course. To
  • 8. Copyright © NR Computer Learning Center ver 1.5.06082015 8 complete the work for each unit, the student must follow the instructions listed in the lecture unit. Perquisite None Required Text Introduction to C++ Language by N&R Technology. Technical Requirements: Basic knowledge of starting an Window application, managing Folder and files and browsing Internet for information. Instructor: TBA For further information and help contact: info@nrclc.com. Topic  Introduction to C++ Language  History of C++ Language  The C++ development cycle  Source Code, Compiler, The Library, The Linker  Installing Visual C++ Software  Writing and Compiling C++ Code  Coding Style & Flow Chart  Sample Coding Styles  Header, Comment, Messages  Declaring variables  Easy Readability  Flowchart  Statements, Expression, Variable  Data Types  Numerical Variable  Mathematical Operators  Assignment Operators  Escape Sequence  Condition  Relational Operation  Logical Operators & Expression  The if statement  The Conditional Operator
  • 9. Copyright © NR Computer Learning Center ver 1.5.06082015 9  The keyword "switch"  For statement  The Comma Operator  The while statement  The do … while statement  Jump command  Break Command  Continue Command  Functions  Arguments  Local and Global Variables  Scope of Variables  Introduction to an Array  Declaring an Array  Initializing Arrays  Accessing Array Elements  Using An Array  Multidimensional Arrays  C++ Arrays in Detail  The String Class in C++  Exception Handling  Throwing Exceptions  Catching Exceptions  C++ Standard Exceptions  Define New Exceptions  File Input/Output  Opening & Closing a File  Writing to & Reading from a File
  • 10. Copyright © NR Computer Learning Center ver 1.5.06082015 10 Lesson 1: Introduction to C++ Language Objective This unit will cover following topics:  History of C++ Language.  C++ Development Life Cycle.  Source Code  Compiler  The Library  The Linker  Installing C++ Compiler  Writing and Compiling C++ code  Flow Chart  Example of Flow Charting At the completion of this unit the learner will be able to:  Develop and compile small application in C++ Language
  • 11. Copyright © NR Computer Learning Center ver 1.5.06082015 11 History of C++ Language C++ was developed by Bjarne Stroustrup of AT&T Bell Laboratories in the early 1980's, and is based on the C language. C was created by Dennis Ritchie at AT&T Bell Labs in the early ‘70s. At the time, Bell Labs had a programming language called B -- B for Bell. C++ is intended as an incremental improvement of C. The C++ development cycle The cycle for developing code in C++ language includes following steps: 1. Use editor to write source code. 2. Compile program by using C++ compiler. 3. Link program to libraries of object code using C++ linker. 4. Execute the program and verify the output. Source Code A programmer uses a text editor such as notepad, Visual C++ or vi to write a program. The program file created by the text editor is called the source or source code. All the source code for C++ programs are written in English like text format readable by human. A code should be written clear, concise, and easy to understand. Basically, the code is a set of instruction that tells the machine what to do and the comments included in the source code tell the programmer about the code. The name of C++ source files must always end with the extension .cpp. For example, following is the source code for the HelloWorld.cpp: #include <iostream> using namespace std; int main() { cout << "Hello Worldn"; } The first line include headers for iostream. The first one is needed to build applications. This includes the support code that needed to turn a .obj file into a fully executable file. Every program must have a main. The main indicate the starting point of the code. using namespace std; This tells the C++ compiler that it should use identifiers from the std library namespace. Without it, the first line in the main() block would need to be prefixed with std::. std::cout << "Hello World"; Without the namespace line, every instance of cout would need a std:: or else it will not compile. cout << "Hello World"; The statement cout is used to print the content within the double quotes.
  • 12. Copyright © NR Computer Learning Center ver 1.5.06082015 12 Compiler A compiler’s job is to translate the source code, which contains human-readable instructions, into object code, which contains machine-readable instructions, to be executed by the computer. When the C++ file is compiled, the compiler check for semantic and syntactic errors in the source code. If the compiler find any error, then it displays the error message, otherwise, it transforms the source code into individual object code files. Each file holds just the object code from the associated .cpp file. The Library A library is a set of object code with predefined functions such as cout for printing data to the consol, exit to exit the program, and cin to get a data from the screen. A programmer can use a set of standard functions that are defined in the library. The Linker The linker takes the object file and combines it with the standard functions from the library to produce the final result, an executable program with an extension *.exe or *.com. The linker does this by scanning the standard library, selecting the needed functions, and linking them into the object file. The final output is a program file that can be executed by the user. Then a linker program runs, which takes all the object files, adds any system files and outputs a fully functioning executable.
  • 13. Copyright © NR Computer Learning Center ver 1.5.06082015 13 Installing Visual C++ Software http://www.microsoft.com/express/2005/download/default.aspx# Click on Download button for visiual C++ . Click on Next button. Check the box and click on the Next button.
  • 14. Copyright © NR Computer Learning Center ver 1.5.06082015 14 Check the Graphical IDE and click on the Next button. Click on Install button to start installing the Visual C++ software. Wait until it is done downloading the software.
  • 15. Copyright © NR Computer Learning Center ver 1.5.06082015 15 Writing and Compiling C++ Code (using Visual Studio) Step 1: Create a Project Folder. Go to Start button > Select Programs > Visual C++ 2005 Express Edition > Microsoft Visual C++ Express Edition. Step 2: Go to File Menu> select New Project …. This will open up a New Project window similar to the one displayed below. * Step 3: In New Project Window, select Win32 on left panel and Win32 Console Application. In the Name field, enter HelloWorld for the name of the project.
  • 16. Copyright © NR Computer Learning Center ver 1.5.06082015 16 Step 4: In the Win32 Application Wizard window, select Application Settings on the left panel and then select Console application and Empty project on the right panel. When done, click Finish button. You now have project created on your system. Step 5: Add a file to the project for typing your source code. In the Project Menu > select Add New Item… Step 6: In the Add New item, select Code in the Categories and C++ File in the Templates window. In the Name field, type HelloWord for the name of the C++ file. Click on Add button to continue to the next step. Step 7: In the work area, type following code: #include <iostream> using namespace std; int main() { cout << "Hello Worldn"; } Step 8: Press Ctrl+S to save the source code. Step 9: To compile the program, go to Debug Menu, and select start without Debugging (ctrl + F5) Once all the errors are fixed, the code will be automatically linked and executed. During execution of the program following window will pop up with the output message “Hello World”: Note: The Output window at the bottom of the work area will display any error the syntax or semantic error that may be discover by the compiler. You need to make sure that there are 0 error(s). In case there is any compilation error, then you need go back to the working window and fix the code. Every time you make a change to the code, you must save and recompile before executing the code there is 0 compilation error.
  • 17. Copyright © NR Computer Learning Center ver 1.5.06082015 17 Writing and Compiling C++ Code (using Notepad) 1. In Windows, click on Start button and select Notepad. 2. In the "Untitled" notepad, type the following simple C program: #include <iostream> using namespace std; int main() { cout<<"HEY, you, I'm alive! Oh, and Hello World!n"; } 3. Go to File menu, select Save As... to save your source code with extension *.cpp. In this case, name the file as lesson1a.cpp. 4. In Windows, click on Start button and the select Run ... 5. Type cmd and click OK 6. Use cd command to change the directory to the working directory 7. To compile the file, use following command: c++ lesson1a.cpp -o lesson1a.exe where lesson1a.cpp is the input file and lesson1a.exe is the output file. 8. Type hello at the command line to see the output of the program.
  • 18. Copyright © NR Computer Learning Center ver 1.5.06082015 18 Worksheet 1 1.0 Follow the steps given below to develop a program in C++ that prints rules for C++ language. 1) Start Visual C++ software (Go to Start button > Select Programs > Visual C++ 2005 Express Edition > Microsoft Visual C++ Express Edition). 2) Go to File Menu> select New Project …. This will open up a New Project window. 3) In New Project Window, select Win32 on left panel and Win32 Console Application. 4) In the Name field, enter CPlusPlusRules for the name of the project. 5) In the Win32 Application Wizard window, select Application Settings on the left panel and then select Console application and Empty project on the right panel. When done, click Finish button. You now have project created on your system. 6) Add a file to the project for typing your source code. In the Project Menu > select Add New Item… 7) In the Add New item, select Code in the Categories and C++ File in the Templates window. 8) In the Name field, type CPlusPlusRules for the name of the C++ file. 9) Click on Add button to continue to the next step. In the Workspace area for CPlusPlusRules’s window, type the following C++ code: #include <iostream> using namespace std; int main() { cout << "All statements end with a semicolon!n"; cout << "Spaces are optional!n"; cout << "Must have a main function!n"; cout << "C is done mostly in lowercase. It’s a case- sensitive language.n"; cout << "Declare variables before you use them!n"; } 10) Press Ctrl+S to save the source code with extension *.cpp. In this case, it should be CPlusPlusRules.cpp for the filename. 11) To compile and execute the program, go to Debug Menu, and select start without Debugging (ctrl + F5) 12) Once all the errors are fixed, the code will be automatically linked and executed. During execution of the program following window should pop up with the output output: All statements end with a semicolon! Spaces are optional! Must have a main function! C is done mostly in lowercase. It’s a case- sensitive language. Declare variables before you use them!
  • 19. Copyright © NR Computer Learning Center ver 1.5.06082015 19 2.0 Modify the CPlusPlusRules.cpp to print following 3 additional rules: The function main must always have an int before it; The function main should have an return 0; The file should always include iostream.cpp; 3.0 Write the following program in Visual C++ that prints the square of a number that is entered by the user. The Source code is given below: #include <iostream> using namespace std; int square() { int answer; int num; cout <<"nSQUARE: n"; cout << "Enter the number:"; cin >> num; answer = num * num; cout << "The sqaure of " << num << " is " << answer <<".n"; return 0; } int main() { square(); return 0; } 4.0 Write the following program in Visual C++ that prints the message with the name. The Source code is given below: #include <iostream> using namespace std; int main() { int answer; char Name[20]; cout <<"First Name: n"; cin >> Name; cout << "Hello " << Name; cout << “n”; }