SlideShare ist ein Scribd-Unternehmen logo
1 von 43
1 
AA qquuiicckk iinnttrroodduuccttiioonn ttoo CC++++
2 
A C++ program 
//if necessary include headers 
//#include <foo.h> 
void main() { 
//variable declaration 
//read values input from user 
//computation 
//print output to user 
} 
Notes: 
 what follows after // on the same line is considered comment 
 indentation is for the reader; compiler ignores all spaces and new 
line ; the delimiter for the compiler is the semicolon 
 all statements ended by ;
3 
Identifiers 
 Rules: 
 Names begin with alphabetic character 
including an underscore e.g. get_Name, 
_Name, a_type 
 Variables- Case sensitive 
 Lower vs. upper case matters!! 
 Void is different than void 
 Main is different that main 
Initialization can be done at the beginning e.g. 
int m=10;
4 
Example 
When learning a new language, the first program people 
usually write is one that salutes the world :) 
Here is the Hello world program in C++. 
#include <iostream.h> 
int main() { 
cout << “Hello world!”; 
return 0; 
}
5 
Variable declaration 
type variable-name; 
Meaning: variable <variable-name> will be a variable of type 
<type> 
Where type can be: 
 int //integer 
 double //real number 
 char //character 
 Long int // 32 bits 
 Float // floating point numbers 
Example: 
int a, b, c; 
double x; 
int sum; 
char my-character;
6 
Input statements 
cin >> variable-name; 
Meaning: read the value of variable <variable-name> 
from the user 
Example: 
cin >> a; 
cin >> b >> c; 
cin >> x; 
cin >> my-character;
7 
Output statements 
cout << variable-name; 
Meaning: print the value of variable <variable-name> to the user 
cout << “any message “; 
Meaning: print the message within quotes to the user 
cout << endl; 
Meaning: print a new line 
Example: 
cout << a; 
cout << b << c; 
cout << “This is my character: “ << my-character << “ he he he”<< endl;
8 
If statements 
if (condition) { 
S1; 
} 
else { 
S2; 
} 
S3; 
True False 
condition 
S1 S2 
S3
9 
Boolean conditions 
..are built using 
 Comparison operators 
== equal 
!= not equal 
< less than 
> greater than 
<= less than or equal 
>= greater than or equal 
 Boolean operators 
&& and 
|| or 
! not
10 
Examples 
Assume we declared the following variables: 
int a = 2, b=5, c=10; 
Here are some examples of boolean conditions we 
can use: 
 if (a == b) … 
 if (a != b) … 
 if (a <= b+c) … 
 if(a <= b) && (b <= c) … 
 if !((a < b) && (b<c)) …
11 
If example 
#include <iostream.h> 
void main() { 
int a,b,c; 
cin >> a >> b >> c; 
if (a <=b) { 
cout << “min is “ << a << endl; 
} 
else { 
cout << “ min is “ << b << endl; 
} 
cout << “happy now?” << endl; 
}
12 
While statements 
while (condition) { 
S1; 
} 
S2; 
True False 
condition 
S1 
S2
13 
While example 
//read 100 numbers from the user and output their sum 
#include <iostream.h> 
void main() { 
int i, sum, x; 
sum=0; 
i=1; 
while (i <= 100) { 
cin >> x; 
sum = sum + x; 
i = i+1; 
} 
cout << “sum is “ << sum << endl; 
}
14 
Arrays 
Used to store a collection of elements (variables) 
type array-name[size]; 
Meaning: 
This declares a variable called <array-name> which contains 
<size> elements of type <type> 
The elements of an array can be accessed as: array-name[0], 
…array-name[size-1] 
Example: 
int a[100]; //a is a list of 100 integers, a[0], a[1], …a[99] 
double b[50]; 
char c[10];
15 
Array example 
//Read 100 numbers from the user 
#include <iostream.h> 
void main() { 
int i, a[100], n; 
i=0; n=100; 
while (i<n) { 
cout << “Input element “ << i << “: ”; 
cin >> a[i]; 
i = i+1; 
} 
//do somehing with it .. 
}
16 
Exercises 
Write a C++ program to read a sequence of (non-negative) 
integers from the user ending with a negative integer and 
write out 
 the average of the numbers 
 the smallest number 
 the largest number 
 the range of the numbers (largest - smallest) 
 Example: 
 The user enters: 3, 1, 55, 89, 23, 45, -1 
 Your program should compute the average of {3, 1, 55, 89, 23, 
45} etc
17 
Exercises 
 Write a program that asks the user 
 Do you want to use this program? (y/n) 
 If the user says ‘y’ then the program 
terminates 
 If the user says ‘n’ then the program asks 
 Are you really sure you do not want to use this program? (y/n) 
 If the user says ‘n’ it terminates, otherwise it prints 
again the message 
 Are you really really sure you do not want to use this program? 
(y/n) 
 And so on, every time adding one more “really”.
18 
Pointers 
int *intPtr; 
intPtr = new int; 
*intPtr = 6837; 
delete intPtr; 
int otherVal = 5; 
intPtr = &otherVal; 
Create a pointer 
Allocate memory 
Set value at given address 
*intPtr 6837 
intPtr 0x0050 
Change intPtr to point to 
a new location 
*intPtr 5 
intPtr 0x0054 
otherVal 
&otherVal 
Deallocate memory
19 
Arrays 
Stack allocation 
int intArray[10]; 
intArray[0] = 6837; 
Heap allocation 
int *intArray; 
intArray = new int[10]; 
intArray[0] = 6837; 
... 
delete[] intArray;
20 
Strings 
A string in C++ is an array of characters 
char myString[20]; 
strcpy(myString, "Hello World"); 
Strings are terminated with the NULL or '0' character 
myString[0] = 'H'; 
myString[1] = 'i'; 
myString[2] = '0'; 
printf("%s", myString); 
output: Hi
Prevents multiple references 
21 
Class Basics 
#ifndef _IMAGE_H_ 
#define _IMAGE_H_ 
#include <assert.h> 
#include "vectors.h“ 
class Image { 
public: 
... 
private: 
... 
}; 
#endif 
Include a library file 
Include a local file 
Variables and functions 
accessible from anywhere 
Variables and functions accessible 
only from within this class
22 
C++ Functions 
Predefined Functions 
 C++ comes with libraries of predefined 
functions 
 Example: sqrt function 
 the_root = sqrt(9.0); 
 returns, or computes, the square root 
of a number 
 The number, 9, is called the argument 
 the_root will contain 3.0 
3.2
23 
Function Calls 
 sqrt(9.0) is a function call 
 It invokes, or sets in action, the sqrt function 
 The argument (9), can also be a variable or an 
expression 
 A function call can be used like any 
expression 
 bonus = sqrt(sales) / 10; 
 Cout << “The side of a square with area “ << 
area 
<< “ is “ << sqrt(area);
24 
Function Call Syntax 
 Function_name (Argument_List) 
 Argument_List is a comma separated list: 
(Argument_1, Argument_2, … , Argument_Last) 
 Example: 
 side = sqrt(area); 
 cout << “2.5 to the power 3.0 is “ << pow(2.5, 3.0);
25 
Function Libraries 
 Predefined functions are found in libraries 
 The library must be “included” in a program 
to make the functions available 
 An include directive tells the compiler which 
library header file to include. 
 To include the math library containing sqrt(): 
#include <cmath> 
 Newer standard libraries, such as cmath, also 
require the directive using namespace std;
26 
Other Predefined Functions 
 abs(x) --- int value = abs(-8); 
 Returns absolute value of argument x 
 Return value is of type int 
 Argument is of type x 
 Found in the library cstdlib 
 fabs(x) --- double value = fabs(-8.0); 
 Returns the absolute value of argument x 
 Return value is of type double 
 Argument is of type double 
 Found in the library cmath
27 
Type Casting 
 Look at this problem with integer division: 
int total_candy = 9, number_of_people = 4; 
double candy_per_person; 
candy_per_person = total_candy / number_of_people; 
 candy_per_person = 2, not 2.25! 
 A Type Cast produces a value of one type 
from another type 
 static_cast<double>(total_candy) produces a double 
representing the integer value of total_candy
28 
Type Cast Example 
 int total_candy = 9, number_of_people = 4; 
double candy_per_person; 
candy_per_person = static_cast<double>(total_candy)/ 
number_of_people; candy_per_person now is 2.25! 
 This would also work: 
candy_per_person = total_candy / 
static_cast<double>( number_of_people); 
 This would not! 
candy_per_person = static_cast<double>( total_candy / 
number_of_people); 
Integer division occurs before type cast
29 
Exercise 
 Can you 
 Determine the value of d? 
double d = 11 / 2; 
 Determine the value of 
pow(2,3) fabs(-3.5), sqrt(pow(3,2)) 
7 / abs(-2),ceil(5.8),floor(5.8) 
 Convert the following to C++ 
x + y xy+7 
b b ac 
- + 2 - 4 
a 
2
30 
Programmer-Defined Functions 
 Two components of a function definition 
 Function declaration (or function prototype) 
 Shows how the function is called 
 Must appear in the code before the function can be called 
 Syntax: 
Type_returned Function_Name(Parameter_List); 
//Comment describing what function does 
 Function definition 
 Describes how the function does its task 
 Can appear before or after the function is called 
 Syntax: 
Type_returned Function_Name(Parameter_List) 
{ 
//code to make the function work 
} 
; 
3.3
31 
Function Declaration 
 Tells the return type 
 Tells the name of the function 
 Tells how many arguments are needed 
 Tells the types of the arguments 
 Tells the formal parameter names 
 Formal parameters are like placeholders for the actual 
arguments used when the function is called 
 Formal parameter names can be any valid identifier 
 Example: 
double total_cost(int number_par, double price_par); 
// Compute total cost including 5% sales tax on 
// number_par items at cost of price_par each
32 
Function Definition 
 Provides the same information as the declaration 
 Describes how the function does its task 
 Example: 
function header 
double total_cost(int number_par, double price_par) 
{ 
const double TAX_RATE = 0.05; //5% tax 
double subtotal; 
subtotal = price_par * number_par; 
return (subtotal + subtotal * TAX_RATE); 
} 
function body
33 
The Return Statement 
 Ends the function call 
 Returns the value calculated by the function 
 Syntax: 
return expression; 
 expression performs the calculation 
or 
 expression is a variable containing the 
calculated value 
 Example: 
return subtotal + subtotal * TAX_RATE;
34 
The Function Call 
 Tells the name of the function to use 
 Lists the arguments 
 Is used in a statement where the 
returned value makes sense 
 Example: 
double bill = total_cost(number, price);
35 
Function Call Details 
 The values of the arguments are plugged into 
the formal parameters (Call-by-value 
mechanism with call-by-value parameters) 
 The first argument is used for the first formal 
parameter, the second argument for the second 
formal parameter, and so forth. 
 The value plugged into the formal parameter is used 
in all instances of the formal parameter in the 
function body
36 
Alternate Declarations 
 Two forms for function declarations 
1. List formal parameter names 
2. List types of formal parmeters, but not names 
 First aids description of the function in comments 
 Examples: 
double total_cost(int number_par, double price_par); 
double total_cost(int, double); 
 Function headers must always list formal 
parameter names!
37 
Order of Arguments 
 Compiler checks that the types of the arguments 
are correct and in the correct sequence. 
 Compiler cannot check that arguments are in the 
correct logical order 
 Example: Given the function declaration: 
char grade(int received_par, int min_score_par); 
int received = 95, min_score = 60; 
cout << grade( min_score, received); 
 Produces a faulty result because the arguments are not in 
the correct logical order. The compiler will not catch this!
38 
Function Definition Syntax 
 Within a function definition 
 Variables must be declared before they 
are used 
 Variables are typically declared before 
the executable statements begin 
 At least one return statement must end 
the function 
 Each branch of an if-else statement might 
have its own return statement
39 
Placing Definitions 
 A function call must be preceded by either 
 The function’s declaration 
or 
 The function’s definition 
 If the function’s definition precedes the call, a 
declaration is not needed 
 Placing the function declaration prior to the 
main function and the function definition 
after the main function leads naturally to 
building your own libraries in the future.
40 
Parameter Passing 
pass by value 
int add(int a, int b) { 
return a+b; 
} 
int a, b, sum; 
sum = add(a, b); 
pass by reference 
int add(int *a, int *b) { 
return *a + *b; 
} 
int a, b, sum; 
sum = add(&a, &b); 
Make a local copy of a & b 
Pass pointers that reference 
a & b. Changes made to a 
or b will be reflected 
outside the add routine
41 
Parameter Passing 
pass by reference – alternate notation 
int add(int &a, int &b) { 
return a+b; 
} 
int a, b, sum; 
sum = add(a, b);
42 
Exercise 
 Can you 
 Write a function declaration and a function definition 
for a function that takes three arguments, all of type 
int, and that returns the sum of its three arguments? 
 Describe the call-by-value parameter mechanism? 
 Write a function declaration and a function definition 
for a function that takes one argument of type int and 
one argument of type double, and that returns a value 
of type double that is the average of the two 
arguments?
43 
Good sites 
 http://www.cs.ucr.edu/cs10/cs10_03fal/slides/

Weitere ähnliche Inhalte

Was ist angesagt? (20)

Unit 3
Unit 3 Unit 3
Unit 3
 
Python unit 3 and Unit 4
Python unit 3 and Unit 4Python unit 3 and Unit 4
Python unit 3 and Unit 4
 
Lecture 6- Intorduction to C Programming
Lecture 6- Intorduction to C ProgrammingLecture 6- Intorduction to C Programming
Lecture 6- Intorduction to C Programming
 
Lecture 12 - Recursion
Lecture 12 - Recursion Lecture 12 - Recursion
Lecture 12 - Recursion
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
 
Pointers
PointersPointers
Pointers
 
FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
 
Arrays in C++
Arrays in C++Arrays in C++
Arrays in C++
 
Lecture 17 - Strings
Lecture 17 - StringsLecture 17 - Strings
Lecture 17 - Strings
 
Pointers in C
Pointers in CPointers in C
Pointers in C
 
C interview question answer 2
C interview question answer 2C interview question answer 2
C interview question answer 2
 
Lecture 10 - Control Structures 2
Lecture 10 - Control Structures 2Lecture 10 - Control Structures 2
Lecture 10 - Control Structures 2
 
Pointer in C++
Pointer in C++Pointer in C++
Pointer in C++
 
Ch5 array nota
Ch5 array notaCh5 array nota
Ch5 array nota
 
Lecture 9- Control Structures 1
Lecture 9- Control Structures 1Lecture 9- Control Structures 1
Lecture 9- Control Structures 1
 
Programming in C (part 2)
Programming in C (part 2)Programming in C (part 2)
Programming in C (part 2)
 
Captitude 2doc-100627004318-phpapp01
Captitude 2doc-100627004318-phpapp01Captitude 2doc-100627004318-phpapp01
Captitude 2doc-100627004318-phpapp01
 
C aptitude.2doc
C aptitude.2docC aptitude.2doc
C aptitude.2doc
 
Pointers+(2)
Pointers+(2)Pointers+(2)
Pointers+(2)
 

Andere mochten auch

Adjustments to final accounts
Adjustments to final accountsAdjustments to final accounts
Adjustments to final accountsWarui Maina
 
8.project management chapter 8
8.project management chapter 88.project management chapter 8
8.project management chapter 8Warui Maina
 
3.o o design -_____________lecture 3
3.o o design -_____________lecture 33.o o design -_____________lecture 3
3.o o design -_____________lecture 3Warui Maina
 
INTRODUCTION TO SYSTEMS AND INFORMATION SYSTEMS IN ORGANIZATIONS
INTRODUCTION TO SYSTEMS AND INFORMATION SYSTEMS IN ORGANIZATIONSINTRODUCTION TO SYSTEMS AND INFORMATION SYSTEMS IN ORGANIZATIONS
INTRODUCTION TO SYSTEMS AND INFORMATION SYSTEMS IN ORGANIZATIONSWarui Maina
 
9.process improvement chapter 9
9.process improvement chapter 99.process improvement chapter 9
9.process improvement chapter 9Warui Maina
 
Closed systems, open systems
Closed systems, open systemsClosed systems, open systems
Closed systems, open systemsrobin fay
 

Andere mochten auch (6)

Adjustments to final accounts
Adjustments to final accountsAdjustments to final accounts
Adjustments to final accounts
 
8.project management chapter 8
8.project management chapter 88.project management chapter 8
8.project management chapter 8
 
3.o o design -_____________lecture 3
3.o o design -_____________lecture 33.o o design -_____________lecture 3
3.o o design -_____________lecture 3
 
INTRODUCTION TO SYSTEMS AND INFORMATION SYSTEMS IN ORGANIZATIONS
INTRODUCTION TO SYSTEMS AND INFORMATION SYSTEMS IN ORGANIZATIONSINTRODUCTION TO SYSTEMS AND INFORMATION SYSTEMS IN ORGANIZATIONS
INTRODUCTION TO SYSTEMS AND INFORMATION SYSTEMS IN ORGANIZATIONS
 
9.process improvement chapter 9
9.process improvement chapter 99.process improvement chapter 9
9.process improvement chapter 9
 
Closed systems, open systems
Closed systems, open systemsClosed systems, open systems
Closed systems, open systems
 

Ähnlich wie 2.overview of c++ ________lecture2

18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operator18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operatorSAFFI Ud Din Ahmad
 
1. DSA - Introduction.pptx
1. DSA - Introduction.pptx1. DSA - Introduction.pptx
1. DSA - Introduction.pptxhara69
 
C++ Tutorial.docx
C++ Tutorial.docxC++ Tutorial.docx
C++ Tutorial.docxPinkiVats1
 
Python programing
Python programingPython programing
Python programinghamzagame
 
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo JobyC++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo JobyGrejoJoby1
 
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docxPROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docxamrit47
 
02a fundamental c++ types, arithmetic
02a   fundamental c++ types, arithmetic 02a   fundamental c++ types, arithmetic
02a fundamental c++ types, arithmetic Manzoor ALam
 
Bikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa_Thapa_Python_Programming_(Basics).pptxBikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa_Thapa_Python_Programming_(Basics).pptxBikalpa Thapa
 
C++ Course - Lesson 3
C++ Course - Lesson 3C++ Course - Lesson 3
C++ Course - Lesson 3Mohamed Ahmed
 
Templates exception handling
Templates exception handlingTemplates exception handling
Templates exception handlingsanya6900
 

Ähnlich wie 2.overview of c++ ________lecture2 (20)

18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operator18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operator
 
1. DSA - Introduction.pptx
1. DSA - Introduction.pptx1. DSA - Introduction.pptx
1. DSA - Introduction.pptx
 
Chapter1.pptx
Chapter1.pptxChapter1.pptx
Chapter1.pptx
 
C++ Tutorial.docx
C++ Tutorial.docxC++ Tutorial.docx
C++ Tutorial.docx
 
Python programing
Python programingPython programing
Python programing
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
 
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo JobyC++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
 
C++ Language
C++ LanguageC++ Language
C++ Language
 
pythonQuick.pdf
pythonQuick.pdfpythonQuick.pdf
pythonQuick.pdf
 
python notes.pdf
python notes.pdfpython notes.pdf
python notes.pdf
 
python 34💭.pdf
python 34💭.pdfpython 34💭.pdf
python 34💭.pdf
 
Namespaces
NamespacesNamespaces
Namespaces
 
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docxPROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
 
02a fundamental c++ types, arithmetic
02a   fundamental c++ types, arithmetic 02a   fundamental c++ types, arithmetic
02a fundamental c++ types, arithmetic
 
Bikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa_Thapa_Python_Programming_(Basics).pptxBikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa_Thapa_Python_Programming_(Basics).pptx
 
Pseudocode
PseudocodePseudocode
Pseudocode
 
C++ Functions.ppt
C++ Functions.pptC++ Functions.ppt
C++ Functions.ppt
 
C++ Course - Lesson 3
C++ Course - Lesson 3C++ Course - Lesson 3
C++ Course - Lesson 3
 
Csharp4 basics
Csharp4 basicsCsharp4 basics
Csharp4 basics
 
Templates exception handling
Templates exception handlingTemplates exception handling
Templates exception handling
 

Mehr von Warui Maina

Partnership Accounting notes (Dac 301)
Partnership Accounting notes (Dac 301)Partnership Accounting notes (Dac 301)
Partnership Accounting notes (Dac 301)Warui Maina
 
Consolidated accounts or Group Acccounts
Consolidated accounts or Group AcccountsConsolidated accounts or Group Acccounts
Consolidated accounts or Group AcccountsWarui Maina
 
Capital budgeting methods lecture notes
Capital budgeting methods lecture notesCapital budgeting methods lecture notes
Capital budgeting methods lecture notesWarui Maina
 
Flexible budgets and basic variance analysis (DAC 203 Management Accounting)
Flexible budgets and basic variance analysis (DAC 203 Management Accounting)Flexible budgets and basic variance analysis (DAC 203 Management Accounting)
Flexible budgets and basic variance analysis (DAC 203 Management Accounting)Warui Maina
 
Internal control lecture notes (DAC 401: Principles and practices of auditing)
Internal control lecture notes (DAC 401: Principles and practices of auditing)Internal control lecture notes (DAC 401: Principles and practices of auditing)
Internal control lecture notes (DAC 401: Principles and practices of auditing)Warui Maina
 
Accounting and Financial Practice Questions (DAC 302 revision questions)
Accounting and Financial Practice Questions (DAC 302 revision questions)Accounting and Financial Practice Questions (DAC 302 revision questions)
Accounting and Financial Practice Questions (DAC 302 revision questions)Warui Maina
 
International financial institutions notes
International financial institutions notesInternational financial institutions notes
International financial institutions notesWarui Maina
 
Company law revision questions 1
Company law revision questions 1Company law revision questions 1
Company law revision questions 1Warui Maina
 
Company Law - Meetings
Company Law - MeetingsCompany Law - Meetings
Company Law - MeetingsWarui Maina
 
Company Law - FORMATION AND FLOTATION OF A COMPANY
Company Law - FORMATION AND FLOTATION OF A COMPANYCompany Law - FORMATION AND FLOTATION OF A COMPANY
Company Law - FORMATION AND FLOTATION OF A COMPANYWarui Maina
 
Company Law - Shares Notes
Company Law - Shares NotesCompany Law - Shares Notes
Company Law - Shares NotesWarui Maina
 
Company Law - Capital
Company Law - CapitalCompany Law - Capital
Company Law - CapitalWarui Maina
 
Company Law - Promotion
Company  Law - PromotionCompany  Law - Promotion
Company Law - PromotionWarui Maina
 
Challenges Facing Nairobi Securities Exchange
Challenges Facing Nairobi Securities ExchangeChallenges Facing Nairobi Securities Exchange
Challenges Facing Nairobi Securities ExchangeWarui Maina
 
7.quality management chapter 7
7.quality management chapter 77.quality management chapter 7
7.quality management chapter 7Warui Maina
 
4.o o design tools=uml -_lecture 4
4.o o design tools=uml -_lecture 44.o o design tools=uml -_lecture 4
4.o o design tools=uml -_lecture 4Warui Maina
 

Mehr von Warui Maina (17)

Partnership Accounting notes (Dac 301)
Partnership Accounting notes (Dac 301)Partnership Accounting notes (Dac 301)
Partnership Accounting notes (Dac 301)
 
Consolidated accounts or Group Acccounts
Consolidated accounts or Group AcccountsConsolidated accounts or Group Acccounts
Consolidated accounts or Group Acccounts
 
Capital budgeting methods lecture notes
Capital budgeting methods lecture notesCapital budgeting methods lecture notes
Capital budgeting methods lecture notes
 
Flexible budgets and basic variance analysis (DAC 203 Management Accounting)
Flexible budgets and basic variance analysis (DAC 203 Management Accounting)Flexible budgets and basic variance analysis (DAC 203 Management Accounting)
Flexible budgets and basic variance analysis (DAC 203 Management Accounting)
 
Internal control lecture notes (DAC 401: Principles and practices of auditing)
Internal control lecture notes (DAC 401: Principles and practices of auditing)Internal control lecture notes (DAC 401: Principles and practices of auditing)
Internal control lecture notes (DAC 401: Principles and practices of auditing)
 
Accounting and Financial Practice Questions (DAC 302 revision questions)
Accounting and Financial Practice Questions (DAC 302 revision questions)Accounting and Financial Practice Questions (DAC 302 revision questions)
Accounting and Financial Practice Questions (DAC 302 revision questions)
 
International financial institutions notes
International financial institutions notesInternational financial institutions notes
International financial institutions notes
 
Company law revision questions 1
Company law revision questions 1Company law revision questions 1
Company law revision questions 1
 
Company Law - Meetings
Company Law - MeetingsCompany Law - Meetings
Company Law - Meetings
 
Company Law - FORMATION AND FLOTATION OF A COMPANY
Company Law - FORMATION AND FLOTATION OF A COMPANYCompany Law - FORMATION AND FLOTATION OF A COMPANY
Company Law - FORMATION AND FLOTATION OF A COMPANY
 
Company Law - Shares Notes
Company Law - Shares NotesCompany Law - Shares Notes
Company Law - Shares Notes
 
Company Law - Capital
Company Law - CapitalCompany Law - Capital
Company Law - Capital
 
Company Law - Promotion
Company  Law - PromotionCompany  Law - Promotion
Company Law - Promotion
 
Challenges Facing Nairobi Securities Exchange
Challenges Facing Nairobi Securities ExchangeChallenges Facing Nairobi Securities Exchange
Challenges Facing Nairobi Securities Exchange
 
Group Accounts
Group AccountsGroup Accounts
Group Accounts
 
7.quality management chapter 7
7.quality management chapter 77.quality management chapter 7
7.quality management chapter 7
 
4.o o design tools=uml -_lecture 4
4.o o design tools=uml -_lecture 44.o o design tools=uml -_lecture 4
4.o o design tools=uml -_lecture 4
 

Kürzlich hochgeladen

MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYKayeClaireEstoconing
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Q4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxQ4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxnelietumpap1
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 

Kürzlich hochgeladen (20)

MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Q4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxQ4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptx
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 

2.overview of c++ ________lecture2

  • 1. 1 AA qquuiicckk iinnttrroodduuccttiioonn ttoo CC++++
  • 2. 2 A C++ program //if necessary include headers //#include <foo.h> void main() { //variable declaration //read values input from user //computation //print output to user } Notes:  what follows after // on the same line is considered comment  indentation is for the reader; compiler ignores all spaces and new line ; the delimiter for the compiler is the semicolon  all statements ended by ;
  • 3. 3 Identifiers  Rules:  Names begin with alphabetic character including an underscore e.g. get_Name, _Name, a_type  Variables- Case sensitive  Lower vs. upper case matters!!  Void is different than void  Main is different that main Initialization can be done at the beginning e.g. int m=10;
  • 4. 4 Example When learning a new language, the first program people usually write is one that salutes the world :) Here is the Hello world program in C++. #include <iostream.h> int main() { cout << “Hello world!”; return 0; }
  • 5. 5 Variable declaration type variable-name; Meaning: variable <variable-name> will be a variable of type <type> Where type can be:  int //integer  double //real number  char //character  Long int // 32 bits  Float // floating point numbers Example: int a, b, c; double x; int sum; char my-character;
  • 6. 6 Input statements cin >> variable-name; Meaning: read the value of variable <variable-name> from the user Example: cin >> a; cin >> b >> c; cin >> x; cin >> my-character;
  • 7. 7 Output statements cout << variable-name; Meaning: print the value of variable <variable-name> to the user cout << “any message “; Meaning: print the message within quotes to the user cout << endl; Meaning: print a new line Example: cout << a; cout << b << c; cout << “This is my character: “ << my-character << “ he he he”<< endl;
  • 8. 8 If statements if (condition) { S1; } else { S2; } S3; True False condition S1 S2 S3
  • 9. 9 Boolean conditions ..are built using  Comparison operators == equal != not equal < less than > greater than <= less than or equal >= greater than or equal  Boolean operators && and || or ! not
  • 10. 10 Examples Assume we declared the following variables: int a = 2, b=5, c=10; Here are some examples of boolean conditions we can use:  if (a == b) …  if (a != b) …  if (a <= b+c) …  if(a <= b) && (b <= c) …  if !((a < b) && (b<c)) …
  • 11. 11 If example #include <iostream.h> void main() { int a,b,c; cin >> a >> b >> c; if (a <=b) { cout << “min is “ << a << endl; } else { cout << “ min is “ << b << endl; } cout << “happy now?” << endl; }
  • 12. 12 While statements while (condition) { S1; } S2; True False condition S1 S2
  • 13. 13 While example //read 100 numbers from the user and output their sum #include <iostream.h> void main() { int i, sum, x; sum=0; i=1; while (i <= 100) { cin >> x; sum = sum + x; i = i+1; } cout << “sum is “ << sum << endl; }
  • 14. 14 Arrays Used to store a collection of elements (variables) type array-name[size]; Meaning: This declares a variable called <array-name> which contains <size> elements of type <type> The elements of an array can be accessed as: array-name[0], …array-name[size-1] Example: int a[100]; //a is a list of 100 integers, a[0], a[1], …a[99] double b[50]; char c[10];
  • 15. 15 Array example //Read 100 numbers from the user #include <iostream.h> void main() { int i, a[100], n; i=0; n=100; while (i<n) { cout << “Input element “ << i << “: ”; cin >> a[i]; i = i+1; } //do somehing with it .. }
  • 16. 16 Exercises Write a C++ program to read a sequence of (non-negative) integers from the user ending with a negative integer and write out  the average of the numbers  the smallest number  the largest number  the range of the numbers (largest - smallest)  Example:  The user enters: 3, 1, 55, 89, 23, 45, -1  Your program should compute the average of {3, 1, 55, 89, 23, 45} etc
  • 17. 17 Exercises  Write a program that asks the user  Do you want to use this program? (y/n)  If the user says ‘y’ then the program terminates  If the user says ‘n’ then the program asks  Are you really sure you do not want to use this program? (y/n)  If the user says ‘n’ it terminates, otherwise it prints again the message  Are you really really sure you do not want to use this program? (y/n)  And so on, every time adding one more “really”.
  • 18. 18 Pointers int *intPtr; intPtr = new int; *intPtr = 6837; delete intPtr; int otherVal = 5; intPtr = &otherVal; Create a pointer Allocate memory Set value at given address *intPtr 6837 intPtr 0x0050 Change intPtr to point to a new location *intPtr 5 intPtr 0x0054 otherVal &otherVal Deallocate memory
  • 19. 19 Arrays Stack allocation int intArray[10]; intArray[0] = 6837; Heap allocation int *intArray; intArray = new int[10]; intArray[0] = 6837; ... delete[] intArray;
  • 20. 20 Strings A string in C++ is an array of characters char myString[20]; strcpy(myString, "Hello World"); Strings are terminated with the NULL or '0' character myString[0] = 'H'; myString[1] = 'i'; myString[2] = '0'; printf("%s", myString); output: Hi
  • 21. Prevents multiple references 21 Class Basics #ifndef _IMAGE_H_ #define _IMAGE_H_ #include <assert.h> #include "vectors.h“ class Image { public: ... private: ... }; #endif Include a library file Include a local file Variables and functions accessible from anywhere Variables and functions accessible only from within this class
  • 22. 22 C++ Functions Predefined Functions  C++ comes with libraries of predefined functions  Example: sqrt function  the_root = sqrt(9.0);  returns, or computes, the square root of a number  The number, 9, is called the argument  the_root will contain 3.0 3.2
  • 23. 23 Function Calls  sqrt(9.0) is a function call  It invokes, or sets in action, the sqrt function  The argument (9), can also be a variable or an expression  A function call can be used like any expression  bonus = sqrt(sales) / 10;  Cout << “The side of a square with area “ << area << “ is “ << sqrt(area);
  • 24. 24 Function Call Syntax  Function_name (Argument_List)  Argument_List is a comma separated list: (Argument_1, Argument_2, … , Argument_Last)  Example:  side = sqrt(area);  cout << “2.5 to the power 3.0 is “ << pow(2.5, 3.0);
  • 25. 25 Function Libraries  Predefined functions are found in libraries  The library must be “included” in a program to make the functions available  An include directive tells the compiler which library header file to include.  To include the math library containing sqrt(): #include <cmath>  Newer standard libraries, such as cmath, also require the directive using namespace std;
  • 26. 26 Other Predefined Functions  abs(x) --- int value = abs(-8);  Returns absolute value of argument x  Return value is of type int  Argument is of type x  Found in the library cstdlib  fabs(x) --- double value = fabs(-8.0);  Returns the absolute value of argument x  Return value is of type double  Argument is of type double  Found in the library cmath
  • 27. 27 Type Casting  Look at this problem with integer division: int total_candy = 9, number_of_people = 4; double candy_per_person; candy_per_person = total_candy / number_of_people;  candy_per_person = 2, not 2.25!  A Type Cast produces a value of one type from another type  static_cast<double>(total_candy) produces a double representing the integer value of total_candy
  • 28. 28 Type Cast Example  int total_candy = 9, number_of_people = 4; double candy_per_person; candy_per_person = static_cast<double>(total_candy)/ number_of_people; candy_per_person now is 2.25!  This would also work: candy_per_person = total_candy / static_cast<double>( number_of_people);  This would not! candy_per_person = static_cast<double>( total_candy / number_of_people); Integer division occurs before type cast
  • 29. 29 Exercise  Can you  Determine the value of d? double d = 11 / 2;  Determine the value of pow(2,3) fabs(-3.5), sqrt(pow(3,2)) 7 / abs(-2),ceil(5.8),floor(5.8)  Convert the following to C++ x + y xy+7 b b ac - + 2 - 4 a 2
  • 30. 30 Programmer-Defined Functions  Two components of a function definition  Function declaration (or function prototype)  Shows how the function is called  Must appear in the code before the function can be called  Syntax: Type_returned Function_Name(Parameter_List); //Comment describing what function does  Function definition  Describes how the function does its task  Can appear before or after the function is called  Syntax: Type_returned Function_Name(Parameter_List) { //code to make the function work } ; 3.3
  • 31. 31 Function Declaration  Tells the return type  Tells the name of the function  Tells how many arguments are needed  Tells the types of the arguments  Tells the formal parameter names  Formal parameters are like placeholders for the actual arguments used when the function is called  Formal parameter names can be any valid identifier  Example: double total_cost(int number_par, double price_par); // Compute total cost including 5% sales tax on // number_par items at cost of price_par each
  • 32. 32 Function Definition  Provides the same information as the declaration  Describes how the function does its task  Example: function header double total_cost(int number_par, double price_par) { const double TAX_RATE = 0.05; //5% tax double subtotal; subtotal = price_par * number_par; return (subtotal + subtotal * TAX_RATE); } function body
  • 33. 33 The Return Statement  Ends the function call  Returns the value calculated by the function  Syntax: return expression;  expression performs the calculation or  expression is a variable containing the calculated value  Example: return subtotal + subtotal * TAX_RATE;
  • 34. 34 The Function Call  Tells the name of the function to use  Lists the arguments  Is used in a statement where the returned value makes sense  Example: double bill = total_cost(number, price);
  • 35. 35 Function Call Details  The values of the arguments are plugged into the formal parameters (Call-by-value mechanism with call-by-value parameters)  The first argument is used for the first formal parameter, the second argument for the second formal parameter, and so forth.  The value plugged into the formal parameter is used in all instances of the formal parameter in the function body
  • 36. 36 Alternate Declarations  Two forms for function declarations 1. List formal parameter names 2. List types of formal parmeters, but not names  First aids description of the function in comments  Examples: double total_cost(int number_par, double price_par); double total_cost(int, double);  Function headers must always list formal parameter names!
  • 37. 37 Order of Arguments  Compiler checks that the types of the arguments are correct and in the correct sequence.  Compiler cannot check that arguments are in the correct logical order  Example: Given the function declaration: char grade(int received_par, int min_score_par); int received = 95, min_score = 60; cout << grade( min_score, received);  Produces a faulty result because the arguments are not in the correct logical order. The compiler will not catch this!
  • 38. 38 Function Definition Syntax  Within a function definition  Variables must be declared before they are used  Variables are typically declared before the executable statements begin  At least one return statement must end the function  Each branch of an if-else statement might have its own return statement
  • 39. 39 Placing Definitions  A function call must be preceded by either  The function’s declaration or  The function’s definition  If the function’s definition precedes the call, a declaration is not needed  Placing the function declaration prior to the main function and the function definition after the main function leads naturally to building your own libraries in the future.
  • 40. 40 Parameter Passing pass by value int add(int a, int b) { return a+b; } int a, b, sum; sum = add(a, b); pass by reference int add(int *a, int *b) { return *a + *b; } int a, b, sum; sum = add(&a, &b); Make a local copy of a & b Pass pointers that reference a & b. Changes made to a or b will be reflected outside the add routine
  • 41. 41 Parameter Passing pass by reference – alternate notation int add(int &a, int &b) { return a+b; } int a, b, sum; sum = add(a, b);
  • 42. 42 Exercise  Can you  Write a function declaration and a function definition for a function that takes three arguments, all of type int, and that returns the sum of its three arguments?  Describe the call-by-value parameter mechanism?  Write a function declaration and a function definition for a function that takes one argument of type int and one argument of type double, and that returns a value of type double that is the average of the two arguments?
  • 43. 43 Good sites  http://www.cs.ucr.edu/cs10/cs10_03fal/slides/

Hinweis der Redaktion

  1. C++ arrays are zero-indexed.
  2. Note that “private:” is the default