0% found this document useful (0 votes)
25 views

CSC 218 Lecture Slides [Intro to C++]-1

Uploaded by

Habeeb
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

CSC 218 Lecture Slides [Intro to C++]-1

Uploaded by

Habeeb
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

CSC 218:

Computer Programming III (Scientific)


(3 Credits)

Amos O. Bajeh, PhD


Room 29, Ground Floor
CIS Building
Introduction to C/C++
Programming Language
C/C++ Programming Language
 History of C and C++ -assignment

 Fundamentals of C/C++

 Control structures

 Arrays and Pointers

 Functions

 Function libraries
 Fundamentals of C/C++
 Structure of C/C++ program:
Generally, a C/C++ program contain one or more functions of
which one must be a main function from which execution
begins.

1. Example:

Preprocessor directives #include <iostream>


int main(){
Main function definition cout<<“Hello world”;
}
2. Example:
Preprocessor directives #include <iostream>
User-defined function(s) void greet(){
Main function definition cout<<“Hello world”;
}
int main(){
greet();
}
3.
Preprocessor directives
User-defined function declaration(s)
Main function definition

Example:
#include <iostream>
void greet();
int main(){
greet();
}
void greet(){
cout<<“Hello world”;
}
Steps for Writing a C/C++ Program
1.Enter code in text editor
2.Compile the code using the C/C++
compiler Enter code into
Text Editor
3.If the code is error-free, execute the
program
4.Execute the program Compile the
Code

No Is
Debug the Code error-
free

Yes

Execute Code
 Fundamentals of C/C++
character set:
alphabets: a,b,c ….z, A,B,C…Z
digits: 0…9
special characters: +,-, /, ;, #, !, <, >, =, (, ), ^, ?, &, ,, *, ’, ”, {, }, %, :,|
Escape sequence: contains two characters but treated as a
single character and are used to denote special action:

Escape sequence meaning


\n New line
\t tab
\a alert
\\ backslash
\’ Single quotes
\” Double quotes
C Programming Language
 Fundamentals of C
reserved words: are words which have predefined meaning and
can only be used for the purpose they are defined.
auto, break, case, char, const, continue, default, do, double,
enum, else, extern, float, for, goto, if, int, long, register, return,
short, signed, sizeof, static, struct, switch, typedef, union,
unsigned, void, volatile, while

Comments : are descriptive text embedded within programs to


add explanatory notes into codes. They are not executed.
Comments can be enclosed in the symbols /* and */. In C++,
they can also begins with the symbol //.
 Fundamentals of C
Operators:
Arithmetic operators, Assignment operators, Logical operators,
Relational operators, Unary operators and Ternary/conditional
operator, shift operators, bitwise operators, comma operator
 Arithmetic operators

Operator Description
+ Additive operator (also used for joining strings)
- Subtraction operator
* Multiplication operator
/ Division operator
% Remainder operator
 Assignment operators

Operator Description

= x=y
+= x+=y implies x=x+y
-= x-=y implies x=x-y
*= x*=y implies x=x*y
/= x/=y implies x=x/y
%= x%=y implies x=x%y
 Relational operators
Operator Description
< Less than: returns 1 (true) if the left hand operand is numerically
less than the right hand operand otherwise it returns 0 (false)
<= Less than or equal to: returns 1 (true) if the left hand operand is
numerically less than or equal to the right hand operand otherwise
it returns 0 (false)
> Greater than: returns 1 (true) if the left hand operand is
numerically greater than the right hand operand otherwise it
returns 0 (false)
>= Greater than or equal to: returns 1 (true) if the left hand operand is
numerically greater than or equal to the right hand operand
otherwise it returns 0 (false)
== Equals to: returns 1 (true) if the left hand operand is numerically
equal to the right hand operand otherwise it returns 0 (false)
!= Not equal to: returns 1 (true) if the left hand operand is
numerically NOT equal to the right hand operand otherwise it
returns 0 (false)
 Logical operators

Operator Description
&& And: Returns 1 (true) iff both operands are true
|| Or: Returns true if one or both operands are true
! Negation: Inverts the value of a Boolean
& Bitwise And operator
| Bitwise Or operator
 Operators
 Unary operators
Operator Description
+ Indicates positive numbers
- Indicates a negative number or expression
++ Increment
-- Decrement

 Ternary operator ( ? : )
(relational/logical expr)? expr1 : expr2
e.g.
(age>18) ? salary=25000: salary=45000;
 Operator precedence
level operator associativity level operator associativity
1 ( ), [ ], -> Left to right 14 ?: Right to left
2 ~, ++, --, ! Left to right 15 =, +=, -=, *=, /=, %= Right to left
3 *, &, sizeof() Left to right 16 , Left to right
4 *, /, % Left to right
5 +, - Left to right
6 <<, >> Left to right
7 <, <=, >, >= Left to right
8 ==, != Left to right
9 & Left to right
10 ` Left to right
11 | Left to right
12 && Left to right
13 || Left to right
 Expression and Statement
 An Expression is a construct that consist of variables,
constants, operators or function invocation which yield a
single value
 Arithmetic expression
 Assignment expression
 Logical expression
 Relational expression

 A Statement is a complete program construct that causes


and execution. It is simply an expression terminated with a
semicolon:
 Assignment statement
• Simple statements
 Declaration statement • Compound statements
 Control flow statement
 Data Types
 Primitive/Basic data types
 Character (char)
 Integer (int)
 Float (float)
 Double (double)
These types can be further described using the qualifiers short,
long and unsigned as follows:
short int, long int, unsigned int, long float

 Composite/Derived data types


 Array
 Pointer
 Enumeration (enum)
 Structure (struct) and union
 Class
 Data Types:
 Primitive/Basic data types cont’d
Data type Memory space (bits) range
short 16 [-32768, 32767]
unsigned short 16 [0, 65535]
int 16 [-32768, 32767]
unsigned int 16 [0, 65535]
long 32 -2147483648, 2147483647
unsigned long 32 [0, 4294967295]
float 32 [3.4E-38, 3.4E38]
double 64 [1.7E-308, 1.7E308]
long double 80 [3.4E-4932, 1.1E4932]
unsigned char 8 [0, 255]
char 8 [-128, 127]
 Fundamentals of C/C++
Identifiers: are names assigned to program entities
Rules for constructing an identifier:
 Must start with an alphabet or the underscore ( _ )

 Other characters can be one or a combination of alphabets, digits or


underscore

 Must not be a reserved word

 C/C++ is case sensitive i.e. name, Name, naMe and NaMe are four
different identifiers

Note: Always use descriptive names as identifiers e.g. total is a better


identifier than t

Examples: _age, 4ages, cumulative_salary, electric&water, 123, auto,


 Fundamentals of C/C++

variables and constants :

Variables: are program entities that can change in


value during the course of program execution

Constants: are program entities that cannot change in


value during the course of program execution
 Variable Declaration
the syntax for declaring variables are:
 dataType varName;
e.g. int age;

 dataType varName [=initial value];


e.g. float height = 1.92;

 data_type list_of_varName;
e.g.
float vol, height, weight;
float age=32, height, weight=75;
 Constants
Literals Example
Integer 657, O657(octal), Ox657(hexadecimal)
Float 0.567, 1.8E3, 5.6E-4
Character ‘A’, ‘&’
String “amos”, “abdulganiu”

 Constant Declaration
the syntax for declaring constant are:
 using the const keyword
e.g. const float height=1.92;
 using the #define preprocessor
e.g. #define height 1.92
 Control structures

 Selection statements
 If
 If-else
 else if
 switch

 Repetition statements
 while
 do-while
 for
 Selection statement
 If statement
if (expr) stmt
e.g.
if(age >=18) status = “Adult”;

 If-else statement
If(expr) stmt_1
else stmt_2
e.g.
if(age>=18) status = “Adult”;
else status=“Teenager”;
 Nexted if
 switch statement - char, int and enum,

switch(expr){
case val_1: stmt_1
break;
case val_2: stmt_2
break;
.
.
.
case val_n: stmt_n
break;
[default: default_stmt]
}
E.g.
int weekDay =5;
switch(weekDay){
case 1: cout<<“Sunday”;
break;
case 2: cout<<“Monday”;
break;
case 3: cout<<“Tuesday”;
break;
case 4: cout<<“Wednesday”;
break;
case 5: cout<< “Thursday”;
break;
case 6: cout<<“Friday”;
break;
case 7: cout<<“Saturday”;
break;
default: cout<<“Wrong day number”;
}
 Iteration statement
 while
while(expr)
stmt
e.g.

Short i=1;
While(i<6){
cout<<“This is iteration %d“<<i;
i=i+1;
}
 Iteration statement
 do - while
do{
stmts
}while(expr);

e.g.

int i=1;
do{
cout“This is iteration %d“<<i;
i=i+1;
}While(i<6);
 Iteration statement
 for
for ([initialization]; [termination]; [increment/decrement]){ statement(s)
}
e.g.

for(Short i=1;i<6;i++)
cout<<“This is iteration %“<<i;
 Other control statement
 break
int x=1;
while(x<10){
if(x==8)break;
cout<<“X = “<<x;
x++;
}
 continue
int x=1;
while(x<10){
if(x==8){x++;continue;}
cout<<“X = “<<x;
x++;
}
 BASIC C++ Input and Output

 Input : cin and the extraction operator, >>


E.g.: cin>>x
This will cause the program to read from in computer
screen and assign the value to x

 Output : cout and the insertion operator, <<


E.g.: cout<<x;
This will display the value of x on the Computer
screen
Functions
 What is a Function

 A C/C++ function is a subprogram designated to


carry out a specific task among the other tasks of a
program

 When a programming problem is broken down into


sub-problems that are more manageable, the
solution to each of the sub-problems can be written
as a function.,
 Function Definition

 C/C++ function contains two parts: function header


and function bosy. It can be defined using the
following general form:

returnType functionName (list of para){

function body

}
Function Definition
where:
 returnType : is the data type of the value the
function is expected to return;
 functionName is an identifier for referencing the
function;
 list of para: is the declaration of one or more
variables separated by commas to represent the
value(s) that will be passed to the function. These
variables are referred to as formal parameters; and
 function body is the line(s) of statements that will
perform the task designated to the function.
 Function Definition
Example:
 the main( ) function that we’ve defined so far in our
codes.
int main(){
int age=10;
if(age<=18)
cout<<"\nA Teenager";
else
cout<<"\nAn Adult";
return 0;
}
 Function Definition

The return statement: the return statement in a function


is used to return value to the caller of the function. It
performs two tasks:

 terminates the execution of the function, and

 returns value and control to the point where is was


called in the program
 Function call/Invocation

 A function must be called or invoked to perform its


designated task. The genral call format is:

functionName (list of actual parameters)


Examples:
greet();
The following is a call to a function named greet that
has no parameter.
avg(x[]);
This is a call to a function named avg and an array is
passed to it.
 Passing Arguments to Function:

 Pass by Value: in this call, the value(s) of the actual


parameters are copied into the formal parameters.
Thus, any change made to the formal parameter
within the function does not reflect on the actual
parameters. This is the default form of parameter
passing.
Function header:
float add_up(float x, float y, float z)

Function call:
add_up(x,y,z);
 Passing Arguments to Function:
 Pass by Reference: in this call, the reference
(address) of the actual parameters are copied into
the formal parameters. Thus, any change made to
the formal parameter within the function will reflect
on the actual parameters because they are directly
accessed
 By reference

Function header:
float add_up(float &x, float &y, float &z)

Function call:
add_up(x,y,z);
 Passing Arguments to Function:

 Pass by Reference:
 By pointer
Function header:
float add_up(float *x, float *y, float *z)

Function call:
add_up(&x,&y,&z);
 Function declaration / Prototype:
 It is simply the function header terminated with a
semi colon (;)

 Example
Function header:
float add_up(float *x, float *y, float *z);
Or
float add_up(float, float, float);

It is useful in situation where function calls come


before the function is defined
 The Standard Function Library
The standard function library is divided into the
following categories −
 I/O: <iostream> https://www.programiz.com/cpp-
programming/library-function/iostream
 String and character handling: <cstring> https://
www.programiz.com/cpp-programming/library-
function/cstring
<cctype>: https://www.programiz.com/cpp-
programming/library-function/cctype
 Mathematical: <cmath> https://www.programiz.
com/cpp-programming/library-function/cmath

You might also like