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

C++ Enumeration: Programming Fundaments

The document discusses C++ strings and enumerations. It provides examples of defining and using enumerations to represent fixed sets of constants. It also discusses C-style strings defined as character arrays, the string class for variable-length strings, and functions for manipulating strings like strcpy(), strcat(), strcmp(), strlen(), strlwr(), and strupr(). Examples are given for inputting, outputting, concatenating, comparing, and modifying strings in C++.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
123 views

C++ Enumeration: Programming Fundaments

The document discusses C++ strings and enumerations. It provides examples of defining and using enumerations to represent fixed sets of constants. It also discusses C-style strings defined as character arrays, the string class for variable-length strings, and functions for manipulating strings like strcpy(), strcat(), strcmp(), strlen(), strlwr(), and strupr(). Examples are given for inputting, outputting, concatenating, comparing, and modifying strings in C++.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 26

Programming Fundaments

C++ Enumeration

Enum in C++ is a data type that contains fixed set of constants.

It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY and SATURDAY), directions (NORTH, SOUTH, EAST and
WEST) etc.

Points to remember for C++ Enum


o enum improves type safety
o enum can be easily used in switch
o enum can be traversed

C++ Enumeration Example

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++";

In the above code, str is a string and it holds 4 characters.

Although, "C++" has 3 characters, the null character \0 is added to the end of the string
automatically.

Example 1: C++ String to read a word


#include <iostream>
using namespace std;
int main(){
char str[100];

cout << "Enter a string: ";


cin >> str;
cout << "You entered: " << str << endl;
return 0;
}

Example 2: C++ String to read a line of text


#include <iostream>
using namespace std;

int main(){
char str[100];
cout << "Enter a string: ";
cin.get (str, 100);

cout << "You entered: " << str << endl;


return 0;
}

Example 3: Copy C-Strings


#include <iostream>
#include <cstring>
using namespace std;
int main(){
char s1[100], s2[100];

cout << "Enter string s1: ";


cin.getline(s1, 100);

strcpy (s2, s1);

cout << "s1 = "<< s1 << endl;


cout << "s2 = "<< s2;

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.

Example 1: C++ string using string data type


#include <iostream>
using namespace std;

int main(){
// Declaring a string object
string str;
cout << "Enter a string: ";
getline (cin, str);

cout << "You entered: " << str << endl;


return 0;
}

Example 2: Copy String Object


#include <iostream>
using namespace std;
int main(){
string s1, s2;

cout << "Enter string s1: ";


getline (cin, s1);

s2 = s1;

cout << "s1 = "<< s1 << endl;


cout << "s2 = "<< s2;

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;

vowels = consonants = digits = spaces = 0;

cout << "Enter a line of string: ";


cin.getline(line, 150);
for(int i = 0; line[i]!='\0'; ++i){

if(line[i]=='a' || line[i]=='e' || line[i]=='i' || line[i]=='o' ||


line[i]=='u' || line[i]=='A' || line[i]=='E' || line[i]=='I' ||
line[i]=='O' || line[i]=='U'){
++vowels;

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

cout << "Vowels: " << vowels << endl;


cout << "Consonants: " << consonants << endl;
cout << "Digits: " << digits << endl;
cout << "White spaces: " << spaces << endl;

return 0;
}

Example 4: From a String Object


This program takes a string object from the user and calculates the number of vowels,
consonants, digits and white-spaces.

#include <iostream>
using namespace std;
int main(){
string line;
int vowels, consonants, digits, spaces;

vowels = consonants = digits = spaces = 0;

cout << "Enter a line of string: ";


getline(cin, line);

for(int i = 0; i < line.length(); ++i)


{
if(line[i]=='a' || line[i]=='e' || line[i]=='i' ||
line[i]=='o' || line[i]=='u' || line[i]=='A' ||
line[i]=='E' || line[i]=='I' || line[i]=='O' ||
line[i]=='U')
{
++vowels;
}
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;
}
}

4|Page
Programming Fundaments

cout << "Vowels: " << vowels << endl;


cout << "Consonants: " << consonants << endl;
cout << "Digits: " << digits << endl;
cout << "White spaces: " << spaces << endl;

return 0;
}

Example 5: Find Frequency of Characters in a C-style String


#include <iostream>
using namespace std;
int main(){

char c[];
cout << "Enter a line of string: ";
cin.getline(c, 150); //C++ programming is not easy

char check = 'm';


int count = 0;

for(int i = 0; c[i] != '\0'; ++i)


{
if(check == c[i])
++count;
}
cout << "Frequency of " << check << " = " << count;
return 0;
}

Example 6: Passing String to a Function

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

cout << "Enter another string: ";


cin.get(str, 100);
display(str1);
display(str);
return 0;
}

void display(char s[])

5|Page
Programming Fundaments

{
cout << "Entered char array is: " << s << endl;
}

void display(string s)
{
cout << "Entered string is: " << s << endl;
}

Output

Enter a string: Programming is fun.


Enter another string: Really?
Entered string is: Programming is fun.
Entered char array is: Really?

Example 7: Remove all characters except alphabets

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

for(int i = 0; line[i] != '\0'; ++i)


{
if ((line[i] >= 'a' && line[i]<='z') || (line[i] >= 'A' && line[i]<='Z'))
{
alphabetString[j++] = line[i];

}
}
alphabetString[j] = '\0';

cout << "Output String: " << alphabetString;


return 0;
}

Output

Enter a string: P2'r"o@gram84iz./


Output String: Programiz

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

cout << "The value of s1= "<< s1 << endl;


cout << "The value of s2= "<< s2;
return 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';

cout<<"\nThe concatenated string is "<<str3;

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

cout << "s1 = " << s1 << endl;


cout << "s2 = " << s2;
return 0;
}

strcmp(): The strcmp() function compares two strings and returns 0 if both
strings are identical.
Return Value from strcmp()

Return Value Remarks

0 if both strings are identical (equal)

negative If the first string is less than second string

positive integer if the first string is greater than second string.

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

cout << "The length of string is= "<< i << endl;


return 0;
}

strlen(): this function is used to find the length of a string


#include <iostream>
#include <cstring>
int main(){
char str[] = "Hello String";
int result;
result = strlen(str);
cout<<result;
return 0;
}

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;

C++ Programming Code to Reverse String

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

C++ Program to remove spaces from a string


#include<iostream>
using namespace std;
int main()
{
int i, j=0;
char str[30];
cout<<"Enter a String:\n";
cin.get(str,30);

for(i=0; str[i]!='\0'; ++i)


{
if(str[i]!=' ')
str[j++]=str[i];
}

str[j]='\0';

cout<<"\nString After Removing Spaces:\n"<<str;


return 0;
}

Write a program to count number of words in string.

#include<iostream>
using namespace std;

int main( )
{
char str[80];

cout << "Enter a string: ";


cin.getline(str,80);

int words = 0; // Holds number of words

for(int i = 0; str[i] != '\0'; i++)


{
if (str[i] == ' ') //Checking for spaces
{
words++;
}
}

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:

Java is the best programming language


Position of the programming word is 16

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

C++ String replace()

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:

Before replacement, string is: Collage


After replacement, string is: College
0 1 2 3 4 5 6
C o l l a g e
C o l l e g e
str1.replace(4, 0, str2);

0 1 2 3 4 5 6 7
C o l l a g e
C o l l e a g e

Output:

Before replacement, string is: Collage


After replacement, string is: Colleage

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:

Before replacement, String is : This is C language


After replacement, String is : This is java language

C++ String insert()

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()

string str1= "M College";


cout<<"String contains :" <<str1<<'\n';
cout<<"After insertion, String value is :"<<str1.insert(1,"TB");
return 0;
}

13 | P a g e
Programming Fundaments
Output:

String contains : M College


After insertion, String value is: MTB College

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:

String contains C++ is a language


After insertion, String is: C++ is a programming language

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.

Defining a Pointer Variable


int *iptr;
iptr can hold the address of an int

Pointer Variables Assignment:


int num = 25;
int *iptr; //pointer declaration
iptr = &num; //pointer initialization

Memory layout

Using the pointer or Dereferencing of Pointer


Once a pointer has been assigned the address of a variable, to access the value of the
variable, pointer is dereferenced, using the indirection operator or dereferencing
operator *.
cout << num; // prints 25
cout << &num; // prints 0x4a00
cout << iptr; // prints 0x4a00
cout << *itptr; // prints 25

Similar, following declaration shows:


char *cptr;
float *fptr;
cptr is a pointer to character and fptr is a pointer to float value.

Pointer and Arrays


When an array is declared, compiler allocates sufficient amount of memory to contain all the
elements of the array. Base address i.e address of the first element of the array is also
allocated by the compiler.
Suppose we declare an array arr,
int arr[5] = { 1, 2, 3, 4, 5 };
Assuming that the base address of arr is 1000 and each integer requires two bytes, the five
elements will be stored as follows:

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.

Program for pointer arithmetic (32-bit machine)


int a = 5, b = 10, c = 0;
int *p1;
int *p2;
p1 = &a;
p2 = &b;
c = *p1+*p2;
cout<<"*p1+*p2 ="<<c; //*p1+*p2 = 15

16 | P a g e
Programming Fundaments

Pointers as Function Argument


Example 2: Passing by reference using pointers
#include <iostream>
using namespace std;

void swap(int* n1, int* n2);

int main()
{
int a = 1, b = 2;
cout << "Before swaping" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;

swap(&a, &b);

cout << "\nAfter swaping" << endl;


cout << "a = " << a << endl;
cout << "b = " << b << endl;
return 0;
}

void swap(int* n1, int* n2) {


int temp;
temp = *n1;
*n1 = *n2;
*n2 = temp;
}

Functions returning Pointer variables


#include <iostream>
int* larger(int*, int*);
void main(){
int a = 15;
int b = 92;
int *p;
p = larger(&a, &b);
cout<<*p<< “ is larger”;
}

int* larger(int *x, int *y){


if(*x > *y)
return x;
else
return y;
}

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

Example: Calculate H.C.F using recursion


#include <iostream>
using namespace std;

int hcf(int n1, int n2);

int main()
{
int n1, n2;

cout << "Enter two positive integers: ";


cin >> n1 >> n2;

cout << "H.C.F of " << n1 << " & " << n2 << " is: " << hcf(n1, n2);

return 0;
}

int hcf(int n1, int n2)


{
if (n2 != 0)
return hcf(n2, n1 % n2);
else
return n1;
}

18 | P a g e
Programming Fundaments

C++ Files and Streams

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:

Data Type Description

ofstream Used to create files and to write information to files.

ifstream Used to read information from files.

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.

void open(filename, ios:: mode);

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.

Mode Flag Stands for Description

If FileName is a new file, then it created an empty file.


ios::in Input
If FileName already exists, then File open for reading

ios::out Output File open for writing

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.

All output operations happen at the end of the file, appending


ios::app append
to its existing contents.

Any contents that existed in the file before it is open are


ios::trunc truncate
discarded.

These flags can be combined with the bitwise OR operator (|).

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

afile.open("file.dat", ios::out | ios::in );

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.

Reading from a File


You read information from a file into your program using the stream extraction
operator (>>) just as you use that operator to input information from the keyboard.
The only difference is that you use an ifstream or fstream object instead of
the cin object.

Read & Write Example


Following is the C++ program which opens a file in reading and writing mode. After
writing information inputted by the user to a file named afile.dat, the program reads
information from the file and outputs it onto the screen:

#include <fstream>
#include <iostream>
using namespace std;

int main () {

char ch=’A’;
int n=10;

// open a file in write mode.


ofstream outfile;
outfile.open("my.txt");

outfile<<n<<’’<<ch;
outfile.close();

// open a file in read mode.


ifstream infile;
infile.open("my.txt");

infile>>n>>ch;
cout<<n<<ch;

return 0;
}

20 | P a g e
Programming Fundaments

Input the names of five cities and store them in a file

#include <fstream>
#include <iostream>
using namespace std;

int main () {
char city[50];
ofstream outfile;
outfile.open("city.txt");

for(int i=0; i<5; i++){


cin>>city;
outfile<<city<<endl;
}

outfile.close();

return 0;
}

Display all the record from city.txt using End-of-File

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

// open a file in write mode.


ofstream outfile;
outfile.open("my.txt");

cout << "Enter your name: ";


cin.getline(data, 100);

// write inputted data into the file.


outfile << data << endl;

cout << "Enter your age: ";


cin >> data;

// again write inputted data into the file.


outfile << data << endl;

// close the opened file.


outfile.close();

// open a file in read mode.


ifstream infile;
infile.open("my.txt");

cout << "Reading from the file" << endl;


infile >> data;

// write the data at the screen.


cout << data << endl;

// again read the data from the file and display it.
infile >> data;
cout << data << endl;

// close the opened file.


infile.close();

return 0;
}

22 | P a g e
Programming Fundaments

The Standard Output Stream (cout)


The predefined object cout is an instance of ostream class. The cout object is said to
be "connected to" the standard output device, which usually is the display screen.
The cout is used in combination with the stream insertion operator, which is written as
<< which are two less than signs as shown in the following example.

#include <iostream>

using namespace std;

int main() {

char str[] = "Hello C++";

cout << "Value of str is : " << str << endl;

When the above code is compiled and executed, it produces the following result −
Value of str is : Hello C++

The Standard Input Stream (cin)


The predefined object cin is an instance of istream class. The cin object is said to be
attached to the standard input device, which usually is the keyboard. The cin is used in
conjunction with the stream extraction operator, which is written as >> which are two
greater than signs as shown in the following example.

#include <iostream>

using namespace std;

int main() {

char name[50];

cout << "Please enter your name: ";

cin >> name;

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.

operator asm equivalent description

& AND Bitwise AND

| OR Bitwise inclusive OR

^ XOR Bitwise exclusive OR

~ NOT Unary complement (bit inversion)

<< SHL Shift bits left

>> SHR Shift bits right

The truth tables for &, |, and ^ are as follows −

p q p&q p|q p^q ~p

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&B = 0000 1100

A|B = 0011 1101

A^B = 0011 0001

~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*

However, there is an exception to this rule.

In C++, there is a general-purpose pointer that can point to any type. This general-
purpose pointer is pointer to void.

void *ptr; // pointer to void

Example: C++ Pointer to Void


void* ptr;
float f = 2.3;
ptr = &f; // float* to void
cout << &f << endl;
cout << ptr;

Pointer to Constant vs Constant Pointer


Pointer to Constant
const int* ptr;

declares ptr a pointer to const int type. You can modify ptr itself, but the object
pointed to by ptr shall not be modified.

const int a = 10;


const int* ptr = &a;
*ptr = 5; // wrong
ptr++; // right

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

You might also like