Fundamentals of Programming-2
Fundamentals of Programming-2
Example:
int val =169
int*ptr =&val; // storing address of val to a pointer ptr
int**double_ptr =&ptr; // pointer to pointer declared which is pointing
to an integer
#include <iostream>
using namespace std;
int main () {
int n, *p, **q;
p=&n;
ff
fi
fi
fi
fi
q=&p;
n=100;
(*p)+=5;
(**q)--;
cout << n << "\n";
cout << *p << "\n";
cout << **q << "\n";
cout << p << "\n";
cout << q << "\n";
return 0;
}
Example in C:
int i=3;
char a[ ] = “Hello World”;
fi
fi
fi
The values of these variables are initially stored within read-only
memory(typically with the code segment) and are copied into the
data segment during the start-up routine of the program.
C malloc( ) method
“malloc” or “memory allocation” in C used to dynamically allocate
a single large block of memory with the speci ed size. It returns a
pointer of type void which can be cast into a pointer of any form. It
initializes each block with default garbage value.
Since the size of int is 4 bytes, this statement will allocate 400
bytes of memory, and the pointer ptr holds the address of the rst
byte in the allocated memory.
#include <iostream>
#include <stdlib.h>
using namespace std;
int main () {
// This pointer will hold the base address of the created block
int*ptr;
int n,l,i;
// Get the number of the elements for the array
n= 5;
cout << "Enter the number of elemets:";
// Dynamically allocate memory using malloc ()
ptr = (int*)malloc(n*sizeof(int));
// Check if the memory has been succesfully allocated
if (ptr== NULL) {
cout << "Memory not allocated.\n";
exit (0);
fi
fi
}
else {
// Memory has been succesfully allocated
cout << "Succesfullly allocated using malloc.\n";
// Get the elements of the array
for (i=0;i<n;++i){
ptr[i]= i + 1;
}
//Print the elements of the array
cout << "The elements of the array are:";
for (i=0; i<n; ++i){
cout << ptr[i];
}
}
return 0;
}
C calloc( ) method
“calloc” or “contiguous allocation” method in C is used to
dynamically allocate the speci ed number of blocks of memory of
the speci ed type. It initialize each block with a default value “0”.
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
int *arr;
int n = 5;
// Allocating memory for n integers using calloc
arr = (int*)calloc(n, sizeof(int));
if (arr == nullptr) {
cout << "Memory allocation failed!" << endl;
return 1; // Returning 1 to indicate failure
}
// Initialize elements to some value
for (int i = 0; i < n; i++) {
arr[i] = i * 2;
fi
fi
fl
fl
ffi
}
// Displaying the elements of the array
cout << "The elements of the array are:" << endl;
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
// Freeing the allocated memory
free(arr);
return 0;
}
2. Functions in C/C++
Function - is a group of statements that together perform a task.
Every C++ program, has at least one function, which is main( ), and
all the most trivial programs can de ne additional functions. It is
possible to divide up the code into separate functions. A function
declaration tells the compiler about a function’s name, return type
and parameters.
Types of functions:
1. Prede ned standard library functions, such as puts( ), gets( ),
printf( ), scanf( ). These are the functions which already have a
de nition in header les( .h les, like stdio.h), so we just call the,
whenever we want.
2. User de ned functions - the functions which we can create by
ourselves, for example we create function bc( ) and call it in mai( )
in order to use it.
Example:
1. The source code of max( ):
int max( int a, int b){
if (a>b) return a;
else return b;
}
2. Function max( ) can be written using ternary operation:
int max( int a, int b){
return (a>b)? a:b;
}
3. Function sqrt( ) returns square of a number:
int sqrt( int n ) {
return n*n;
}
4. Program code with function for calculating the sum of natural
numbers.
#include <iostream>
#include <cstdlib>
using namespace std;
int msum(int n) {
int s=0;
for (int i=1; i<=n; i++) s+=i;
return s;
}
int main (){
int n;
cout << "Enter n=";
fi
cin >> n;
cout << "Sum is " << msum(n) << "\n";
return n;
}
5. Here is the same program, but here function does nor return a
result.
#include <iostream>
using namespace std;
void msum2() {
int n;
cout << "Enter n= ";
cin >> n;
int s=0;
for (int i=1; i<=n; i++) s+=i;
cout << "Sum is " << s << "\n";
}
int main (){
msum2 ();
return 0;
}
6. This program nds 1/n and here the function is declared at the
end of the program.
#include <iostream>
using namespace std;
void InvFunc(double z);
int main (){
double s;
cout << "Enter number ";
cin >>s;
InvFunc(s);
return 0;
}
void InvFunc(double z){
if (z==0){
cout << "Divison by zaero!" << endl;
return;
}
double x;
x=1/z;
cout << "1/z = " << x << endl;
}
fi
Function arguments:
#include <iostream>
using namespace std;
int incr(int*m){
*m = *m + 1;
return *m;
}
int main (){
int n=5;
cout << "n= " << incr(&n)<< endl;
cout << "n= " << n << endl;
return 0;
}
#include <iostream>
using namespace std;
void show (int n[5]){
for (int i=0;i<5;i++)
cout << "n["<< i << "] = " << n[i]<< endl;
}
int main (){
int n[5]= {1,2,3,4,5};
show(n);
return 0;
}
5. Passing array argument. (size is not speci ed, implicit)
#include <iostream>
using namespace std;
void show (int n[ ]){
for (int i=0;i<5;i++)
cout << "n["<< i << "] = " << n[i]<< endl;
}
int main (){
int n[5]= {1,2,3,4,5};
fi
fi
show(n);
return 0;
6. Passing an array as a pointer.
#include <iostream>
using namespace std;
void show (int *n, int m){
for (int i=0;i<m;i++)
cout << "n["<< i << "] = " << n[i]<< endl;
}
int main (){
int n[5]= {1,2,3,4,5};
show(n, 5);
show(n, 3);
return 0;
}
7. Passing 2D array.
#include <iostream>
using namespace std;
void show2(int n[][3], int size) {
for (int i = 0; i < size; i++) {
for (int j = 0; j < 3; j++) {
cout << n[i][j] << " ";
}
cout << endl;
}
}
int main() {
int n[][3] = {{1, 2, 3},
{4, 5, 6}};
show2(n, 2);
return 0;
}
8. The function returns a pointer as a value.
#include <iostream>
using namespace std;
int *mpoint(int&n, int&m){
if (n>m) return &n;
else return &m;
}
int main (){
int n=3, m=5;
int *p;
p = mpoint(n,m);
(*p)++;
cout << "n= " << n << endl;
cout << "m= " << m << endl;
return 0;
}
3. Recursion
The recursive function is a function that calls itself. It is also a part
of a cycle in the sequence of function calls. The equality 0!=1 or
f(0)=1 is called simple case, terminating case or base case.
Syntax:
int fact(int n) {
If (n==0) return 1;
return fact(n-1) * n;
}
In order to calculate n! we simply call a function: fact(n)
Types of recursion:
Disadvantages of recursion:
Syntax:
int n(int n) {
if (n<=0) return 0;
else if (n==1) return 1;
else return b(n-1) + b(n-2);
}
#include <iostream>
using namespace std;
int bonacci(int n){
// Initial bonacci 0 is 0, bonacci 1 is 1.
if (n==0) return 0;
else if (n==1) return 1;
else return bonacci(n-1)+ bonacci(n-2);
}
int main (){
int n;
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
cout << "Input the number ";
cin >> n;
int b_num = bonacci(n);
cout << "The" << n << "Fibonacci number is:" << b_num << endl;
return 0;
}
#include <iostream>
using namespace std;
int sum(int a, int b){
return a + b;
}
int sum(int a, int b, int c){
return a + b + c;
}
oat sum( oat a, oat b){
return a + b;
}
int main() {
int m, k, l;
oat p, q;
cout << "m= ";
cin >> m;
cout << "k= ";
cin >> k;
cout << "l= ";
cin >> l;
fl
fl
fl
fl
fi
cout << "p= ";
cin >> p;
cout << "q= ";
cin >> q;
cout << "m+k= " << sum(m, k) << endl;
cout << "l+k= " << sum(l, k) << endl;
cout << "m+k+l= " << sum(m, k, l) << endl;
cout << "p+q= " << sum(p, q) << endl;
return 0;
}
include <iostream>
#include <cstdlib>
using namespace std;
// Matrix size
const int N = 3;
void trans (double A[N][N], double B[N][N]){
int i,j;
for (i=0; i<N; i++)
for (j=0; j<N; j++)
B[i][j] = A[j][i];
}
void trans (double A[N][N]){
int i,j;
double s;
for (i=0; i<N; i++)
for (j=i+1 ; j<N; j++){
s = A[i][j];
A[i][j] = A[j][i];
A[j][i] = s;
}
fi
fi
fi
}
// Filing a matrix with random numbers:
void ll (double A[N][N]){
int i,j;
for (i=0; i<N; i++)
for (j=0; j<N; j++)
A[i][j] = rand() % 10;
}
// Displaying the matrix on the screen:
void show (double A[N][N]){
int i,j;
for (i=0; i<N; i++){
for (j=0; j<N; j++)
cout << A[i][j] << " ";
cout << endl;
}
}
int main () {
double A[N][N], B[N][N];
cout << "Initial matrix: \n";
ll (A);
show (A);
cout << "After the transform: \n";
trans (A,B);
// Result:
show (B);
cout << "Initial matrix: \n";
// Fillling an array:
ll (A);
// Result:
show (A);
cout << "After transform: \n";
trans (A);
show (A);
return N;
}
6. Structures
• A structure is a collection of related data items, possibly of
di erent types. A structure type in C++ is called struct.
• Struct - is heterogeneous, that’s way it can be composed of
data di erent types. However, array is homogeneous since it can
contain only data of the same type.
ff
fi
fi
fi
ff
• Structures hold data that belongs together. In database
application, structures are called records.
• Individual components of a struct are called members or elds.
Members can be di erent types: simple, array or struct.
• A struct is named as a whole while individual members are
named using eld identi ers.
• Complex data structures can be formed by de ning arrays of
structs.
Struct syntax:
struct<struct_type> {
<type><identi er_list>;
<type><identi er_list>;
……
};
Each identi er de nes a member of structure.
1. Example: Listing
#include <iostream>
#include <cstring>
using namespace std;
struct Marks {
char name[80];
int phys;
int chem;
int math;
} aliyev, valiyev, piriyev;
struct Exams {
double phys;
int chem;
int math;
};
int main (){
strcpy (aliyev.name, "Ali Aliyev");
aliyev.phys = 4;
aliyev.chem = 3;
aliyev.math = 3;
strcpy (valiyev.name, "Vali Valiyev");
fi
fi
fi
ff
fi
fi
fi
fi
fi
valiyev.phys = 5;
valiyev.chem = 4;
valiyev.math = 4;
strcpy (piriyev.name, "Piri Piriyev");
piriyev.phys = 5;
piriyev.chem = 4;
piriyev.math = 3;
Exams LastYear, ThisYear;
LastYear.phys = 4.33333;
LastYear.chem = 3.66667;
LastYear.math = 3.33333;
ThisYear.chem = (double)(aliyev.chem + valiyev.chem + piriyev.chem)/3;
ThisYear.phys = (double)(aliyev.phys + valiyev.phys + piriyev.phys)/3;
ThisYear.math = (double)(aliyev.math + valiyev.math + piriyev.math)/3;
cout << "Last year marks: " << endl;
cout << "Physics: " << LastYear.phys << endl;
cout << "Chemistry: " << LastYear.chem << endl;
cout << "Mathematics: " << LastYear.math << endl;
cout << endl;
cout << "This year marks: " << endl;
cout << "Physics: " << ThisYear.phys << endl;
cout << "Chemistry: " << ThisYear.chem << endl;
cout << "Mathematics: " << ThisYear.math << endl;
return 0;
}