View
219
Download
1
Embed Size (px)
Citation preview
C++ Basics
Prof. Shermane Austin
Learning Programming Language Basics
• Data Types – simple • Expressions• Relational and Logical Operators• Conditional Statements• Arrays• Iteration• Memory Allocation• I/O• Functions
Hello World
//Simple C++ program#include <iostream> //input and output library#include <string> //string libraryusing namespace std; // predefined objectsint main() //first function, { //function delimiter
cout << “Hello world!” << endl; //output stream return 0; //ends execution and returns]
Simple Data Types
• Int – 32 bit, optional qualifiers: long, short
• Float – 32 bit, IEEE floating point
• Double – 64 bit, optional qualifer: long
• Char – 8 bit
• Byte – 8 bit
Operators
• Arithmetic– +, -, /, * – % - modulus or remainder, integer only, e.g. 23%4
• Relational – <, >, <=, >=, !=, ==– (c == a) \\ common error is omitting one of the =– Be careful using != or == with floating point values,
rounding occurs at the machine level• Logical
– And &&, e.g. (c <= a) && (c >= b)– Or ||, e.g. (c <= a) || (c >= b)
Operator shortcuts – Compound Assignment
• Increment, Decrement++, --a = a + 1; \\can be written as a++;a++, ++a, a--, --aPosition of operator is important, e.g.b = f(a++); \\a is incremented after f(a) callc = f(++a); \\a is incremented before f(a) call• Compound Assignment Operatorsint a;…a = a + 5;a += 5;Can be used with all arithmetic operators
Exercise - 1
• Compute volume of an object• Read in:
– Object mass (grams)– Object density (grams per cubic centimeter)
• Output:Volume (cubic centimeters)
• Relationship:Density = Mass/Volume
Code Needs
• Determine variables (with types needed)
• Issue prompts – use cout, e.g.
Cout << “Object Mass?” << endl;
• Read in values – use cin, e.g.
Cin >> mass;
• Compute Distance and Velocity
Conditional Expressions
• Any combination of logical and relational operators
• Use () as needed• Examples:Simple if statement if( a < b) s1 else s2
If/else statement
• General format – single statement execution on true condition
• Long format – multiple statement execution on true condition
• General rule: more than one statement under if and/or else condition requires {}
• Short-hand format – single statement
• Nested if statements
If – single statement
Format:
if(expression)
s1;
else
s2;
If – multiple statementsFormat:
if(expression){
s1; s2; …
}else{
s1; s2; …
}
If shorthand
• Used only with single statements• Format:Expression ? S1 : s2;Example: c != b ? c++ : b++;Example: int a,b; … int min = a <= b ? a : b ;
Short-circuit evaluation
• && - evaluation terminates with first false condition
• || - evaluation terminates with first true condition
• Done to insure objects can be properly manipulated, e.g.– (i != 0) && ((j/i) > 5)
Arrays
• Included in C++ for backward compatibility with C
• Arrays less popular and class representation of lists, especially the vector class more frequently used
• Vector class is an example of container classes is defined in the Standard Template Library (STL)
Simple arrays - Declaration
const int N = 20;const int M = 40;const int MaxListSize = 1000;// Note: const qualifier used to denote constant
values//Declaration examples:int a[10];float c[M*N];int Values[MaxListSize];
Simple Arrays - Referencing
• Array elements are referenced using subscripts or indices
• First index in C++ is 0• Examples: a[0] = b; a[i++] = a[j] + 3; a[a[k]] = 12;• Warning: No automatic checking for array
boundaries. Illegal subscripts will result in inaccurate memory references or storage
Simple Array - Initialization
• Int frequency[5] = {0,0,0,0,0};
• Int total[5] = {0}; // first element set to 0, remainder are uninitialized and default at 0
• Int digits[] = {0,1,2,3,4,5,6,7,8,9};
• Int zero[] = {0}; //one-element array
Iteration
• For-loops
• While-loops
Iteration using while
• Format: while (conditional expression){
s1; …}Statement in the block are executed as long as
condition is trueIf condition is evaluated to false, statements are
never executed
Interation using for
• Format:
for (ForInit ; ForExpression; PostExpression)
{
}
ForInit – initialization step to start loop
ForExpression – logical expression
PostExpression – next iteration of loop
For examples
for( i = 0; i<= maxsize; i++){}for(j=minsize; j < maxsize; j+=2){}for(k = maxsize; k > minsize; k--){}
Exercises
• Compute n! using a for loop
• Compute the nth Fibonacci term using a while loop
• Example, compute roots of a quadratic equation://Quadratic roots#include <iostream>#include <string>#include <math.h>Using namespace std;int main(){
double a, b, c; cout << “Coefficients for quadratic equation: “; cin >> a >> b >> c; if ((a != 0) && ((b*b – 4*a*c) > 0)) { double radical = sqrt(b*b – 4 * a * c); double root1 = (-b + radical) / (2 * a); double root2 = (-b – radical) / (2 * a); cout << “ roots are “ << root1 << “ and “ << root2 << endl; } else { cout << “ No real roots “ << endl; } return 0;}
Compute area of a circle#include <iostream>#include <string>Using namespace std;const float Pi = 3.1415int main(){ float radius; cout << “Enter radius: ”; cin >> radius; //compute area float area = Pi * radius * radius; //output cout << “Area = “ << area;}
More general using functions#include <iostream>#include <string>Using namespace std;float CircleArea(float r){ const float Pi = 3.1415; return Pi * r * r;}int main(){ float radius; cout << “Enter radius: ”; cin >> radius; //compute area float area = CircleArea(radius); //output cout << “Area = “ << area;}
Function prototyping
• Functions cannot be used until they are defined
• Can create problems with functions calling other functions
• Use prototype conventions
• Define function prototype before main
• Implement function after main
Prototype Example#include <iostream>#include <string>Using namespace std;float CircleArea(float r);int main(){ float radius; cout << “Enter radius: ”; cin >> radius; //compute area float area = CircleArea(radius); //output cout << “Area = “ << area;}float CircleArea(float r){ const float Pi = 3.1415; return Pi * r * r;}
Homework
• Write a program for integrating a quadratic polynomial
• User input will be– Quadratic coefficients: a1, a2, a3– Interval of interest : n1, n2
• Output will be the area