Uploaded by spicewolf10

Class 2 - Chapter 2 - Intro to C++

advertisement
Program 1:
/*
Miguel Razo
CS 1337
DESCRIPTION:
Chapter 2: Introduction to C++
 From previous class:
o a program is a series of steps.
o A programming language (like C++ ) is made of keywords, programmer defined
identifiers (i.r. variables), operators, punctuation and syntax (how statements are used)

Identifiers: defined by the programmer(variables, functions, etc)
o Cannot use keywords
o The identifier name should hint the use: totalNumberOfItems,
computeCirclePerimeter()
o Can use alphabetic characters, numbers and underscore
o Lower and upper case,
o Case sensitive: myvariable, and MYVARIABLE are different
o Cannot start with a digit
 Variables and literals:
o A variable is a reserved space(bytes) in memory (RAM)
 The amount of memory depends on the variable type(int, double, float, etc)
 Syntax: <data_type> <identifier_name>;
• Primitive Data Types(int, char, bool, etc)
• Derived Data Types (arrays, pointers, etc)
• Abstract or user defined data types (Structures, unions, classes, enum,
typdef)
 Variables of the same data type, can be defined on the same line, as a comma
separated list:
• <data_type> <var_1>, <var_2>;
o Literal: a value written as part of the code
 5, 3.14, 23456, ‘A’,”Hello”
o Literals are constants
o Integer literals, float literals, char literals, string literals.
o To determine the number of bytes(variables)
 Sizeof(<variable>)
 Variables(programmer identifiers) are always assigned from right to left
o Int c = 45;
 Scope of the variable: part of the program that the variable can be accessed
o Local or global
o
 Some of the most used special characters:
o // double forward slash: line comment
o /**/ block comment
o # pound sign: preprocessor directive








o <> open/close brackets: enclose the filename in include directive
o () parentheses: for function arguments
o {} curly braces: to enclose a block of code
o “ “ quotation marks: used with strings
o ; semicolon: end of the statement
o , comma: to separate elements in a list
Integer
o Signed: it includes negative and positive numbers
o Unsigned: starts from 0, and includes only positive numbers
o Short (2 bytes)
o Int (4 bytes)
o Long (4 bytes)
o Integer literals are by default consider integers
o To store a literal in a long memory location use L: 789L;
o Literal integers that start with 0 are consider octal
o Literal integers that start with 0x are consider hexadecimal
Char
o 1 byte
o 0 to 255 (ASCII TABLE?)
o Character literals are enclosed by single quote ‘A’
Character strings
o A series of characters terminated by ‘\0’(null terminator)
o In C++ strings are supported using #include <string>
 #include directive inserts that content of a file into another program
o After this directive, the string data type is available
Float
o Float (4 bytes)
o Double (8 bytes)
o Floating point literals are stored in double memory locations by default
o Can be forced to be float (0.456f) or long (3.567L)
o Can be represented in decimal or scientific notation0.0004 or 4e-4
Bool
o Two possible values: true(1) or false(0)
o Represented as small integers
Three types of constants:
o symbolic (using the preprocessor directive #define)
o named constants: (using the keyword const before the data type)
o literals
Operators:
o Unary: only one operand
o Binary: a*b
o Ternary : a>b?opt1:opt2;
Arithmetic operations:
o +,-,*,/ and %
This is a program example, that asks the
user for the length and width of a rectangle,
and computes the rectangle's area
*/
#include <iostream> // To use cout/cin
//Is a way to group/scope the code. By selecting a namespace we are limiting the code that will be made
available from the “include” directives.
using namespace std;
int main()
{
float length=10.6, width=15.3, area;//Variable definition
cout << "This program calculates "
<< "the area of a rectangle " << endl; //End Line
cout << "Enter the length :";
//cin >> length;
cout << "The length entered was/is :" << length <<endl;
cout << "Enter the width :";
//cin >> width;
cout << "The width entered was/is :" << width << endl;
area = length * width;
cout << "The area is :";
cout.precision(5);
cout.fill('x');
cout << length * width << endl;
return 0;
}//End of main
Program 2:
/*
DESCRIPTION;
Write a program to read first and last name of a person, course number
and grades for exams 1, 2, and 3. Then computes the average
grade and displays the information left aligned, with
no more than two decimals for the average.
*/
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
//Output formatting setw, setprecision, showpoint, etc.
int main()
{
//To store user's information: First/Last Name
string firstName, lastName;
//Course number. i.e. 1337, 1336, 1325, etc.
int courseNumber = 0;
//These are to store grades and compute the average
double exam1Grade = 0.0, exam2Grade= 0.0,
exam3Grade= 0.0, avgGrade= 0.0;
//Ask for the first name
cout << "First Name: ";
//Store what is typed on the keyboard(std input)
//to the string variable firstName
cin >> firstName;
//Ask for the last name
cout << "Last Name: ";
//Store what is typed on the keyboard(std input)
//to the variable lastName
cin >> lastName;
//Ask for course number
cout << "Course Number: ";
cin >> courseNumber;
// When testing the code, you may need to compile and
// execute it several times. Each time you need to
// provide all the information.
// Sometimes, after making sure that you are getting
// the right values, you may want to either provide
// the information as hardcode (i.e. exam1Grade = 78,
// exam2Grade =90, and so on)
// In many other situations, the number of entries is
// so large, that hardcoding may be actually hard.
// So, you can use:
// rand(): generates random number between 0 and the
//
max int
//
To generate random numbers[min_value,max_value]
//
within a range:
//
min_value+rand()%(max_value+1)
//
For example, to generate numbers from 0 to 9:
//
0 + rand()%10
//
It may generate numbers like:
//
0,6,1,9,4,5
//
Or
//
3,1,7,4,0,9
// Everytime you use rand() function, use:
// srand(x): Initiates the random number in a given seed.
// srand(11)
// This option will still generate random numbers, but you
// can make sure that the sequence is always the same.
// If you want to generate a different sequence every time,
// make sure to use different value for x on srand(x)
// For example, you can generate course numbers between
// 1000 and 6000 by using:
//
courseNumber = 1000 + rand() % 5001;
// Ask for exam1
cout<<"Exam 1 grade: ";
cin >> exam1Grade;
// Ask for exam2
cout<<"Exam 2 grade: ";
cin >> exam2Grade;
// Ask for exam3
cout<<"Exam 3 grade: ";
cin >> exam3Grade;
// Make sure that there is at least one double as part of
// the division. Otherwise you will get the integer division
avgGrade = ( exam1Grade + exam2Grade + exam3Grade )/3.0;
//Output formatting:
// setw(x): Prints in a field at least x spaces. Use more
//
spaces if the field is not wide enough
// fixed : Use the decimal notation for floating point
//
values
// setprecision(x): When used with fixed, it determines the
//
number of digits after the decimal point.
// showpoint: always prints decimal point for floating
//
point values
//You can set the alignment to left, right or internal
cout<<left;
cout<< setw(15) << "Name" << setw(10) << "Course"
<< setw(10) << "Exam 1" << setw(10) << "Exam 2"
<< setw(10) << "Exam 3" << setw(10) << "Average"<<endl;
cout<<left;
cout<< setw(15) << firstName +" "+lastName << setw(10) << courseNumber
<< setw(10) << exam1Grade << setw(10) << exam2Grade
<< setw(10) << exam3Grade<< setw(10)
<< setprecision(2)<<fixed<<avgGrade<<endl;
return 0;
}//End of main
Download