10
Advanced Structured Programming Page 1 of 10 Laboratory 0 Week 0 Advanced Structured Programming An Introduction to Visual Studio and C++ 0.1 Introduction This is a session to familiarize working with the Visual Studio development environment. It can be used to create various applications such as simple store apps, games for mobile, and complex systems that power enterprises and data centers. Visual Studio by default supports C#, C and C++, JavaScript, F#, and Visual Basic. Here we are going to work with C++. Also this session is going to give you an understanding of the following C++ Concepts: Variables, Data Types and Variables’ Declaration Reserved Words Special Characters Operators Arithmetic Assignment Comparison Logical Algorithmic operations: o Conditional operation 0.2 Preliminaries Make sure you have access to your home directory. Visual Studio should create a place for all of your workspaces in c:\documents\visual studio\Projects. Check that in this case. 0.3 Starting and Ending Visual Studio You can find out which edition of Visual Studio is right for you at Visual Studio Editions. You can install Visual Studio 2015 by downloading it from Visual Studio Downloads. If you need to know more about the installation process, see Installing Visual Studio 2015. Note that any version you download from the Visual Studio website might be slightly different to the versions that we are running on the department machines, but all of the concepts should be the same. On department machines, Visual Studio can be found through the following menus: Start Button-All Apps – Visual Studio This program works similar to any other software product, i.e. you open up the program, and you then either create a new program or load an existing program. When you have finished, you exit Visual Studio by selecting File-Exit.

Laboratory 0 Week 0 Advanced Structured Programming An ...els.thebesacademy.org/Uploads/Documents/755/Advanced Structured... · Advanced Structured Programming An Introduction to

Embed Size (px)

Citation preview

Advanced Structured Programming Page 1 of 10

Laboratory 0 – Week 0

Advanced Structured Programming

An Introduction to Visual Studio and C++

0.1 Introduction

This is a session to familiarize working with the Visual Studio development

environment. It can be used to create various applications such as simple

store apps, games for mobile, and complex systems that power enterprises

and data centers.

Visual Studio by default supports C#, C and C++, JavaScript, F#, and Visual

Basic. Here we are going to work with C++.

Also this session is going to give you an understanding of the following C++ Concepts:

Variables, Data Types and Variables’ Declaration

Reserved Words

Special Characters

Operators

Arithmetic Assignment Comparison Logical

Algorithmic operations:

o Conditional operation

0.2 Preliminaries

Make sure you have access to your home directory. Visual Studio should create a place

for all of your workspaces in c:\documents\visual studio\Projects. Check that in this

case.

0.3 Starting and Ending Visual Studio

You can find out which edition of Visual Studio is right for you at Visual Studio Editions.

You can install Visual Studio 2015 by downloading it from Visual Studio Downloads. If

you need to know more about the installation process, see Installing Visual Studio

2015.

Note that any version you download from the Visual Studio website might be slightly

different to the versions that we are running on the department machines, but all of

the concepts should be the same.

On department machines, Visual Studio can be found through the following menus:

Start Button-All Apps – Visual Studio

This program works similar to any other software product, i.e. you open up the

program, and you then either create a new program or load an existing program.

When you have finished, you exit Visual Studio by selecting File-Exit.

Advanced Structured Programming Page 2 of 10

0.4 Visual Studio IDE

When you create an application in Visual Studio, you first create a project.

To create a console application deploy the following steps

1. On the menu bar, choose File, New, and Project.

2. In the Visual C++ category, choose the Win32 Console Application template,

then name the project and Press Ok.

3. When the Win32 Application Wizard appears, choose the Finish button.

The project with the basic files for a Win32 console application is created as shown below.

Advanced Structured Programming Page 3 of 10

The components of the Visual Studio IDE that we will be working with are as

follows:

a) Code Editor Window for editing source code manually. b) Error List Window for displaying information about a specific error message.

Next, you'll add code in the Code Editor Window.

To display “Welcome to Lab 0” in the console window

1. In the code editor window enter a blank line before the line “return 0”.

2. Enter the following code cout << "Welcome to Lab 0\n";

A red squiggly line appears under cout. An error message appears if you point

to it.

This error message “cout is included in the <iostream> header file” also

appears in the Error List window. You can display the window by going to the

menu bar, choosing View, then Error List.

Advanced Structured Programming Page 4 of 10

3. To include the iostream header, enter the following code

after this header #include "stdafx.h".

You probably noticed that a box appeared as you entered code, providing

suggestions for the characters that you entered. This box is part of C++

IntelliSense, which provides coding prompts, including listing class or interface

members and parameter information. You can also use code snippets, which are

pre-defined blocks of code. For more information, see Using IntelliSense and

Code Snippets.

Note that: The red squiggly line under cout disappears when you fix the error.

4. Save the changes to the file.

You can debug your application now to see whether the sentence “Welcome to Lab 0”

appears in console window.

To debug the application

Start the debugger by choosing Debug from menu bar, and Start without

Debugging

The debugger starts, and a console window appears showing as below.

#include <iostream>

using namespace std;

Advanced Structured Programming Page 5 of 10

Note: You can press SHIFT + F5 to stop debugging.

The components of this simple program are as follows:

stdafx.h describes both standard system and project specific include files

that are used frequently but hardly ever change.

iostream provides basic C++ standard library input and output services.

using namespace std is used to replace std:: in each sentence Without

using namespace std; when you write for example cout <<; you'd have to

put std::cout <<;.

Program Statements, Every program statement must end with a semi-colon ";".

main is a section where any code within it will be executed when we run our program. The Code needs to be placed within the braces that follow the definition of main as below:

0.5 Data Types, Variables’ Declaration, and Statements’ Types

Variable is a symbol whose value can change during the execution of a program. Variables must:

have a name and a type.

contain upper or lower case letters, numbers & underscore character “_”.

Names must begin with an alphabetical character.

- Valid names Fred, X, y, Salary, abc12, Z_1

- Invalid names 54p, @Hello, John*, Zero#, Temp, 12

Advanced Structured Programming Page 6 of 10

0.5.1 Data Types

0.5.2 Variables’ Declaration and Initialization

Syntax: <Type> <Name> = <Expression>;

Example: bool b1 = true; char c; int a =10; float b =2.5; string text; byte z = 22;

0.5.3 Statements’ Types: - Declaration statements string name; int y, x= 100; x+=y;

- Executable statements cin >> name; cout <<”Hello ”<< name <<endl;

0.6 Reserved Words cannot be used for other purpose Example: bool, break, byte, case, catch, char, default, double, do, else, false, float, for, if, import,

int, long, new, null, public, return, short, static, switch, true, try, void, while, using

0.7 Special Characters

0.8 Operators

0.8.1 Arithmetic 0.8.2 Assignment

Character Name Description

// Double slash Marks single line comment.

# Pound sign (hash) Marks the beginning of a preprocessor directive

< > Opening / closing brackets Encloses a filename when used in #include directive

( ) Opening / closing parentheses Used in naming a function e.g. int main ( )

{ } Opening / closing braces Encloses a group of statements

“ “ Opening / closing quotations Encloses a string of characters ,

; Semicolon Marks the end of a complete statement

Advanced Structured Programming Page 7 of 10

0.8.3 Comparison 0.8.4 Logical

Note: Be careful of the Order of Operator Precedence

0.9 Visual Deployment Average computation of three numbers a, b, and c

#include "stdafx.h" #include <iostream> using namespace std; int main() { float a, b, c, avg; cout << "Enter the value of A \n"; cin >> a; cout << "Enter the value of B \n"; cin >> b; cout << "Enter the value of C \n"; cin >> c; avg = (a+b+c)/3; cout << "Average is " << avg << endl; return 0; }

Exchange X and Y integer values

#include "stdafx.h" #include <iostream> using namespace std; int main() { int X,Y,Temp; cout << "Enter the value of X \n"; cin >> X; cout << "Enter the value of Y \n"; cin >> Y; Temp = X; X=Y; Y=Temp; cout <<"X= "<<X<<" Y= "<<Y<<endl; return 0; }

0.10 Conditional Operation Types of conditional operators are : if-else , if-elseif- else, switch, nested conditions

If-else If-elseif-else Switch Nested conditions

Syntax

If( boolean expression)

{ statement(s);}

else

{ statement(s);}

If( boolean expression)

{ statement(s);}

elseif

{ statement(s);}

else

{ statement(s);}

Switch(expression)

{ case constant exp.:

statement(s);

break;

default:

statement(s);

break; }

If( boolean expression)

{

If( boolean expression)

{ statement(s);}

else { statement(s);} }

else

{ statement(s);}

Advanced Structured Programming Page 8 of 10

Using If condition Subtracting two numbers

#include "stdafx.h" #include <iostream> using namespace std; int main()

{ int a, b , c; cout << "Enter the 1st Value\n"; cin >> a; cout << "Enter the 2nd Value\n"; cin >> b; if (a > b) { c = a - b; } else { c = b - a; } cout << " the result is " << c << endl; return 0;

}

Using Switch Printing number of days per month

#include "stdafx.h" #include <iostream> using namespace std; int main()

{ int month_num, daysinmonth = 0; cin >> month_num; switch (month_num) {case 1: case 3: case 5: case 7: case 8: case 10: case 12:

daysinmonth = 31; break;

case 2: daysinmonth = 28; break;

case 4: case 6: case 9: case 11: daysinmonth = 30; break;

default: daysinmonth = -1; break;}

cout<<"Days in month # "<<month_num<<" = "<< daysinmonth<<endl;

return 0;

}

0.11 Exercise The following is a short list of tasks aimed at demonstrating some of the features of Visual Studio and C++.

0.11.1 Write C++ statements to display on the screen the following patterns

1) *************

*********

*****

***

*

2) ******

*****

****

***

**

*

3) @@@@@@@@

Good Morning!

@@@@@@@@

Advanced Structured Programming Page 9 of 10

0.11.2 Write a C++ program to print your Name, Level, and Faculty each in different line.

Run the program to see the results. Remove the << after cout Keyword. Try running

it again, what happens? Then Remove the semi-colon ";”. Try running it again, what

happens? And Finally Remove \n. Try running it again as well, what happens?

0.11.3 State whether each of the following statements are valid or invalid then state

statement type

a) int a , b , c; b) cout < “ Hello to CS World\n”;

c) y = 100.3; d) x = (a +b)/(d+c);

e) bol h=true; f) cinn> k;

g) cout<< ‘A’; h) cout<< endl;

0.11.4 Find any errors in the following C++ programs

a) #include <iostream> using namespace std;

void main() { cout<<'C++ Programming questions and answers'; return 0; } b) #include <iostream> using namespace sd; void main(){ integer a; float b; return 0;} c) #include <iostrem> usng namespace std;

int main(){ a,b,c int; d float; cout<<’The end of the program"; return 0; } d) #nclude <iostream> using namespace std; int main(){ int a,b,sum,pro; a=100; 20=b; sum=a+b; pro=a*b; cout<<left; cout<<"a+b";<<’\n’<<"a-b" cout<sum<<’\t’<<pro; return 0; }

0.11.5 Create a new project and call it Lab00. Write the following code:

#include "stdafx.h" #include <iostream> using namespace std; int main() { int x; x = 100; cout << x << endl; x = x + 10; //Line A cout << "Line A " << x << endl; x = x + 20; //Line B cout << "Line B " << x << endl; return 0; }

Then run the program to see the results. What could you replace the code commented

with Line A and Line B in order to make the program produce the same results? Now

modify the code.

0.11.6 Write a new program that declares the following variables:

a = 100, b = 2.3, c = -52.2, d = true, e = "I am ", f = "a

student", g = 0, h = '!'.

0.11.7 Declare the following constants, pi = 3.142 and name = <your name>. Make sure

you use the correct types. Declare three more variables, x as a long, y as a double

and z as a String.

0.11.8 Write a C++ Program to implement basic Calculator Operations (+,-, /,*, %) on two

numbers.

0.11.9 Write a C++ Program to converts 125 seconds to an equivalent number of minutes,

& seconds.

0.11.10 Given y = ax3 + 7, which of the following, if any, are correct C++ statements for

this equation?

Advanced Structured Programming Page 10 of 10

a) y = ( a * x ) * x * x + 7; d) y = a * x * x * x + 7;

b) y = a * ( x * x * x ) + 7; e) y = a * x * x * ( x + 7 );

c) y = a * x * ( x * x + 7 ); f) y = ( a * x ) * x * ( x + 7 );

0.11.11State the order of evaluation of the operators in each of the following C statements

and show the value of x after each statement is performed.

a) x = 7 + 3 * 6 / 2 - 1; b) x = 2 % 2 + 2 * 2 - 2 / 2; c) x = ( 3 * 9 * (3 + ( 9*3 / ( 3 ) ) ) );

0.11.12 Write C++ Program to calculate the square root of a given number. If the number is

negative print the error message “Square root does not exist”, otherwise print the number.

0.11.13Write C++ Program to read two numbers m and n and decide if n is bigger than m.

0.11.14 Write C++ Program to read a number and decide if it is odd or even.

0.11.15 Write C++ Program to take the letter grade from the user then using switch print its

equivalent E.g. input: A Output: Excellent

0.11.16Write C++ Program to compute a simple calculator using switch statement.