In this tutorial we will discuss on Default Argument, Alias Variable, Array, Pointer and Strings in C++(CPP).
Default Arguments
The default arguments are used whenever the programmer provides no arguments or only few arguments while calling a function.
The default arguments are used during compilation of program. For example, let's say you have a user-defined function simpleinterest() declared like this:
float simpleinterest(float p=100, float t=1, float r=10);
Now while calling this function if you do not provide any arguments, and simply call
simpleinterest();
then in this case the result would be 10, compiler used the default values of 100, 1 and 10 declared in function signature/prototype. If you pass only one argument like this:
simpleinterest(200) ;
then the result would be 20, using the passed argument 200 as first value and 1 and 10 taken from the default argument. The point is when we have default argument but provide different value in the function call, the default value of the argument will be overridden by the value(s) being passed.
For example:
simpleinterest(200,2,15);
In this case the value of p, t and r will be overridden by 200, 2, and 15 respectively and the function will return .
One simple rule in assigning default arguments is that the default arguments must be declared from right to left.
For example:
float simpleinterest(float p, float t, float r=10); //valid float
simpleinterest(float p, float t=1, float r=10); //valid
float simpleinterest(float p=100, float t=1, float r=10); //valid
float simpleinterest(float p=100, float t, float r=10); //invalid
float simpleinterest(float p=100, float t, float r); //invalid
float simpleinterest(float p, float t=1, float r); //invalid
WAP in CPP to calculate simple interest using the concept of default arguments.
#include<iostream>
using namespace std;
float simpleinterest(float p=100, float t=1, float r = 10)
{ return (p*t*r)/100;
}
int main()
{
cout<<"Simple interest with default values"<<endl;
cout<<simpleinterest()<<endl;
cout<<"Simple interest with p=200,t=1 and r=10"<<endl;
cout<<simpleinterest(200)<<endl;
cout<<"Simple interest with p=200,t=2 and r=15"<<endl;
cout<<simpleinterest(200,2,15)<<endl;
return 0;
}
Pass by Reference
→ It is a method of function call in which the memory address of the actual arguments is passed to the called function from calling function.
→ The memory location of actual arguments listed in the function call are copied into the list of formal argument declared inside the function definition of called function.
→ In pass by reference, the formal arguments in the function definition of called function are simply the pointer variable which holds memory address of the corresponding arguments in the calling function.
WAP in C++ to illustrate the concept of pass by reference
#include<iostream>
using namespace std;
void swap(int *,int *);
int main()
{ int a,b;
cout<<"Enter the first number a:";
cin>>a;
cout<<"Enter second number b:";
cin>>b;
cout<<"Before calling the function swap a="<<a<<" b="<<b<<endl;
swap(&a,&b);
cout<<"After calling the function swap a="<<a<<" b="<<b; return 0;
}
void swap(int * p,int * q)
{ int temp;
temp = *p;
*p = *q;
*q = temp;
}
Reference Variable or Alias Variable
→ Reference variable or alias variable are the special types of variables which provides an alternative name for previously defined variable.
→ The syntax for declaring an alias or a reference variable is:
data_type &alias_variable_name=previously_defined_variable;
Example: int a=5;
int &b=a;
WAP in CPP to illustrate the concept of reference variable
#include<iostream>
using namespace std;
int main()
{ int a;
int &b=a;
cout<<"Enter the value of a:";
cin>>a;
cout<<"The value of a is:"<<b;
return 0;
}
Next Example:
Return by reference
Example 1: WAP in CPP to find the greatest number among two numbers entered by
the user using the concept of return by reference.
#include<iostream>
using namespace std;
int & max(int &p,int &q)
{ if(p>q) return p;
else return q;
}
int main() {
int a,b;
cout<<"Enter two numbers:";
cin>>a>>b;
cout<<"The greatest no. is:"<<max(a,b);
return 0;
}
Array, Pointer and Strings
Array:-
The grouping of similar types of variables with a common tag is known as array. Arrays are very useful in programming because it helps to decrease the number of variable names used in the program by using a common tag with different index.
Declaring/Defining one dimensional array:
The syntax of declaring one dimensional array is:
data_type array_name[size];
Examples:
int a[10];
The above statement declares an array of integers with size 10 and creates 10 integer variable in a contiguous memory locations. They are a[0], a[1], a[2], a[3], a[4], a[5], …a[9].
Initializing one dimensional(1D) arrays:
Array can be initialized as following:-
int a[] = {1,2,3,5,6,9,10};
the above statement declares an array of integers with name “a” and initializes its elements i.e. a[0] to 1, a[1] to 2, a[2] to 3, a[3] to 5, a[4] to 6, a[5] to 9 and a[6] to 10. The size of array is 7.
WAP to calculate the sum and average of n integer numbers entered by the user using array.
#include<iostream>
using namespace std;
int main()
{
int n;
float a[10],sum=0,avg;
cout<<"Enter the no. of terms"<<endl;
cin>>n;
cout<<"Start entering the values..."<<endl;
for(int i=0;i<n;i++)
{ cin>>a[i];
sum=sum+a[i];
}
avg=sum/n;
cout<<"Sum="<<sum<<endl<<"Average="<<avg;
return 0;
}
Multi-dimensional arrays:
The arrays having two or more than two indices are known as multi-dimensional arrays. In two dimensional arrays, there are two indices.
Declaring a two dimensional array:
int a[3][3];
The above statement declares 3 × 3 = 9 values in the following order: a[0][0], a[0][1], a[0][2], a[1][0], a[1][1], a[1][2], a[2][0], a[2][1], a[2][2]
Initializing two dimensional(2D) array:-
Two dimensional arrays can be initialized in the same way as we initialized one dimensional array.
For example: int a[3][3] = {1,2,3,4,5,6,7,8,9};
The above statement initializes the elements of a, a[0][0], a[0][1], a[0][2], a[1][0], a[1][1], a[1][2], a[2][0], a[2][1], a[2][2] respectively to 1,2,3,4,5,6,7,8,9.
WAP in CPP to find the product of two 3×3 matrices entered by the user:
#include<iostream>
using namespace std;
int main() {
int a[3][3],b[3][3],c[3][3],i,j,k,sum;
cout<<"Enter first Matrix:\n";
for(i=0;i<3;i++)
{ for(j=0;j<3;j++)
{ cin>>a[i][j];
}
}
cout<<"Enter Second Matrix:\n";
for(i=0;i<3;i++)
{ for(j=0;j<3;j++)
{
cin>>b[i][j];
}
}
for(i=0;i<3;i++)
{ for(j=0;j<3;j++)
{ sum=0;
for(k=0;k<3;k++)
{
sum = sum + a[i][k]*b[k][j];
}
c[i][j]=sum;
}
}
cout<<"The product matrix is:\n"<<endl;
for(i=0;i<3;i++)
{ for(j=0;j<3;j++){
cout<<c[i][j]<<" ";
}
cout<<"\n"; }
return 0;
}
Pointers:
Pointers are the special types of variables that can hold or store the memory location of other variable. Using the concept of pointer it is possible to write a very powerful and optimized code that can be run using very less memory space especially for a resource constraint environment.
Following are the advantages of using pointers in C++:
- Pointers provide direct access to memory.
- Pointers provide a way to return more than one value to the functions.
- Reduces the storage space and complexity of the program.
- Reduces the execution time of the program.
- Provides an alternate way to access array elements.
- Pointers can be used to pass information back and forth between the calling function and called function.
- Pointers allow us to perform dynamic memory allocation and de-allocation.
- Pointers helps us to build complex data structures like linked list, stack, queues, trees, graphs etc.
- Pointers allow us to resize the dynamically allocated memory block.
- Addresses of objects can be extracted using pointers.
Pointer Declaration:
The general syntax for declaring a pointer variable is:
type *variable_name;
Example:
int a,*ptr; ptr=&a; //Assign memory addr of a to ptr.
The second statement makes ptr pointer to a.
Example: WAP in CPP to illustrate the concept of pointer.
#include<iostream>
using namespace std;
int main() {
int a=5,*ptr;
ptr=&a;
cout<<"Value of a= "<<a<<endl;
cout<<"Memory address of a= "<<&a<<endl;
cout<<"Value of a= "<<*ptr<<endl;
cout<<"Memory address of a= "<<ptr<<endl;
return 0;
}
Pointer Arithmetic:
The rule to increment the pointer is given below:-
new_address= current_address + i * size_of(data type)
Pointer to 1D array:
Suppose we have declared an array and pointer as:
data_type a[SIZE], *ptr;
ptr=&a[0];
Strings:
In C programming language, string is defined as an array of characters terminated by a null character('\0'). The syntax for defining a string is:
char string_variable[size];
For example:
char str[20];
The above statement declares a string variable or character array with identifier str and size 20.
char name[10];
The above statement declares a string variable or character array with identifier name and size 10.
Initializing a string:-
Similar to initialization of integer or float arrays, string variable can be initialized by initializing the character array.
For example:-
char str1[]="Pokhara";
char str2[]={'P','o','k','h','a','r','a','\0'};
Structure
Structure is a collection of dissimilar types of data. Use of structure in programs makes the programs more readable and efficient.
The syntax for defining a structure is as follows:-
struct structure_name
{
type1 variable_name1;
type2 variable_name2;
type3 variable_name3;
type4 variable name;
}
Example:
struct student
{
char name[20];
int roll;
int marks;
char address[30];
};
The above example shows how a structure definition can be written. The above code defines a new structure with name student embedding different variable like name, roll, marks and address.
After a structure has been defined, it can be declared in any function as follows:
struct structure_name variable_name;
Example:
struct student s;
The above statement declares a structure variable s of type student. The struct is the keyword.
The structure variable can also be declared along with the definition as follows:
struct student
{
char name[20];
int roll;
int marks;
char address[30];
}s;
It defines the structure student as well as declares a structure variable named s of type student.
Initializing a structure:-
Suppose we a have structure named student already defined. The structure can be initialized like an array and string.
The statement,
struct student s = {"Ram", 12, 98,"Kathmandu"};
initializes s.name to "Ram", s.roll to 12 , s. marks to 98 and s.address to "Kathmandu".
Accessing Structure Elements:-
Each element of structure can be accessed by using dot (.) operator. If we have defined a structure called student and have declared it as follows:
struct student s;
Each element of s can be accessed by using dot operator as follows:
s.name, s.roll, s.address etc.
Each of these can be treated as a separate variable. We can input values into them using cin and display values out of them using cout as follows: cin>>s.name; cout<<s.name;
Array of Structure:-
One can create an array of structure like we created an array of basic types.
For example:
struct student s[48];
The above statement declares/creates an array of structure called student with size 48.
This means 48 structures ranging from s[0], s[1],…. up to s[47] has been created at once.
The member can be accessed as s[0].name, s[0].roll, s[0].address, s[1].name, s[1].roll, s[1].address, etc.
Union
Union is similar to structure with some differences. First, all member of structure have different addresses and sizes. Secondly, the total size of the structure is equal to the sum of the size of each member. For example: If we have the structure student defined as:
struct student
{ int roll; char name[20]; float marks; char address[50]; }
Assuming the size of integer is 2 bytes, character is 1 byte and float is 4 bytes, the size of member variables roll, name, marks and address are 2 bytes, 20 bytes, 4 bytes and 50 bytes respectively and the total size of structure student is 76 bytes. In case of union, all member of structure share the common address. And the total size of the union is equal to the size of largest member contained in it. While using union, since all members of the union share common memory address, only one member can be accessed at a time.
The syntax for defining a union is:
union union_name
{
type1 variable_name1;
type2 variable_name2;
type3 variable_name3;
type4 variable_name4;
}
Once the union has been defined a variable of type union can be declared using following syntax: union union_name variable_name;
For example:
union student
{ int roll;
char name[20];
float marks;
char address[50];
}
In the above union definition, the size of largest member is 50 bytes. And all other members share this memory. So the total size of union student is 50 bytes. The statement, union student s; declares a union variable s of type student.
Enumeration
Enumeration (or enum) is a user defined data type in C++. It is mainly used to assign names to integral constants, the names make a program easy to read and maintain.
The syntax for defining enumeration is:
enum enum_name{const1,const2,const3,... ... ... ...,constn};
The const1,const2,... ...,constn are assigned value 0,1,2 and so on. However if we wish we can assign different values to the constants using following syntax:
enum enum_name{const1=value1,const2=value2,const3=value3,... ... ... ...,constn=valuen};
Once the enum has been defined a variable of type enum can be declared using following syntax:
enum enum_name variable_name;
This is the end of Default Argument, Alias Variable, Array, Pointer and Strings in C++(CPP).