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

Fundamentals of Programming-2

C/C++ Files, Structures,Dynamic arrays. Calloc() malloc(). This pdf file includes all C/C++ course for second semester.

Uploaded by

thekonan726
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
259 views

Fundamentals of Programming-2

C/C++ Files, Structures,Dynamic arrays. Calloc() malloc(). This pdf file includes all C/C++ course for second semester.

Uploaded by

thekonan726
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Fundamentals of programming - 2

1. C/C++ Memory management


In C++ pointer is a variable that used to store the memory address
of the other variables. It is a variable that points to a data type (like
int or string) of the same type and is created with the * operator.

Syntax of pointer in c++:


data_type_of_pointer * name_of_variable =& normal_variable;

When we de ne a pointer to a pointer, the rst pointer is used to


store the address of the variables, and the second one stores the
address of the rst pointer. We call it double pointer or pointer to
pointer.

Declaring a pointer to pointer is similar to declaring a pointer in


c++. The di erence is, we have to use an additional * operator
before the name of the pointer.

Syntax of double pointer in c++:


data_type_of_pointer ** name_of_variable =& normal_pointer_variable;

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

In C++ double pointer behave similarly to a normal pointer, so the size


of a variable of a double pointer and the size of a variable of a normal
pointer is always equal. The size of a pointer is not xed, and it
depends on other factors like CPU, and OS. Usually, for 64-bit
operating system a size of 8 bytes memory and for 32-bit operating
system a size of 4 bytes memory is assigned.

#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;
}

Memory layout of c/c++ programs


A typical memory
representation of a C
program consists of the
following sections:
1.Text segment
2.Initialized data segment
3.Uninitialized data
segment (bss)
4.Stack
5.Heap

BSS - Block Starting Symbol


A computer program memory can be categorizes into two sections:
read only and read/write. The code segment also known as text
segment, contains executable code and is generally read only and
xed size.

The data segment contains initialized static variables or global


variables and local static variables, which have a de ned value and
can be modi ed.

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.

In C/C++ for dynamic memory allocation following functions are used:


1. malloc( ) memory allocation a.cpp
2. calloc( ) contiguous allocation a.c
3. free( ) a.obj
4. realloc( ) a.exe

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.

Syntax: ptr = (data_type*)malloc(byte_size);


Example: ptr = (int*)malloc(100*sizeof(int));

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”.

Syntax: ptr = (data_type*)calloc(n, element_size);


Example: ptr = (int*)calloc(25, sizeof( oat));

This statement allocates contiguous space in memory for 25


elements, each with the size of oat. If space is insu cient,
allocation fails and returns a NULL pointer.

#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.

Syntax for de ning a function:


return_type function_name (parameter_list) {
body of the function
}

A function de nition in C consists of function header and a function


body. Here are all parts of the function:
1. Return type - a function may return a value. The return_type is
the data type of the value that function returns. Some functions
fi
fi
fi
fi
fi
fi
fi
fi
perform the desired operations without returning a value, in this
case, the return_type is keyword void.
2. Function name - is the actual name of the function, the
function name and the parameter list together constitute the
function signature.
3. Parameter - a parameter is like a placeholder. When a function
is invoked, you pass a value to the parameter. The parameter list
refers to the type, order and the number of the parameters of a
function. Parameters are optional; for example function may not
have a parameter.
4. Function body - function body contains a collection of
statements that de ne what function does.

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:

• If a function has to use arguments, it must declare variables that


accept the values of the arguments. These variables are called
the formal parameters of the function.
• Formal parameters behave like other local variables inside the
function and are created upon entry into the function and
destroyed upon exit.
• Di erent memory is allocated for both actual and formal
parameters.
• Actual parameter is the argument which is used in function call.
• Formal parameter is the argument which is used in function
de nition.
• While calling a function, there are two ways in which arguments,
can be passed to a function: call by value and call by reference.
• Call by value method copies the actual value an argument into
the formal parameter inside the function have no e ect on the
argument.
1. Passing an argument by value:
#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;
}

• Call by reference method copies the address of an argument into


the formal parameter. Inside the function, the address is used to
access the actual argument used in the call. This means that
changes made to the parameter a ect the argument.
2. Passing an argument by reference:
#include <iostream>
using namespace std;
int incr(int&m){
m = m + 1;
ff
fi
ff
ff
return m;
}
int main (){
int n=5;
cout << "n= " << incr(n)<< endl;
cout << "n= " << n << endl;
return 0;
}

3. Passing a pointer as a function argument.

#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;
}

4. Array transfer: explicit size speci cation

#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.

A recursive function consists of two cases: base case and


recursive case.

The recursive case de nes the problem in terms of smaller problem


of the same type. This case includes a recursive function call.
There can be one or more recursive case.

f(n) = f(n-1) * n - this is called recursive case. We continue recursive


process till n=0, when 0!=1 - this is called 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:

1. Direct - when a function calls itself


2. Indirect - function A calls function B, and function B calls
function A, or more elements which call A at the end.

Disadvantages of recursion:

It is slower than non-recursive programs, because recursive


functions needs to store the previous function call addresses for
the correct program jump to take place.

Requires more memory to store, because recursive program


require the allocation of a new stack frame and each state needs to
be placed into the stack frame, unlike non-recursive (iterative)
programs.
fi
1. Function for calculating factorial of number using recursion.
#include <iostream>
using namespace std;
int factorial(int n){
if (n==1) return 1;
else return n*factorial(n-1);
}
int main (){
int n;
cout << "Enter n= ";
cin >> n;
cout << "n!= " << factorial(n)<< endl;
return 0;
}

The natural de nition of some problems leads to recursive function,


for example bonacci numbers.
Recursive solution of bonacci numbers: b(n) = b(n-1) + b(n-2)
Base case: n <=0, n==1

Syntax:
int n(int n) {
if (n<=0) return 0;
else if (n==1) return 1;
else return b(n-1) + b(n-2);
}

2. Program to implement a recursive function to get the n bonacci


number.

#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;
}

3. Program to implement recursive function to calculate the sum of


digits of a given number.
#include <iostream>
using namespace std;
int sumOfDigits(int number){
if (number>=0 && number <=9) return number;
return (number % 10) + sumOfDigits(number/10);
}
/* Recursive case calculates the same of the last digut and the sum
the rest of the digits*/
int main() {
int n;
cout << "Input a number: ";
cin >> n;
int sum_digits = sumOfDigits(n);
cout << " Sum of Digits " << n << "is: " << sum_digits << endl;
return 0;
}
5. Function overloading in C++

Function overloading is a feature in C++, where two or more


functions can have the same name but di erent parameters.
Function overloading can be considered as an example of
polymorphism feature in C++.

1. Program that demonstrates function overloading.


#include <iostream>
using namespace std;
//1:
void showArgs(double x) {
cout << "Double number: " << x << endl;
}
//2:
void showArgs(double x, double y) {
cout << "Double numbers: " << x << "and" << y << endl;
fi
fi
ff
fi
}
//3:
void showArgs(char s) {
cout << "Symbol: " << s << endl;
}
//4:
int showArgs (int n){
return n;
}
int main () {
int n=3;
double x=2.5, y=5.1;
char s = 'w';
//1:
showArgs(x);
//2:
showArgs(x,y);
//3:
showArgs(s);
//4:
cout << "Int-number " << showArgs(n) << endl;
return 0;
}

2. Overloaded function for nding the sum of two integer numbers,


three integers and two real numbers.

#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;
}

In this example, the function its overloaded. The function cannot


return on array. The original matrix (two-dimensional) is passed as
the rst argument of the trans( ) function.
The function does not return a value. If there are no more
arguments, changes are made to this matrix. If the function has
another argument, (a two-dimensional array of the same size as the
rst) the result of the transpose is written to the second matrix.

3. Program for nding transpose of the matrix.

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;
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy