C++ Enumeration: Programming Fundaments
C++ Enumeration: Programming Fundaments
C++ Enumeration
It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY and SATURDAY), directions (NORTH, SOUTH, EAST and
WEST) etc.
Let's see the simple example of enum data type used in C++ program.
#include <iostream>
using namespace std;
enum week { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday };
int main()
{
week day;
day = Friday;
cout << "Day: " << day+1<<endl;
return 0;
}
Output:
Day: 5
1|Page
Programming Fundaments
C-strings
In C programming, the collection of characters is stored in the form of arrays, this is also
supported in C++ programming. Hence, it's called C-strings.
C-strings are arrays of type char terminated with null character, that is, \0 (ASCII value
of null character is 0).
How to define a C-string?
char str[] = "C++";
Although, "C++" has 3 characters, the null character \0 is added to the end of the string
automatically.
int main(){
char str[100];
cout << "Enter a string: ";
cin.get (str, 100);
return 0;
}
2|Page
Programming Fundaments
string Object
In C++, you can also create a string object for holding strings.
Unlike using char arrays, string objects has no fixed length, and can be extended as per
your requirement.
int main(){
// Declaring a string object
string str;
cout << "Enter a string: ";
getline (cin, str);
s2 = s1;
return 0;
}
Example 3:
C++ Program to Find the Number of Vowels, Consonants, Digits and White
Spaces in a String
#include <iostream>
using namespace std;
int main()
{
char line[150];
int vowels, consonants, digits, spaces;
3|Page
Programming Fundaments
}
else if((line[i]>='a'&& line[i]<='z') || (line[i]>='A'&&
line[i]<='Z'))
{
++consonants;
}
else if(line[i]>='0' && line[i]<='9')
{
++digits;
}
else if (line[i]==' ')
{
++spaces;
}
}
return 0;
}
#include <iostream>
using namespace std;
int main(){
string line;
int vowels, consonants, digits, spaces;
4|Page
Programming Fundaments
return 0;
}
char c[];
cout << "Enter a line of string: ";
cin.getline(c, 150); //C++ programming is not easy
Strings are passed to a function in a similar way arrays are passed to a function.
#include <iostream>
using namespace std;
void display(char s[]);
void display(string);
int main(){
string str1;
char str[100];
cout << "Enter a string: ";
getline(cin, str1);
5|Page
Programming Fundaments
{
cout << "Entered char array is: " << s << endl;
}
void display(string s)
{
cout << "Entered string is: " << s << endl;
}
Output
This program below takes a string (C-style string) input from the user and removes all
characters except alphabets.
#include <iostream>
using namespace std;
int main() {
char line[100], alphabetString[100];
int j = 0;
cout << "Enter a string: ";
cin.getline(line, 100);
}
}
alphabetString[j] = '\0';
Output
6|Page
Programming Fundaments
7|Page
Programming Fundaments
Example: Copy C-Strings
Inputs a string from the user and then copies it another string
#include <iostream>
using namespace std;
int main(){
char s1[50], s2[50];
int i=0;
cout << "Enter string: ";
cin.getline(s1, 50);
while(s1[i] != ‘\0’){
s2[i]=s1[i];
i++;
}
S2[i]= ‘\0’;
Example: input first name and second name in two strings concatenate both
strings in third string and display it.
#include <iostream>
using namespace std;
int main(){
char str1[30],str2[30],str3[60];
int i,j;
cout<<"Enter first string:";
gets(str1);
cout<<"\nEnter second string:";
gets(str2);
while(str1[i]!='\0'){
str3[i]=str1[i];
i++;
}
str3[i++]=' ';
while(str2[j]!='\0'){
str3[i]=str2[j];
i++;
j++;
}
str3[i]='\0';
return 0;
}
8|Page
Programming Fundaments
strcat(): this function is used to append a copy of one string to the end of second
string.
#include <iostream>
#include <cstring>
using namespace std;
int main(){
char s1[50], s2[50], result[100];
cout << "Enter string s1: ";
cin.getline(s1, 50);
cout << "Enter string s2: ";
cin.getline(s2, 50);
strcat(s1, s2);
strcmp(): The strcmp() function compares two strings and returns 0 if both
strings are identical.
Return Value from strcmp()
#include <iostream>
#include <cstring>
int main(){
char str1[] = "a", str2[] = "abcd", str3[] = "ab";
int result;
result = strcmp(str1, str2);
cout<<result;
result = strcmp(str2, str3);
cout<<result;
return 0;
}
Example: Program that input a string from the user and display its length
#include <iostream>
using namespace std;
int main(){
char s1[100];
int i=0;
cout << "Enter string: ";
cin.getline(s1, 100);
while(s1[i] != ‘\0’)
9|Page
Programming Fundaments
i++;
strlwr(): this function is used to convert all characters of a string to lower case
char str[] = "Hello String";
strlwr(str);
cout<<str;
strupr(): this function is used to convert all characters of a string to upper case
char str[] = "Hello String";
strupr(str);
cout<<str;
Following C++ program ask to the user to enter a string to reverse it and display the
reversed string on the screen:
#include<iostream>
int main(){
char str[100], temp;
int i=0, j;
cout << "Enter string: ";
cin.getline(str, 100);
j=strlen(str)-1;
while(i<j)
{
temp=str[i];
str[i]=str[j];
str[j]=temp;
i++;
j--;
}
cout<<"Reverse of the String = "<<str;
return 0;
}
10 | P a g e
Programming Fundaments
str[j]='\0';
#include<iostream>
using namespace std;
int main( )
{
char str[80];
cout << "The number of words = " << words+1 << endl;
return 0;
}
11 | P a g e
Programming Fundaments
C++ String Find()
#include<iostream>
using namespace std;
int main()
{
string str= "C++ is the best programming language";
cout<< str.find("programming");
return 0;
}
Output:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
C + + i s t h e b e s t p r o g r a m m i n g
Example 1
First example shows how to replace given string by using position and length as
parameters.
#include<iostream>
using namespace std;
int main()
{
string str1 = "Collage";
string str2 = "e";
cout << "Before replacement, string is: "<<str1<<'\n';
str1.replace(4, 1, str2);
cout << "After replacement, string is: "<<str1<<'\n';
return 0;
}
Output:
0 1 2 3 4 5 6 7
C o l l a g e
C o l l e a g e
Output:
12 | P a g e
Programming Fundaments
str1.replace(4, 2, str2);
0 1 2 3 4 5 6
C o l l a g e
C o l l e e
str1.replace(4, 3, str2);
0 1 2 3 4 5 6
C o l l a g e
C o l l e
Example 2
Second example shows how to replace given string using position and length of the string
which is to be copied in another string object.
#include<iostream>
using namespace std;
int main()
{
string str1 ="This is C language"
string str3= "java language";
cout <<"Before replacement, String is :"<<str1<<'\n';
str1.replace(8, 1, str3, 0, 4);
cout<<"After replacement,String is :"<<str1<<'\n';
return 0;
}
Output:
This function is used to insert a new character, before the character indicated by the
position pos.
Example 1
#include<iostream>
using namespace std;
int main()
13 | P a g e
Programming Fundaments
Output:
Example 2
#include<iostream>
using namespace std;
int main()
{
string str1 = "C++ is a language";
string str2 = "programming";
cout<<"String contains :" <<str1<<'\n';
cout<<"After insertion, String is :"<< str1.insert(9,str2,0,11);
return 0;
}
Output:
14 | P a g e
Programming Fundaments
Pointer
A pointer is a variable that holds a memory address, usually the location of another variable
in memory.
Data type of a pointer must be same as the data type of the variable to which the pointer
variable is pointing. void type pointer works with all data types but is not often used.
Memory layout
Here variable arr will give the base address, which is a constant pointer pointing to the first
element of the array, arr[0]. Hence arr contains the address of arr[0] i.e 1000. In
short, arr has two purposes - it is the name of the array and it acts as a pointer pointing
towards the first element in the array.
arr is equal to &arr[0] by default
15 | P a g e
Programming Fundaments
We can also declare a pointer of type int to point to the array arr.
int *p;
p = arr;
// or,
p = &arr[0]; //both the statements are equivalent.
Now we can access every element of the array arr using p++ to move from one element to
another.
NOTE: You cannot decrement a pointer once incremented. p-- won't work.
Pointer to Array
As studied above, we can use a pointer to point to an array, and then we can use that
pointer to access the array elements. Let’s have an example,
#include <iostream>
int main(){
int i;
int a[5] = {1, 2, 3, 4, 5};
int *ptr = a; // same as int*p = &a[0]
for (i = 0; i < 5; i++){
cout<<*ptr;
ptr++;
//or
// cout << *(ptr+i);
}
return 0;
}
In the above program, the pointer *p will print all the values stored in the array one by one.
Pointer Arithmetic
Pointer is an address which is a numeric value; therefore, you can perform arithmetic
operations on a pointer just as you can a numeric value.
There are four arithmetic operators that can be used on pointers: ++, --, +, and -.
To understand pointer arithmetic, let us consider that ptr is an integer pointer which
points to the address 1000. Assuming 32-bit integers, let us perform the following
arithmetic operation on the pointer:
ptr++
the ptr will point to the location 1004 because each time ptr is incremented, it will point
to the next integer. This operation will move the pointer to next memory location without
impacting actual value at the memory location. If ptr points to a character whose address
is 1000, then above operation will point to the location 1001 because next character will
be available at 1001.
16 | P a g e
Programming Fundaments
int main()
{
int a = 1, b = 2;
cout << "Before swaping" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
swap(&a, &b);
17 | P a g e
Programming Fundaments
Example 1: Factorial of a Number Using Recursion
#include <iostream>
using namespace std;
int factorial(int);
int main()
{
int n;
cout<<"Enter a number to find factorial: ";
cin >> n;
cout << "Factorial of " << n <<" = " << factorial(n);
return 0;
}
int factorial(int n)
{
if (n > 1)
{
return n*factorial(n-1);
}
else
{
return 1;
}
}
int main()
{
int n1, n2;
cout << "H.C.F of " << n1 << " & " << n2 << " is: " << hcf(n1, n2);
return 0;
}
18 | P a g e
Programming Fundaments
This tutorial will teach you how to read and write from a file. This requires another standard C++
library called fstream, which defines three new data types:
fstream Has the capabilities of both ofstream and ifstream which means it can
create files, write information to files, and read information from files.
To perform file processing in C++, header files <iostream> and <fstream> must be included in
your C++ source file.
Opening a File
A file must be opened before you can read from it or write to it. Either
the ofstream or fstream object may be used to open a file for writing and ifstream object is used
to open a file for reading purpose only.
Following is the standard syntax for open() function, which is a member of fstream, ifstream, and
ofstream objects.
Here, the first argument specifies the name and location of the file to be opened and the second
argument defines the mode in which the file should be opened.
ios::binary Binary Operations are performed in binary mode rather than text.
ios::ate at end The output position starts at the end of the file.
You can combine two or more of these values by ORing them together. For example, if you want
to open a file in write mode and want to truncate it in case it already exists, following will be the
syntax:
ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc );
Similar way, you can open a file for reading and writing purpose as follows:
fstream afile;
19 | P a g e
Programming Fundaments
Closing a File
Following is the standard syntax for close() function, which is a member of fstream,
ifstream, and ofstream objects.
void close();
Writing to a File
While doing C++ programming, you write information to a file from your program
using the stream insertion operator (<<) just as you use that operator to output
information to the screen. The only difference is that you use
an ofstream or fstream object instead of the cout object.
#include <fstream>
#include <iostream>
using namespace std;
int main () {
char ch=’A’;
int n=10;
outfile<<n<<’’<<ch;
outfile.close();
infile>>n>>ch;
cout<<n<<ch;
return 0;
}
20 | P a g e
Programming Fundaments
#include <fstream>
#include <iostream>
using namespace std;
int main () {
char city[50];
ofstream outfile;
outfile.open("city.txt");
outfile.close();
return 0;
}
#include <fstream>
#include <iostream>
using namespace std;
int main () {
char city[50];
ifstream infile;
infile.open("my.txt");
while(!infile.eof()){
infile>>city;
cout<<city<<endl;
}
infile.close();
return 0;
}
21 | P a g e
Programming Fundaments
#include <fstream>
#include <iostream>
using namespace std;
int main () {
char data[100];
// again read the data from the file and display it.
infile >> data;
cout << data << endl;
return 0;
}
22 | P a g e
Programming Fundaments
#include <iostream>
int main() {
When the above code is compiled and executed, it produces the following result −
Value of str is : Hello C++
#include <iostream>
int main() {
char name[50];
cout << "Your name is: " << name << endl;
When the above code is compiled and executed, it will prompt you to enter a name. You
enter a value and then hit enter to see the following result −
Please enter your name: xyz
Your name is: xyz
23 | P a g e
Programming Fundaments
Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The Bitwise operators
supported by C++ language are listed in the following table.
| OR Bitwise inclusive OR
0 0 0 0 0 1
0 1 0 1 1 1
1 1 1 1 0 0
1 0 0 1 1 0
Assume if A = 60; and B = 13; now in binary format they will be as follows:
A = 0011 1100
B = 0000 1101
-----------------
~A = 1100 0011
24 | P a g e
Programming Fundaments
C++ Pointer to Void
In C++, you cannot assign the address of variable of one type to a pointer of another
type. Consider this example:
int *ptr;
double d = 9;
ptr = &d; // Error: can't assign double* to int*
In C++, there is a general-purpose pointer that can point to any type. This general-
purpose pointer is pointer to void.
declares ptr a pointer to const int type. You can modify ptr itself, but the object
pointed to by ptr shall not be modified.
Constant Pointer
int * const ptr;
declares ptr a const pointer to int type. You are not allowed to modify ptr but the
object pointed to by ptr.
int a = 10;
int *const ptr = &a;
*ptr = 5; // right
ptr++; // wrong
25 | P a g e
Programming Fundaments
Q. Write a program to find the norm of a matrix. The norm is defined as the
square root of the sum of squares of all element in the matrix.
1. #include <iostream.h>
2. #include <math.h>
3.
4. void main ()
5. {
6.
7. static int array[10][10];
8. int i, j, m, n, sum = 0, norm;
9.
10. cout<<"Enter the order of the matrix\n";
11. cin >> m >> n;
12.
13. cout"Enter the n coefficients of the matrix \n";
14. for (i = 0; i < m; ++i)
15. {
16. for (j = 0; j < n; ++j)
17. {
18. cin>>array[i][j]);
19. sum = sum + array[i][j] * array[i][j];
20.
21. }
22. }
23.
24. norm = sqrt(sum);
25.
26. cout<<"Norm of the matrix is ="<< norm;
27.
28. }
26 | P a g e