Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Programming Amon

Download as pdf or txt
Download as pdf or txt
You are on page 1of 24

Programming

Function: is collection of statements when executed it


accomplishes something it can be predefined or standard.

Syntax: rules to tell a statement is legal.

Semantic rule: the meaning of the instruction, no error it just


means the program is working but not in correct way.

Reserved words:

✓ int ✓ void ✓ string ✓ bool ✓ break


✓ const ✓ return ✓ if ✓ true ✓ default
✓ float ✓ else ✓ false ✓ while
✓ double ✓ char ✓ switch ✓ case ✓ for
✓ void
in C++ identifiers or variables can only have (Numbers,
letters, $, _) must not begin with number!

Data type: each value has a data type for example:

✓ Integer (true number) int


✓ Float-double (number with decimal place) float 7decimal
place, double 15 decimal place
✓ Character (any single letter only one!) char ‘ A ‘ -128 , 127
✓ string (sequence of characters car ) string “ amna”
car length is 3 c position is 0 , empty string called null
✓ bool ( values of true or false )bool
To declare a constant variable:

const - data type – variable name = (the value)

declare value means it exist, initializing gives it value

Cout and Cin are predefined identifiers (may be redefined)

✓ Cin Input read statement used to gather input


Cin>>miles cause computer to get a value of type
integer 70 miles
✓ Cout output statement used to print something Cout<<”
hello” will show in screen the word hello

Manipulator alters output

endl \n causes to move the begging of next line

\t tab moves to next tap stop (space)

\b backspace moves one step to the left and replace


whatever there (salary\b) salar

\r return ‫يرجع اول سطر ويكمل الي فالجملة والي انحذف ما يرجع‬

\\ backslash print \

\’ single otation ‘ is printed

\” double quotation “ is printed


Arithmetic operations

Order:
all operation inside () evaluated first

* / % are in the same level evaluated from left to right

+ - are in the same level they come last evaluated left to right

Integral expression ( 2+3/5)= int

Floating point expression (12.8*7.5-34.60)float

Mixed expression (2/2.5+5) float

// only one line comment

/* multiple lines comments */

Count=count+1 Increment the value


Count++ = ++ count count by 1

Count-- = -- count Decrement the value count by 1

X=5 and y=++X ++X is evaluated first pre increment

First x value will change to 6 then y will equal x to both 6

X=5 and y=x++ X++ is evaluated last post increment

First y equal 5 then x will change to 6 so x=6 and y=5


Compound assignment : x*=y+2
x= x* ( y+2 )
(x=x*y ) is the same as (x*=y)

(value=-expression) is the same as(value=value–expression )

Type conversation:

Use static_cast to convert from data types

value=static_cast<data type to be converted into>(value)

from char to int include a data type in and then convert

using mathematical function: First convert data type then


Do all the other operation
#include<cmath>

Square root = sqrt(x)

Power = pow(x,2) 𝑥 2

Absolute value = fabs(x)

Trigonometric function = sin(theta) cos(theta ) in radius

Each code starts with #include<iostream>


using namespace std;
int main()
{
return 0;
}
selection

control structures:

sequence , selectively(making choice),repetitively(looping)

statements are executed only if certain conditions met


boolean expression condition is represented by it can be true
or false Syntax:
if( logical expression )

if selection (one way, two way )


{
relational operator
statement;
statements are executed only if }

evaluated to true Else


{
statement;
relational operation:
}

== equal != not equal

< less than > bigger than

<= less than or equal >= bigger than or equal

Any non-zero is true Zero is false

Compound statement: block of statement considered as


single statement
Nesting: one control statement in another else is associated
with if if()

else if ()

comparing string types: relational operation can be used in


string, the comparing start from first char and continues until
a mismatch is found or all char equal

if 2 string in different length and both ended in same char of


short one then the short string is less

example: (what comes first is the smaller , capital is smaller)

string1: Hello String1 < string2 true

string2: Hi String1 > Hen false


String3 < an true
string3: air String1 == hello false
String3 <= string4 true
string4: Bill
Amna<amna true
logical boolean operation

! not reverse the value (true become false )

&& and both conditions must be true

|| or one of the conditions must be true

if ( 60<avg<=65) X True = 1 false=0


if( ( 60<avg ) && ( avg<=65 )) ✓
Precedence of operator

Evaluated from left to right (logical and relational operation)

Parentheses can override precedence

first ! ++ -- (unary operator)

second */%

third + -

fourth > < <= >=

fifth == !=

sixth &&

seventh ||

last =

conditional operator (?:) Syntax:

example: Expression1 ? expression2 : expression3

max=( a>= b)? a : b True value

if a is bigger than or equal to be max False value


value will be a
if the expression is false the max value
will be b
switch structures (alternative to if statement )

When value match the case Syntax:


switch ( expression )
the statements are executed
{
until reach a break, braces are case 1:

not needed , default is executed statement;


break;
always
}

the assert function:

#include <cassert> Syntax:


Assert ( expression );
if true the statement
Statement;
is executed

to calculate % in calculator ( A%B )

1. Mode base-in
2. A - A ÷ b x b

char values for numbers can be from ( -128 to 127 )

and letters ( 0 to 255 )


Loops
while loop structured Syntax:
while ( expression )
statement continues to
{
execute until the expression statement;

is no longer true }

Syntax:
counter controlled while loop
int counter=0;
When do you know exactly how while ( counter<(limit-1) )
{
many iteration loops should
statement;
execute we called it counter control }

Syntax:
sentinel controlled while loop
int sentinel=-999;
we use it when we want to stop while (number!=sentinel)
{
at certain value
statement;
}
Syntax:
flag controlled while loop while ( !found )
{
use boolean variable to control
if( condition )
the loop (bool found=false) found=true;
}

the do while loop structured Syntax:


do
used to check something after
statement;
an action happens first do while ( condition );

statement will be executed once {


statement;
then if the condition of while is
}
it true it will execute do statement again and again until the
statement of white is false the statement inside the wild will
be executed
for loop structured Syntax:
for ( initial statement ; loop condition ; update loop )
example:
statement;
for(counter=0 ; counter<4 ; counter ++)

we can remove initial statement and declare it up we will


always assume it’s true , we can remove the condition and put
if statement instead , we can remove the update and put ++
statement in the loop body.

#include <cmath>

floor ( nearest double, keep it ) 9.6 9.0

21.1 21

ceil ( nearest double , round it ) 9.6 10

21.1 22

#include<cctype>

toupper(a) = A

tolower(A) = a

isupper(N)= true if uppercase

islower(e)= true if lowercase


random numbers #include<cstdlib> #include<ctime>

srand( time ( 0 ) );

cout<<rand();
always gives you a different value
cout<<rand()%100
will give you random numbers from 0 to 99
cout<<rand()%100+1
will give you random numbers from 1 to 99
cout<<rand()%(max-min+1)+min
for certain period from min to max use this formula

to have the right digit of number (268)

268%10=8 third digit

268/10=26

26%10=6 second digit

26/10=2 first digit


Input output
#include < iostream >

To use cin and cout

>> input stream extraction operator

<< output stream operator

Stream: sequence of character from source to destination

Input stream: sequence of character from an input device to


computer

Output stream: sequence of character from the computer to


an output device

#include <iomanip>

setprecision( n ) output the number with n decimal places

fixed output in fixed notation without e-13

showpoint force output to show decimal point and trailing


zero

cout<<showpoint<<fixed<<setprecision(2); 3.14

setw( n ) used to reverse spaces either left or right


Open file for output

#include< fstream >

Declare file stream variables

ofstream read; input variable

read.open(“ file name “); open file

read.close(); Close file

open a file for the input

ifstream read;

read.open(“ file name “)

read.close();

Arrays
Array collection of fixed number of components having same
data type and there is one , two-dimensional array

Simple data type variable can store only one value

Structured data type each data item can store a collection of


data items Syntax:

Accessing array components Data type array name [ size ]


* Size always positive
[ ] is the array subscripting operator

Size is the index; it specifies the position of component in


array

Index always start from 0 so for array[ 50 ] array index is


from 0 to 49 ( position )

int list [ 10 ]; index is only between 0,1,2,3,4,5,6,7,8,9

C++ doesn’t check if index written is within the range or not

Size of array is needed it can’t be empty,

if size is taken from user, then it will be

during execution time

to find the sum of array component

use for loop , starting from index 0 till index ( size-1 ) and
initialize sum=0 and add array[ i ] to the sum inside the loop,
print the sum outside the loop.
to output the array in reverse order

use for loop, start from last index which is ( size-1 ) and the
update condition it decrement – inside the for loop output
the index value.

In array initialization size is not important

double array[ ]={ 12.5, 23.4 , 16.90 , 23 } initializer list

4 components so the size is 4 initial values

Int list[ 10 ]={ 0 } array size is 10 and all components are 0

Int list[ 10 ]={ 8,5,12 } array size 10 and first 3 index are
initialized, and the rest are zero

8 5 12 0 0 0 0 0 0 0

Copying array to another one should be done with loop

For ( int i=0; i<size ; i++)

Array1[ i ] = Array2[ i ]

C string ( character arrays )

String sequence of zero or more character enclosed in “ “

\0 is the last char in string it’s the null character


Hello, contain 5 letter and \0 is considered as 1 letter

( Requires 6 memory location of type char )

“ A “ 2 memory cells

‘ A ‘ 1 memory cell

Char array[ 16 ]

Because string end with null the largest string letters allowed
is 15

Char name[ ]=” saad “; declare an array of size 5

Saad 4 letter + 1 for the null = 5

#include < cstring >

strcpy( s1, s2 ) copy string s2 to s1

strlen( s ) returns the length of the array excluding the null


character.

strcmp( s1 , s2 ) used to compare

( s1<s2 ) negative ( s1>s2 ) positive ( s1=s2 ) zero

Taking input for string char name[ 20 ]

Cin>>name ( strings without blanks )


Cin.get( name,31 ) store the next 30 characters with blanks

To output the string in the char array use

Cout<<name

Two-dimensional array

1d array is data organized as list

2d array is data organized as table Syntax:


Data type array name [ index1 ][ index2 ]
For example :
Index1 for rows number
int sale [ 5 ] [ 4 ] rows from 0 to 4 Index2
columns from 0 number
for column to 3

Initialize 2d array :

Double sale [ ][ ]={ { 2,3,4 },{ 5,8,6 } } 2 rows and 3 columns

2 rows {} {} each row written using {} and separated by


comma the column values are inside the row also separated
by comma.

Making whole row zero or whole column to zero

Set row constant and do a loop where the column increase

To make a whole 2d array component to values of zero


Start with 2 loops having 0 row and 0 columns
array[row][col]=0

To find the largest element in array

Declare an integer max value and set it equal to [0][0] value


then set an if statement to check for bigger value let it be the
max

To output each row component alone

use normal row col loop but at the end of the row loop used
endl so you can go to the next line then start a new row

for inputting the values of a 2d array

use normal row col loop then use

cin>>matrix[row][col] one row at a time

2d array diagonal when row and col are


-- -- --
equal(row==col)
-- -- --
Upper diagonal when col higher than
-- -- --
row(col>row)

Lower diagonal when row higher than col(row>col)


functions
functions called modules like miniature programs; it can be
put together to form a larger program

pre-defined functions

pow function has 2 parameters pow( x , 2 )= x2

x and 2 called parameters

sqrt function has 1 parameter sqrt(2.25)=1.5

floor function has 1 parameter floor(48.9)=48.

user defined functions( written by programmer )


function prototype or declaration should be done before the
main function if we put function before main prototype is not
needed .

in the function call ( actual parameters ) Must match


the same
number of
in the function definition ( formal parameters ) parameter and
data type
inside the function header there is the function body

function prototype is the function heading without body

you need to include the parameter data type without


variables Syntax:
Function type function name ( formal parameter )

Data type of returned {


value
Statements
}

execution always begins at first statement in the main


function other function executed only when they are called

when a return statement executed it replace the function call


with the returned value, the return in main terminates the
whole program
void function

value-returning function any function that returns value

void function doesn’t have a Syntax:


Void function name ( parameter )
return statement with data
Value parameter ^
type void. Receive a copy from actual parameter

Value parameter Values that enter function don’t get


affected

Reference parameter Receive the actual parameter

& Reference sign original value changes in any function

Global identifiers variables declared outside main and other


function static variables

Local identifiers variables declared inside any function

scope resolution operator : : we use it to refer to global


variable

static data type the value of it keep updating to the newest

arrays are always passed by reference there is no need for &


void arrayfunction (int list[ ] )

void 2darraytest(int list [ ][ 4 ]) column must be specified!!

In the main to call a function with array parameter

Use the name of array to be replaced in the function

Arrayfunction(list ) for both 2 or 1 dimension array

Pointers and dynamic variables

Pointer memory address of variable

Double *p; P is declared a pointer to double variable


Syntax to declare a pointer :
& operator address of
Data type * pointer name
p1=&v1 means p1 equal the address of v1 Example = int * p

two ways to refer to v1 :

Cout<<v1;
Cout<<*p1;

* Dereference operator gets the data the pointer is pointing


to

p1=p2

*p1=*p2
P1 is pointing the same

As where p2 is pointing

They will have same value

P1=new int assign a new nameless variable and p1 points to


it Access it by *p1

P1=new int[ 3 ] let p1 points to new array list of size 3

P1=p1+1; is pointing to second component


P[0]
P1=p1+2; is pointing to third component
P[1]

P[2]

You might also like