This document provides an introduction to C++ programming. It covers basic concepts like variables, data types, input/output statements, conditional statements, loops, arrays, functions, and classes. Some key points:
- A C++ program consists of variable declarations, input/output statements, computations, and printing output. Comments begin with //.
- Variables are declared with a data type like int or double followed by the name. Input is done with cin and output with cout.
- Conditional statements like if-else and loops like while are used to control program flow. Boolean conditions use comparison and logical operators.
- Arrays allow storing multiple values of a type. Functions can be predefined or programmer-
C Programming Language is the most popular computer language and most used programming language till now. It is very simple and elegant language. This lecture series will give you basic concepts of structured programming language with C.
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...ssuserd6b1fd
C programming language notes for beginners and Collage students. Written for beginners. Colored graphics. Function by Function explanation with complete examples. Well commented examples. Illustrations are made available for data dealing at memory level.
This set of slides introduces the reader to the concept of multidimensional arrays in C++ (with elements of C++11 and C++14). The true nature of multidimensional arrays is discussed by means of an intermediate type alias. The pheonomenon of array-to-pointer decay and pointer arithmetic is then generalized to arrays of arrays. The presentation proceeds with a discussion on how to pass multidimensional arrays to functions.
This set of slides introduces the reader to the concept of resource wrappers, i.e., classes that are responsible for the correct handling of resources of some kind (e.g., memory). In particular, the presentation discusses the design and implementation of a simplified version of std::vector for the specific case of integer elements. In this regard, we first discuss the fundamental role of destructors as a deterministic, general-purpose undo mechanism. Second, we notice that providing an explicit destructor entails the need of a consequent explicit implementation for the copy constructor and copy assignment operator. We conclude with the formulation of the so-called "rule of three".
C Programming Language is the most popular computer language and most used programming language till now. It is very simple and elegant language. This lecture series will give you basic concepts of structured programming language with C.
An introduction to pointers and references in C++ (with elements of C++11 and C++14). The presentation introduces the readers to the concepts of pointers and references through the pragmatic need of writing a swap function between integers. Generic programming notions (e.g., type constructors) are adopted when useful for the explanation.
C Programming Language is the most popular computer language and most used programming language till now. It is very simple and elegant language. This lecture series will give you basic concepts of structured programming language with C.
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...ssuserd6b1fd
C programming language notes for beginners and Collage students. Written for beginners. Colored graphics. Function by Function explanation with complete examples. Well commented examples. Illustrations are made available for data dealing at memory level.
This set of slides introduces the reader to the concept of multidimensional arrays in C++ (with elements of C++11 and C++14). The true nature of multidimensional arrays is discussed by means of an intermediate type alias. The pheonomenon of array-to-pointer decay and pointer arithmetic is then generalized to arrays of arrays. The presentation proceeds with a discussion on how to pass multidimensional arrays to functions.
This set of slides introduces the reader to the concept of resource wrappers, i.e., classes that are responsible for the correct handling of resources of some kind (e.g., memory). In particular, the presentation discusses the design and implementation of a simplified version of std::vector for the specific case of integer elements. In this regard, we first discuss the fundamental role of destructors as a deterministic, general-purpose undo mechanism. Second, we notice that providing an explicit destructor entails the need of a consequent explicit implementation for the copy constructor and copy assignment operator. We conclude with the formulation of the so-called "rule of three".
C Programming Language is the most popular computer language and most used programming language till now. It is very simple and elegant language. This lecture series will give you basic concepts of structured programming language with C.
An introduction to pointers and references in C++ (with elements of C++11 and C++14). The presentation introduces the readers to the concepts of pointers and references through the pragmatic need of writing a swap function between integers. Generic programming notions (e.g., type constructors) are adopted when useful for the explanation.
C Programming Language is the most popular computer language and most used programming language till now. It is very simple and elegant language. This lecture series will give you basic concepts of structured programming language with C.
C Programming Language is the most popular computer language and most used programming language till now. It is very simple and elegant language. This lecture series will give you basic concepts of structured programming language with C.
This set of slides introduces the reader to the concept of arrays in C++ (with elements of C++11 and C++14). After presenting the array data type, the concept of array-to-pointer decay is introduced. The presentation proceeds with a discussion on how to pass arrays to functions. To this extent, the reader is guided to the use of bounded ranges as the first step towards the use of the Standard Template Library (STL).
C Programming Language is the most popular computer language and most used programming language till now. It is very simple and elegant language. This lecture series will give you basic concepts of structured programming language with C.
C Programming Language is the most popular computer language and most used programming language till now. It is very simple and elegant language. This lecture series will give you basic concepts of structured programming language with C.
C Programming Language is the most popular computer language and most used programming language till now. It is very simple and elegant language. This lecture series will give you basic concepts of structured programming language with C.
C Programming Language is the most popular computer language and most used programming language till now. It is very simple and elegant language. This lecture series will give you basic concepts of structured programming language with C.
C Programming Language is the most popular computer language and most used programming language till now. It is very simple and elegant language. This lecture series will give you basic concepts of structured programming language with C.
This set of slides introduces the reader to the concept of arrays in C++ (with elements of C++11 and C++14). After presenting the array data type, the concept of array-to-pointer decay is introduced. The presentation proceeds with a discussion on how to pass arrays to functions. To this extent, the reader is guided to the use of bounded ranges as the first step towards the use of the Standard Template Library (STL).
C Programming Language is the most popular computer language and most used programming language till now. It is very simple and elegant language. This lecture series will give you basic concepts of structured programming language with C.
C Programming Language is the most popular computer language and most used programming language till now. It is very simple and elegant language. This lecture series will give you basic concepts of structured programming language with C.
C Programming Language is the most popular computer language and most used programming language till now. It is very simple and elegant language. This lecture series will give you basic concepts of structured programming language with C.
Very brief presentation about open vs. closed system, open source, community source, and some of the challenges by robin fay, georgiawebgurl@gmail.com.
learn how to program with python
from scratch to be an expert
use the link in the first slide to get the full course
here is the link if you want : https://oke.io/JdxdUl
the link of the documentation : https://oke.io/J6DeY3
link to download python : https://oke.io/BENgRLR2
I am Baddie K. I am a C++ Homework Expert at cpphomeworkhelp.com. I hold a Masters in Programming from The University of Queensland. I have been helping students with their homework for the past 9 years. I solve homework related to C++. Visit cpphomeworkhelp.com or email info@cpphomeworkhelp.com. You can also call on +1 678 648 4277 for any assistance with C++ Homework.
C++ and OOPS Crash Course by ACM DBIT | Grejo JobyGrejoJoby1
The slides from the C++ and OOPS Crash Course conducted for ACM DBIT by Grejo Joby.
Learn the concepts of OOPS and C++ Programming in the shortest time with these notes.
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docxamrit47
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY GOOD WORK NICE FORMULA OR SOMETHING LIKE THAT, BUT ACTULLY HE CAN USE. THANK YOU.
Hartleys Function Code
Contains unread posts
Actions for Hartleys Function Code
Chad Hartley posted Nov 5, 2015 5:10 PM
Subscribe
This program will add an integer number and a decimal number up to 2 decimal places. I have included notes in the code to explain what each thing does. I hope I did this right. It compiles successfully.
PseudoCode
Start
Declare int O1; Stands for Output1
O1=sum; Sum is the functions name
Int sum()
Declare variables
Int num1;
Float num2;
Write “Enter a number.”
Scanf num1
Write”Enter a decimal number.”
Scanf num2
Return num1+num2
end
C Code
#include <stdio.h>
int sum();//prototype
int main()//calling program
{
//Declare a varaiable
int O1;
O1=sum();//main is calling sum one time.
//if I listed this twice it would run the function 'sum' twice.
// Example: if I add a new int (int O1, O2) and declare O2 to
//be O2=sum then the function would run twice.
}
int sum ()//function 'sum'
{
int num1;// Declare intergers/variables
float num2;
printf("Enter a number.\n");
scanf("%d",&num1);// Take first input and assign it to num1
printf("Enter a decimal number.\n");
scanf("%.2f",&num2);
//Can use the printf statement but when you are calling an integer you can use the return.
//printf("The sum of %d, %d, is %d", num1,num2,num1+num2);
return num1+num2;
}
ADD COMMENT HERE
Chaotic Function
Contains unread posts
Actions for Chaotic Function
Joshua Ray posted Nov 5, 2015 2:33 PM
Subscribe
float tmp
int i
function float chaos(float num)
{
for i < 20
num = 3.9*num*(1-num)
print num
}
main
print "Program description"
print "Request input btw 0 and 1"
tmp = input
chaos(tmp)
/*
* File: main.c
* Author: JaiEllRei
*
* Created on November 5, 2015, 2:04 PM
*/
#include <stdio.h>
#include <stdlib.h>
float chaos(float num);
int main(void)
{
float tmp;
printf("This program illustrates a choatic function. \n");
printf("Input a number between 0 and 1: ");
scanf("%f", &tmp);
chaos(tmp);
}
float chaos(float num)
{
for (int i=0; i<20; i++){
/*Chaotic Formula*/
num = 3.9 * num * (1-num);
printf("%.3f \n", num);
}
}
This program illustrates a choatic function.
Input a number between 0 and 1: .2
0.624
0.915
0.303
0.824
0.566
0.958
0.156
0.514
0.974
0.098
0.345
0.881
0.409
0.943
0.210
0.647
0.891
0.379
0.918
0.293
ADD COMMENT HERE
//MPH to KPH Conversion Function
Function KPHConv(value) as float
Set KPHConv = value*1.609344
End Function
Pseudocode for simple conversion program calling function
//Declare function
// MPH to KPH Conversion Function
Functio ...
Notes on partnership accounting excellent for CPAs, Accounting, Finance and students taking introductory accounting classes. Notes are brief, clear and simple to understand.
Consolidated accounts or Group AcccountsWarui Maina
Lecture notes on Consolidated accounts or Group Accounts. They have illustrations, are brief and simple to understand. Excellent for revision and quick review for CPA, B.Com, Finance and Accounting students.
These lecture notes clearly explain the concept of shares in regards to Company Law. Excellent for revision and study for CPAs, Bcom or any students taking business related courses where business law is a course unit.
Operation “Blue Star” is the only event in the history of Independent India where the state went into war with its own people. Even after about 40 years it is not clear if it was culmination of states anger over people of the region, a political game of power or start of dictatorial chapter in the democratic setup.
The people of Punjab felt alienated from main stream due to denial of their just demands during a long democratic struggle since independence. As it happen all over the word, it led to militant struggle with great loss of lives of military, police and civilian personnel. Killing of Indira Gandhi and massacre of innocent Sikhs in Delhi and other India cities was also associated with this movement.
Model Attribute Check Company Auto PropertyCeline George
In Odoo, the multi-company feature allows you to manage multiple companies within a single Odoo database instance. Each company can have its own configurations while still sharing common resources such as products, customers, and suppliers.
Synthetic Fiber Construction in lab .pptxPavel ( NSTU)
Synthetic fiber production is a fascinating and complex field that blends chemistry, engineering, and environmental science. By understanding these aspects, students can gain a comprehensive view of synthetic fiber production, its impact on society and the environment, and the potential for future innovations. Synthetic fibers play a crucial role in modern society, impacting various aspects of daily life, industry, and the environment. ynthetic fibers are integral to modern life, offering a range of benefits from cost-effectiveness and versatility to innovative applications and performance characteristics. While they pose environmental challenges, ongoing research and development aim to create more sustainable and eco-friendly alternatives. Understanding the importance of synthetic fibers helps in appreciating their role in the economy, industry, and daily life, while also emphasizing the need for sustainable practices and innovation.
The Roman Empire A Historical Colossus.pdfkaushalkr1407
The Roman Empire, a vast and enduring power, stands as one of history's most remarkable civilizations, leaving an indelible imprint on the world. It emerged from the Roman Republic, transitioning into an imperial powerhouse under the leadership of Augustus Caesar in 27 BCE. This transformation marked the beginning of an era defined by unprecedented territorial expansion, architectural marvels, and profound cultural influence.
The empire's roots lie in the city of Rome, founded, according to legend, by Romulus in 753 BCE. Over centuries, Rome evolved from a small settlement to a formidable republic, characterized by a complex political system with elected officials and checks on power. However, internal strife, class conflicts, and military ambitions paved the way for the end of the Republic. Julius Caesar’s dictatorship and subsequent assassination in 44 BCE created a power vacuum, leading to a civil war. Octavian, later Augustus, emerged victorious, heralding the Roman Empire’s birth.
Under Augustus, the empire experienced the Pax Romana, a 200-year period of relative peace and stability. Augustus reformed the military, established efficient administrative systems, and initiated grand construction projects. The empire's borders expanded, encompassing territories from Britain to Egypt and from Spain to the Euphrates. Roman legions, renowned for their discipline and engineering prowess, secured and maintained these vast territories, building roads, fortifications, and cities that facilitated control and integration.
The Roman Empire’s society was hierarchical, with a rigid class system. At the top were the patricians, wealthy elites who held significant political power. Below them were the plebeians, free citizens with limited political influence, and the vast numbers of slaves who formed the backbone of the economy. The family unit was central, governed by the paterfamilias, the male head who held absolute authority.
Culturally, the Romans were eclectic, absorbing and adapting elements from the civilizations they encountered, particularly the Greeks. Roman art, literature, and philosophy reflected this synthesis, creating a rich cultural tapestry. Latin, the Roman language, became the lingua franca of the Western world, influencing numerous modern languages.
Roman architecture and engineering achievements were monumental. They perfected the arch, vault, and dome, constructing enduring structures like the Colosseum, Pantheon, and aqueducts. These engineering marvels not only showcased Roman ingenuity but also served practical purposes, from public entertainment to water supply.
The Indian economy is classified into different sectors to simplify the analysis and understanding of economic activities. For Class 10, it's essential to grasp the sectors of the Indian economy, understand their characteristics, and recognize their importance. This guide will provide detailed notes on the Sectors of the Indian Economy Class 10, using specific long-tail keywords to enhance comprehension.
For more information, visit-www.vavaclasses.com
Unit 8 - Information and Communication Technology (Paper I).pdfThiyagu K
This slides describes the basic concepts of ICT, basics of Email, Emerging Technology and Digital Initiatives in Education. This presentations aligns with the UGC Paper I syllabus.
Read| The latest issue of The Challenger is here! We are thrilled to announce that our school paper has qualified for the NATIONAL SCHOOLS PRESS CONFERENCE (NSPC) 2024. Thank you for your unwavering support and trust. Dive into the stories that made us stand out!
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdfTechSoup
In this webinar you will learn how your organization can access TechSoup's wide variety of product discount and donation programs. From hardware to software, we'll give you a tour of the tools available to help your nonprofit with productivity, collaboration, financial management, donor tracking, security, and more.
How to Make a Field invisible in Odoo 17Celine George
It is possible to hide or invisible some fields in odoo. Commonly using “invisible” attribute in the field definition to invisible the fields. This slide will show how to make a field invisible in odoo 17.
Palestine last event orientationfvgnh .pptxRaedMohamed3
An EFL lesson about the current events in Palestine. It is intended to be for intermediate students who wish to increase their listening skills through a short lesson in power point.
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/