C++ Programming Code Examples
C++ > Algorithms Code Examples
Telephone
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
/* Telephone */
#include<stdio.h>
#include<string.h>
main()
{
FILE *t,*p;
char another,choice;
struct telephone
{
char name[30];
long int code;
long int number;
};
struct telephone data;
char custname[30];
long int n;
long int recsize;
t=fopen("TELEPHONE.DAT","rb+");
if(t==NULL)
{
t=fopen("TELEPHONE.DAT","wb+");
if(t==NULL)
{
printf("The File can't open\n");
exit();
}
}
printf(" TELEPHONE DIRECTORY \n");
printf(" ************* \n");
recsize=sizeof(data);
while(1)
{
printf("\n\n");
printf("1.Add Records\n");
printf("2.List Records\n");
printf("3.Modify Records\n");
printf("4.Finding Number\n");
printf("5.Finding Name\n");
printf("6.Delete Records\n");
printf("0.Exit\n");
printf("Your Choice:");
fflush(stdin);
choice=getche();
switch(choice)
{
case '1':
fseek(t,0,SEEK_END);
another='y';
while(another=='y')
{
printf("\nEnter Customer name,Code number and Telephone number\n");
scanf("%s %ld %ld",data.name,&data.code,&data.number);
fwrite(&data,recsize,1,t);
printf("Add another data(y/n):");
fflush(stdin);
another=getche();
printf("\n");
}
break;
case '2':
rewind(t);
printf("\n");
printf("---------------------------------------------\n");
printf("| CUSTOMER | CODE | TELEPHONE |\n");
printf("---------------------------------------------\n");
rewind(t);
while(fread(&data,recsize,1,t)==1)
printf("| %-18s %-2ld %12ld |\n\n",data.name,data.code,data.number);
printf("--------------------------------------------\n");
getch();
printf("\n");
break;
case '3':
another='y';
while(another=='y')
{
printf("\nEnter name of customer to modify:");
scanf("%s",custname);
rewind(t);
while(fread(&data,recsize,1,t)==1)
{
if(strcmp(data.name,custname)==0)
{
printf("\nEnter new name,code and telephone number\n");
scanf("%s %ld &ld",data.name,&data.code,&data.number);
fseek(t,-recsize,SEEK_CUR);
fwrite(&data,recsize,1,t);
break;
}
}
printf("Modify another record(y/n):");
fflush(stdin);
another=getche();
printf("\n");
}
break;
case '4':
another='y';
while(another=='y')
{
printf("\nEnter name of customer:");
scanf("%s",custname);
rewind(t);
while(fread(&data,recsize,1,t)==1)
{
if(strcmp(data.name,custname)==0)
{
printf("Telephone Number=%ld %ld\n",data.code,data.number);
getch();
}
}
printf("Find another number(y/n)? ");
fflush(stdin);
another=getche();
printf("\n");
}
break;
case '5':
another='y';
while(another=='y')
{
printf("\nEnter number of customer:");
scanf("%ld",&n);
rewind(t);
while(fread(&data,recsize,1,t)==1)
{
if(data.number==n)
{
printf("The Name is %s\n",data.name);
getch();
}
}
printf("Find another name(y/n)? ");
fflush(stdin);
another=getche();
printf("\n");
}
break;
case '6':
another='y';
while(another=='y')
{
printf("\nEnter name of customer to delete:");
scanf("%s",custname);
p=fopen("TEMP.DAT","wb");
rewind(t);
while(fread(&data,recsize,1,t)==1)
{
if(strcmp(data.name,custname)!=0)
fwrite(&data,recsize,1,p);
}
fclose(t);
fclose(p);
remove("TELEPHONE.DAT");
rename("TEMP.DAT","TELEPHONE.DAT");
t=fopen("TELEPHONE","rb+");
printf("Delete another record(y/n):");
fflush(stdin);
another=getche();
}
break;
case '0':
printf("\n");
fclose(t);
exit();
}
}
}
write() Function in C++
Write block of data. Inserts the first n characters of the array pointed by s into the stream. This function simply copies a block of data, without checking its contents: The array may contain null characters, which are also copied without stopping the copying process.
Internally, the function accesses the output sequence by first constructing a sentry object.
Then (if good), it inserts character into its associated stream buffer object as if calling its member function sputc until n characters have been written or until an insertion fails (in this case it sets the badbit flag).
Finally, it destroys the sentry object before returning.
Syntax for write() Function in C++
#include <fstream>
ostream& write (const char* s, streamsize n);
s
Pointer to an array of at least n characters.
n
Number of characters to insert. Integer value of type streamsize representing the size in characters of the block of data to write. streamsize is a signed integral type.
Function returns the ostream object (*this).
Errors are signaled by modifying the internal state flags:
• eofbit: -
• failbit: May be set if the construction of sentry failed.
• badbit: Either an insertion on the stream failed, or some other error happened (such as when this function catches an exception thrown by an internal operation). When set, the integrity of the stream may have been affected.
Multiple flags may be set by a single operation.
If the operation sets an internal state flag that was registered with member exceptions, the function throws an exception of member type failure.
Data races
Access up to n characters pointed by s. Modifies the stream object.
Concurrent access to the same stream object may cause data races, except for the standard stream objects (cout, cerr, clog) when these are synchronized with stdio (in this case, no data races are initiated, although no guarantees are given on the order in which characters from multiple threads are inserted).
Exception safety
Basic guarantee: if an exception is thrown, the object is in a valid state. It throws an exception of member type failure if the resulting error state flag is not goodbit and member exceptions was set to throw for that state.
Any exception thrown by an internal operation is caught and handled by the function, setting badbit. If badbit was set on the last call to exceptions, the function rethrows the caught exception.
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
27
28
29
30
31
32
33
/* write block of data by ostream::write function code example */
/* in order to perform a binary input/output operation using the read() and write() functions, C++ provides us a few file stream classes */
// Copy a file
#include <fstream> // std::ifstream, std::ofstream
int main () {
std::ifstream infile ("test.txt",std::ifstream::binary);
std::ofstream outfile ("new.txt",std::ofstream::binary);
// get size of file
infile.seekg (0,infile.end);
long size = infile.tellg();
infile.seekg (0);
// allocate memory for file content
char* buffer = new char[size];
// read content of infile
infile.read (buffer,size);
// write to outfile
outfile.write (buffer,size);
// release dynamically-allocated memory
delete[] buffer;
outfile.close();
infile.close();
return 0;
}
main() Function in C++
A program shall contain a global function named main, which is the designated start of the program in hosted environment. main() function is the entry point of any C++ program. It is the point at which execution of program is started. When a C++ program is executed, the execution control goes directly to the main() function. Every C++ program have a main() function.
Syntax for main() Function in C++
void main()
{
............
............
}
void
void is a keyword in C++ language, void means nothing, whenever we use void as a function return type then that function nothing return. here main() function no return any value.
main
main is a name of function which is predefined function in C++ library.
In place of void we can also use int return type of main() function, at that time main() return integer type value.
1) It cannot be used anywhere in the program
a) in particular, it cannot be called recursively
b) its address cannot be taken
2) It cannot be predefined and cannot be overloaded: effectively, the name main in the global namespace is reserved for functions (although it can be used to name classes, namespaces, enumerations, and any entity in a non-global namespace, except that a function called "main" cannot be declared with C language linkage in any namespace).
3) It cannot be defined as deleted or (since C++11) declared with C language linkage, constexpr (since C++11), consteval (since C++20), inline, or static.
4) The body of the main function does not need to contain the return statement: if control reaches the end of main without encountering a return statement, the effect is that of executing return 0;.
5) Execution of the return (or the implicit return upon reaching the end of main) is equivalent to first leaving the function normally (which destroys the objects with automatic storage duration) and then calling std::exit with the same argument as the argument of the return. (std::exit then destroys static objects and terminates the program).
6) (since C++14) The return type of the main function cannot be deduced (auto main() {... is not allowed).
7) (since C++20) The main function cannot be a coroutine.
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
27
28
29
30
31
32
/* simple code example by main() function in C++ */
#include <iostream>
using namespace std;
int main() {
int day = 4;
switch (day) {
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
case 4:
cout << "Thursday";
break;
case 5:
cout << "Friday";
break;
case 6:
cout << "Saturday";
break;
case 7:
cout << "Sunday";
break;
}
return 0;
}
sizeof() Operator in C++
The sizeof() is an operator that evaluates the size of data type, constants, variable. It is a compile-time operator as it returns the size of any variable or a constant at the compilation time. The size, which is calculated by the sizeof() operator, is the amount of RAM occupied in the computer.
The sizeof is a keyword, but it is a compile-time operator that determines the size, in bytes, of a variable or data type. The sizeof operator can be used to get the size of classes, structures, unions and any other user defined data type.
Syntax for sizeof() Operator in C++
sizeof(data_type);
data_type
data type whose size is to be calculated
The data_type can be the data type of the data, variables, constants, unions, structures, or any other user-defined data type.
If the parameter of a sizeof() operator contains the data type of a variable, then the sizeof() operator will return the size of the data type.
sizeof() may give different output according to machine, we have run our program on 32 bit gcc compiler.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/* The sizeof() is an operator in C and C++. It is an unary operator which assists a programmer in finding the size of the operand which is being used. */
#include <iostream>
using namespace std;
int main() {
int arr[]={10,20,30,40,50};
std::cout << "Size of the array 'arr' is : "<<sizeof(arr) << std::endl;
cout << "Size of char : " << sizeof(char) << endl;
cout << "Size of int : " << sizeof(int) << endl;
cout << "Size of short int : " << sizeof(short int) << endl;
cout << "Size of long int : " << sizeof(long int) << endl;
cout << "Size of float : " << sizeof(float) << endl;
cout << "Size of double : " << sizeof(double) << endl;
cout << "Size of wchar_t : " << sizeof(wchar_t) << endl;
return 0;
}
fseek() Function in C++
Reposition stream position indicator. Sets the position indicator associated with the stream to a new position. For streams open in binary mode, the new position is defined by adding offset to a reference position specified by origin.
For streams open in text mode, offset shall either be zero or a value returned by a previous call to ftell, and origin shall necessarily be SEEK_SET.
If the function is called with other values for these arguments, support depends on the particular system and library implementation (non-portable).
The end-of-file internal indicator of the stream is cleared after a successful call to this function, and all effects from previous calls to ungetc on this stream are dropped.
On streams open for update (read+write), a call to fseek allows to switch between reading and writing.
Syntax for fseek() Function in C++
#include <cstdio>
int fseek ( FILE * stream, long int offset, int origin );
stream
Pointer to a FILE object that identifies the stream.
offset
Binary files: Number of bytes to offset from origin. Text files: Either zero, or a value returned by ftell.
origin
Position used as reference for the offset. It is specified by one of the following constants defined in <cstdio> exclusively to be used as arguments for this function:
• SEEK_SET Beginning of file
• SEEK_CUR Current position of the file pointer
• SEEK_END End of file *
* Library implementations are allowed to not meaningfully support SEEK_END (therefore, code using it has no real standard portability).
If successful, the function returns zero.
Otherwise, it returns non-zero value.
If a read or write error occurs, the error indicator (ferror) is set.
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
27
28
29
30
31
32
33
34
35
36
/* fseek() in C language, is use to move file pointer to a specific position. Offset and stream are the destination of pointer, is given in the function parameters. If successful, it returns zero. If it is not successful, it returns non-zero value. */
/* Reposition stream position indicator by fseek() function code example */
#include <cstdio>
int main()
{
FILE* fp = fopen("example.txt","w+");
char ch;
fputs("Erica 25 Berlin", fp);
rewind(fp);
printf("Name: ");
while((ch=fgetc(fp))!=' ')
putchar(ch);
putchar('\n');
printf("Age: ");
fseek(fp,10,SEEK_SET);
while((ch=fgetc(fp))!=' ')
putchar(ch);
putchar('\n');
printf("City: ");
fseek(fp,15,SEEK_SET);
while((ch=fgetc(fp))!=EOF)
putchar(ch);
putchar('\n');
fclose(fp);
return 0;
}
Break Statement in C++
Break statement in C++ is a loop control statement defined using the break keyword. It is used to stop the current execution and proceed with the next one. When a compiler calls the break statement, it immediately stops the execution of the loop and transfers the control outside the loop and executes the other statements. In the case of a nested loop, break the statement stops the execution of the inner loop and proceeds with the outer loop. The statement itself says it breaks the loop. When the break statement is called in the program, it immediately terminates the loop and transfers the flow control to the statement mentioned outside the loop.
Syntax for Break Statement in C++
// jump-statement;
break;
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
27
28
29
30
31
32
/* break statement with while loop code example */
// program to find the sum of positive numbers
// if the user enters a negative numbers, break ends the loop
// the negative number entered is not added to sum
#include <iostream>
using namespace std;
int main() {
int number;
int sum = 0;
while (true) {
// take input from the user
cout << "Enter a number: ";
cin >> number;
// break condition
if (number < 0) {
break;
}
// add all positive numbers
sum += number;
}
// display the sum
cout << "The sum is " << sum << endl;
return 0;
}
While Loop Statement in C++
In while loop, condition is evaluated first and if it returns true then the statements inside while loop execute, this happens repeatedly until the condition returns false. When condition returns false, the control comes out of loop and jumps to the next statement in the program after while loop.
The important point to note when using while loop is that we need to use increment or decrement statement inside while loop so that the loop variable gets changed on each iteration, and at some point condition returns false. This way we can end the execution of while loop otherwise the loop would execute indefinitely. A while loop that never stops is said to be the infinite while loop, when we give the condition in such a way so that it never returns false, then the loops becomes infinite and repeats itself indefinitely.
Syntax for While Loop Statement in C++
while (condition) {
// body of the loop
}
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
27
28
29
30
31
/* While Loop Statement in C++ language */
// program to find the sum of positive numbers
// if the user enters a negative number, the loop ends
// the negative number entered is not added to the sum
#include <iostream>
using namespace std;
int main() {
int number;
int sum = 0;
// take input from the user
cout << "Enter a number: ";
cin >> number;
while (number >= 0) {
// add all positive numbers
sum += number;
// take input again if the number is positive
cout << "Enter a number: ";
cin >> number;
}
// display the sum
cout << "\nThe sum is " << sum << endl;
return 0;
}
strcmp() Function in C++
Compare two strings. Compares the C string str1 to the C string str2. This function starts comparing the first character of each string. If they are equal to each other, it continues with the following pairs until the characters differ or until a terminating null-character is reached. This function performs a binary comparison of the characters. For a function that takes into account locale-specific rules, see strcoll. The strcmp() function in C++ compares two null-terminating strings (C-strings). The comparison is done lexicographically. It is defined in the cstring header file.
Syntax for strcmp() Function in C++
int strcmp ( const char * str1, const char * str2 );
str1
pointer to the C-string that needs to be compared.
str2
pointer to the C-string that needs to be compared.
Here, str1 stands for left hand side, str2 stands for right hand side.
Function returns a positive value if the first differing character in str1 is greater than the corresponding character in str2.
Function returns a negative value if the first differing character in str1 is less than the corresponding character in str2.
Function returns 0 if str1 and str2 are equal.
The strcmp() compares the contents of str1 and str2 lexicographically.
The sign of the result is the sign of difference between the first pairs of characters that differ in str1 and str2.
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
27
28
29
30
/* compare two strings by strcmp() string function code example */
#include <cstring>
#include <iostream>
using namespace std;
int main() {
char str1[] = "HappyCodings";
char str2[] = "Happy";
// returns -1 because "HappyCodings" < "Happy" lexicographically
int result = strcmp(str1, str2);
cout << "Comparing " << str1 << " and " << str2 << ": " << result << endl;
// returns 1 because "Happy" > "HappyCodings" lexicographically
result = strcmp(str2, str1);
cout << "Comparing " << str2 << " and " << str1 << ": " << result << endl;
// returns 1 because "HappyCodings" = "HappyCodings" lexicographically
result = strcmp(str1, str1);
cout << "Comparing " << str1 << " and " << str1 << ": " << result;
return 0;
}
exit() Function in C++
The exit function terminates the program normally. Automatic objects are not destroyed, but static objects are. Then, all functions registered with atexit are called in the opposite order of registration. The code is returned to the operating system. An exit code of 0 or EXIT_SUCCESS means successful completion. If code is EXIT_FAILURE, an indication of program failure is returned to the operating system. Other values of code are implementation-defined.
Syntax for exit() Function in C++
void exit (int status);
status
Status code. If this is 0 or EXIT_SUCCESS, it indicates success. If it is EXIT_FAILURE, it indicates failure.
Calls all functions registered with the atexit() function, and destroys C++ objects with static storage duration, all in last-in-first-out (LIFO) order. C++ objects with static storage duration are destroyed in the reverse order of the completion of their constructor. (Automatic objects are not destroyed as a result of calling exit().)
Functions registered with atexit() are called in the reverse order of their registration. A function registered with atexit(), before an object obj1 of static storage duration is initialized, will not be called until obj1's destruction has completed. A function registered with atexit(), after an object obj2 of static storage duration is initialized, will be called before obj2's destruction starts.
Normal program termination performs the following (in the same order):
• Objects associated with the current thread with thread storage duration are destroyed (C++11 only).
• Objects with static storage duration are destroyed (C++) and functions registered with atexit are called.
• All C streams (open with functions in <cstdio>) are closed (and flushed, if buffered), and all files created with tmpfile are removed.
• Control is returned to the host environment.
Note that objects with automatic storage are not destroyed by calling exit (C++).
If status is zero or EXIT_SUCCESS, a successful termination status is returned to the host environment.
If status is EXIT_FAILURE, an unsuccessful termination status is returned to the host environment.
Otherwise, the status returned depends on the system and library implementation.
Flushes all buffers, and closes all open files.
All files opened with tmpfile() are deleted.
Returns control to the host environment from the program.
exit() returns no values.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/* terminate the process normally, performing the regular cleanup for terminating programs by exit() function code example */
#include<iostream>
using namespace std;
int main()
{
int i;
cout<<"Enter a non-zero value: "; //user input
cin>>i;
if(i) // checks whether the user input is non-zero or not
{
cout<<"Valid input.\n";
}
else
{
cout<<"ERROR!"; //the program exists if the value is 0
exit(0);
}
cout<<"The input was : "<<i;
}
read() Function in C++
Read block of data. Extracts n characters from the stream and stores them in the array pointed to by s. This function simply copies a block of data, without checking its contents nor appending a null character at the end.
If the input sequence runs out of characters to extract (i.e., the end-of-file is reached) before n characters have been successfully read, the array pointed to by s contains all the characters read until that point, and both the eofbit and failbit flags are set for the stream.
Internally, the function accesses the input sequence by first constructing a sentry object (with noskipws set to true). Then (if good), it extracts characters from its associated stream buffer object as if calling its member functions sbumpc or sgetc, and finally destroys the sentry object before returning.
The number of characters successfully read and stored by this function can be accessed by calling member gcount.
Syntax for read() Function in C++
#include <fstream>
istream& read (char* s, streamsize n);
s
Pointer to an array where the extracted characters are stored.
n
Number of characters to extract. streamsize is a signed integral type.
Function returns the istream object (*this).
Errors are signaled by modifying the internal state flags:
• eofbit: The function stopped extracting characters because the input sequence has no more characters available (end-of-file reached).
• failbit: Either the function could not extract n characters or the construction of sentry failed.
• badbit: Error on stream (such as when this function catches an exception thrown by an internal operation). When set, the integrity of the stream may have been affected.
Multiple flags may be set by a single operation.
If the operation sets an internal state flag that was registered with member exceptions, the function throws an exception of member type failure.
Data races
Modifies the elements in the array pointed to by s and the stream object. Concurrent access to the same stream object may cause data races, except for the standard stream object cin when this is synchronized with stdio (in this case, no data races are initiated, although no guarantees are given on the order in which extracted characters are attributed to threads).
Exception safety
Basic guarantee: if an exception is thrown, the object is in a valid state. It throws an exception of member type failure if the resulting error state flag is not goodbit and member exceptions was set to throw for that state.
Any exception thrown by an internal operation is caught and handled by the function, setting badbit. If badbit was set on the last call to exceptions, the function rethrows the caught exception.
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
27
28
29
30
31
32
33
34
35
/* The function read() in <iostream> header file extracts n characters from the stream and stores them in the array pointed to the stream. Unlike functions put() and get() it is usually used to handle the data in binary form. */
/* extracts n characters from the stream and stores them in the array pointed by s with read() function code example. */
#include <iostream>
#include <fstream>
int main () {
std::ifstream is ("test.txt", std::ifstream::binary);
if (is) {
is.seekg (0, is.end);
int length = is.tellg();
is.seekg (0, is.beg);
char * buffer = new char [length];
std::cout << "Reading " << length << " characters... ";
is.read (buffer,length);
if (is)
std::cout << "all characters read successfully.";
else
std::cout << "error: only " << is.gcount() << " could be read";
is.close();
delete[] buffer;
}
return 0;
}
Structures in C++ Language
In C++, classes and structs are blueprints that are used to create the instance of a class. Structs are used for lightweight objects such as Rectangle, color, Point, etc. Unlike class, structs in C++ are value type than reference type. It is useful if you have data that is not intended to be modified after creation of struct.
C++ Structure is a collection of different data types. It is similar to the class that holds different types of data.
Syntax for Structures in C++
struct structureName{
member1;
member2;
member3;
.
.
.
memberN;
};
struct Teacher
{
char name[20];
int id;
int age;
}
s.id = 4;
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
27
28
29
30
31
/* Structure is a collection of variables of different data types under a single name. It is similar to a class in that, both holds a collecion of data of different data types. */
#include <iostream>
using namespace std;
struct Person
{
char name[50];
int age;
float salary;
};
int main()
{
Person p1;
cout << "Enter Full name: ";
cin.get(p1.name, 50);
cout << "Enter age: ";
cin >> p1.age;
cout << "Enter salary: ";
cin >> p1.salary;
cout << "\nDisplaying Information." << endl;
cout << "Name: " << p1.name << endl;
cout <<"Age: " << p1.age << endl;
cout << "Salary: " << p1.salary;
return 0;
}
Nested Loop Statement in C++
C supports nesting of loops in C. Nesting of loops is the feature in C that allows the looping of statements inside another loop. Any number of loops can be defined inside another loop, i.e., there is no restriction for defining any number of loops. The nesting level can be defined at n times. You can define any type of loop inside another loop; for example, you can define 'while' loop inside a 'for' loop.
A loop inside another loop is called a nested loop. The depth of nested loop depends on the complexity of a problem. We can have any number of nested loops as required. Consider a nested loop where the outer loop runs n times and consists of another loop inside it. The inner loop runs m times. Then, the total number of times the inner loop runs during the program execution is n*m.
Syntax for Nested Loop Statement in C++
Outer_loop
{
Inner_loop
{
// inner loop statements.
}
// outer loop statements.
}
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
27
28
29
30
31
32
33
/* nested loop statement in C++ language */
// C++ program that uses nested for loop to print a 2D matrix
#include <bits/stdc++.h>
using namespace std;
#define ROW 3
#define COL 3
// Driver program
int main()
{
int i, j;
// Declare the matrix
int matrix[ROW][COL] = { { 4, 8, 12 },
{ 16, 20, 24 },
{ 28, 32, 36 } };
cout << "Given matrix is \n";
// Print the matrix using nested loops
for (i = 0; i < ROW; i++) {
for (j = 0; j < COL; j++)
cout << matrix[i][j];
cout << "\n";
}
return 0;
}
If Else If Ladder in C/C++
The if...else statement executes two different codes depending upon whether the test expression is true or false. Sometimes, a choice has to be made from more than 2 possibilities. The if...else ladder allows you to check between multiple test expressions and execute different statements.
In C/C++ if-else-if ladder helps user decide from among multiple options. The C/C++ if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the C else-if ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.
Syntax of if...else Ladder in C++
if (Condition1)
{ Statement1; }
else if(Condition2)
{ Statement2; }
.
.
.
else if(ConditionN)
{ StatementN; }
else
{ Default_Statement; }
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
27
28
29
30
31
32
/* write a C program which demonstrate use of if-else-if ladder statement */
/* Program to Print Day Names using Else If Ladder in C++*/
#include <iostream>
using namespace std;
int main()
{
int day;
cout << "Enter Day Number: ";
cin >> day;
cout << "Day is ";
if (day == 1)
cout << "Sunday" << endl;
else if (day == 2)
cout << "Monday" << endl;
else if (day == 3)
cout << "Tuesday" << endl;
else if (day == 4)
cout << "Wednesday" << endl;
else if (day == 5)
cout << "Thursday" << endl;
else if (day == 6)
cout << "Friday" << endl;
else
cout << "Saturday" << endl;
return 0;
}
File System rename() Function in C++
Rename file. Changes the name of the file or directory specified by oldname to newname. This is an operation performed directly on a file; No streams are involved in the operation.
If oldname and newname specify different paths and this is supported by the system, the file is moved to the new location.
If newname names an existing file, the function may either fail or override the existing file, depending on the specific system and library implementation.
Proper file access shall be available.
Syntax for rename() Function in C++
#include <stdio.h>
int rename ( const char * oldname, const char * newname );
oldname
C string containing the name of an existing file to be renamed and/or moved.
Its value shall follow the file name specifications of the running environment and can include a path (if supported by the system).
newname
C string containing the new name for the file. Its value shall follow the file name specifications of the running environment and can include a path (if supported by the system).
If the file is successfully renamed, a zero value is returned.
On failure, a nonzero value is returned.
On most library implementations, the errno variable is also set to a system-specific error code on failure.
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
/* change the filename of a file by rename() function code example. */
/* The C++ <cstdio> rename() function is used to change the name of a file. The file is identified by character string pointed to by oldname. The new filename is identified by character string pointed to by newname. If newname already exists, the behavior of this function is implementation-defined. */
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
char oldname[] = "file_old.txt";
char newname[] = "file_new.txt";
/* Deletes the file if exists */
if (rename(oldname, newname) != 0)
perror("Error renaming file");
else
cout << "File renamed successfully";
return 0;
}
#include Directive in C++
#include is a way of including a standard or user-defined file in the program and is mostly written at the beginning of any C/C++ program. This directive is read by the preprocessor and orders it to insert the content of a user-defined or system header file into the following program. These files are mainly imported from an outside source into the current program. The process of importing such files that might be system-defined or user-defined is known as File Inclusion. This type of preprocessor directive tells the compiler to include a file in the source code program.
Syntax for #include Directive in C++
#include "user-defined_file"
#include <header_file>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/* using #include directive in C language */
#include <stdio.h>
int main()
{
/*
* C standard library printf function
* defined in the stdio.h header file
*/
printf("I love you Clementine");
printf("I love you so much");
printf("HappyCodings");
return 0;
}
fclose() Function in C++
Close file. Closes the file associated with the stream and disassociates it. Closes the given file stream. Any unwritten buffered data are flushed to the OS. Any unread buffered data are discarded.
Whether or not the operation succeeds, the stream is no longer associated with a file, and the buffer allocated by std::setbuf or std::setvbuf, if any, is also disassociated and deallocated if automatic allocation was used.
All internal buffers associated with the stream are disassociated from it and flushed: the content of any unwritten output buffer is written and the content of any unread input buffer is discarded.
Even if the call fails, the stream passed as parameter will no longer be associated with the file nor its buffers.
Syntax for fclose() Function in C++
#include <cstdio>
int fclose ( FILE * stream );
stream
Pointer to a FILE object that specifies the stream to be closed.
If the stream is successfully closed, a zero value is returned.
On failure, EOF is returned.
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
27
28
29
30
/* The fclose() function takes a single argument, a file stream which is to be closed. All the data that are buffered but not written are flushed to the OS and all unread buffered data are discarded.
Even if the operation fails, the stream is no longer associated with the file. If the file pointer is used after fclose() is executed, the behaviour is undefined. */
/* Close file by fclose() function code example */
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
FILE *fp;
fp = fopen("file.txt","w");
char str[20] = "Hello World!";
if (fp == NULL)
{
cout << "Error opening file";
exit(1);
}
fprintf(fp,"%s",str);
fclose(fp);
cout << "File closed successfully";
return 0;
}
getch() Function in C++
The getch() is a predefined non-standard function that is defined in conio.h header file. It is mostly used by the Dev C/C++, MS- DOS's compilers like Turbo C to hold the screen until the user passes a single value to exit from the console screen. It can also be used to read a single byte character or string from the keyboard and then print. It does not hold any parameters. It has no buffer area to store the input character in a program.
Syntax for getch() Function in C++
#include <conio.h>
int getch(void);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/* wait for any character input from keyboard by getch() function code example. The getch() function is very useful if you want to read a character input from the keyboard. */
// C code to illustrate working of
// getch() to accept hidden inputs
#include<iostream.h>
#include<conio.h>
void main()
{
int a=10, b=20;
int sum=0;
clrscr();
sum=a+b;
cout<<"Sum: "<<sum;
getch(); // use getch() befor end of main()
}
File System remove() Function in C++
The remove() function in C++ deletes a specified file. Deletes the file whose name is specified in filename. The remove() function takes a single argument filename and returns an integer value. It deletes the file pointed by the parameter.
This is an operation performed directly on a file identified by its filename; No streams are involved in the operation. Proper file access shall be available. Incase the file to be deleted is opened by a process, the behaviour of remove() function is implementation-defined.
It is defined in <cstdio> header file.
Syntax for remove() Function in C++
#include <cstdio>
int remove ( const char * filename );
filename
C string containing the name of the file to be deleted. Its value shall follow the file name specifications of the running environment and can include a path (if supported by the system).
If the file is successfully deleted, a zero value is returned.
On failure, a nonzero value is returned.
On most library implementations, the errno variable is also set to a system-specific error code on failure.
In case the file to be deleted is opened by a process, the behaviour of remove() function is implementation-defined:
• POSIX systems - If the name was the last link to a file, but any processes still have the file open, the file will remain in existence until the last running process closes the file.
• Windows - The file won't be allowed to be deleted if it remains open by any process.
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
27
28
29
/* The remove() function in C++ removes a specified file. It is defined in the cstdio header file. */
/* Delete the file whose name is specified in filename by remove() function code example. */
#include <iostream>
#include <cstdio>
using namespace std;
int main() {
char filename[] = "C:\\Users\\file.txt";
// deletes the file if it exists
int result = remove(filename);
// check if file has been deleted successfully
if (result != 0) {
// print error message
cerr << "File deletion failed";
}
else {
cout << "File deleted successfully";
}
return 0;
}
fflush() Function in C++
Flush stream. The fflush() function in C++ flushes any buffered data to the respective device. Buffered data is the temporary or application specific data stored in the physical memory of the computer until a certain time.
If the given stream was open for writing (or if it was open for updating and the last i/o operation was an output operation) any unwritten data in its output buffer is written to the file.
If stream is a null pointer, all such streams are flushed.
In all other cases, the behavior depends on the specific library implementation. In some implementations, flushing a stream open for reading causes its input buffer to be cleared (but this is not portable expected behavior).
The stream remains open after this call.
When a file is closed, either because of a call to fclose or because the program terminates, all the buffers associated with it are automatically flushed.
Syntax for fflush() Function in C++
#include <cstdio>
int fflush ( FILE * stream );
stream
Pointer to a FILE object that specifies a buffered stream.
Function returns a zero value indicates success.
If an error occurs, EOF is returned and the error indicator is set (see ferror).
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
27
28
/* For output streams (and for update streams on which the last operation was output), writes any unwritten data from the stream's buffer to the associated output device. For input streams (and for update streams on which the last operation was input), the behavior is undefined.
If stream is a null pointer, all open output streams are flushed, including the ones manipulated within library packages or otherwise not directly accessible to the program. */
/* flushes the output buffer of the stream by fflush function code example. */
#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{
char mybuffer[800];
FILE * file;
file = fopen ("demo.txt","r+");
fputs ("test",file);
fflush (file); // flushing required
fgets (mybuffer,800,file);
cout << mybuffer << endl;
fclose (file);
return 0;
}
Switch Case Statement in C++
Switch statement in C tests the value of a variable and compares it with multiple cases. Once the case match is found, a block of statements associated with that particular case is executed.
Each case in a block of a switch has a different name/number which is referred to as an identifier. The value provided by the user is compared with all the cases inside the switch block until the match is found.
If a case match is NOT found, then the default statement is executed, and the control goes out of the switch block.
Syntax for Switch Case Statement in C++
switch( expression )
{
case value-1:
Block-1;
Break;
case value-2:
Block-2;
Break;
case value-n:
Block-n;
Break;
default:
Block-1;
Break;
}
Statement-x;
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
27
28
29
30
31
/* the switch statement helps in testing the equality of a variable against a set of values */
#include <iostream>
using namespace std;
int main () {
// local variable declaration:
char grade = 'D';
switch(grade) {
case 'A' :
cout << "Excellent!" << endl;
break;
case 'B' :
case 'C' :
cout << "Well done" << endl;
break;
case 'D' :
cout << "You passed" << endl;
break;
case 'F' :
cout << "Better try again" << endl;
break;
default :
cout << "Invalid grade" << endl;
}
cout << "Your grade is " << grade << endl;
return 0;
}
IOS Library eof() Function in C++
Check whether eofbit is set. Returns true if the eofbit error state flag is set for the stream. This flag is set by all standard input operations when the End-of-File is reached in the sequence associated with the stream.
Note that the value returned by this function depends on the last operation performed on the stream (and not on the next).
Operations that attempt to read at the End-of-File fail, and thus both the eofbit and the failbit end up set. This function can be used to check whether the failure is due to reaching the End-of-File or to some other reason.
Syntax for IOS eof() Function in C++
bool eof() const;
Data races
Accesses the stream object. Concurrent access to the same stream object may cause data races.
Exception safety
Strong guarantee: if an exception is thrown, there are no changes in the stream.
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
/* The eof() method of ios class in C++ is used to check if the stream is has raised any EOF (End Of File) error. It means that this function will check if this stream has its eofbit set. */
// C++ code example to demonstrate the working of eof() function
#include <iostream>
#include <fstream>
int main () {
std::ifstream is("example.txt");
char c;
while (is.get(c))
std::cout << c;
if (is.eof())
std::cout << "[EoF reached]\n";
else
std::cout << "[error reading]\n";
is.close();
return 0;
}
If Else Statement in C++
In computer programming, we use the if statement to run a block code only when a certain condition is met. An if statement can be followed by an optional else statement, which executes when the boolean expression is false. There are three forms of if...else statements in C++:
• if statement,
• if...else statement,
• if...else if...else statement,
Syntax for If Statement in C++
if (condition) {
// body of if statement
}
Syntax for If...Else Statement
if (condition) {
// block of code if condition is true
}
else {
// block of code if condition is false
}
Syntax for If...Else...Else If Statement in C++
if (condition1) {
// code block 1
}
else if (condition2){
// code block 2
}
else {
// code block 3
}
Syntax for If Else If Ladder in C++
if (condition)
statement 1;
else if (condition)
statement 2;
.
.
else
statement;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/* If Else Statement in C++ Language */
#include <iostream>
using namespace std;
int main () {
// local variable declaration:
int a = 100;
// check the boolean condition
if( a < 20 ) {
// if condition is true then print the following
cout << "a is less than 20;" << endl;
} else {
// if condition is false then print the following
cout << "a is not less than 20;" << endl;
}
cout << "value of a is : " << a << endl;
return 0;
}
getche() Function in C++
This function waits for any character input from keyboard. And, it will also echo the input character on to the output screen. The getch() function is very useful if you want to read a character input from the keyboard.
Like getch(), getche() is also character input functions. It is unformatted input function meaning it does not allow user to read input in their format. Difference between getch() and getche() is that getche() echoes pressed character. getche() also returns character pressed like getch(). It is also defined in header file conio.h.
Syntax for getche() Function in C++
int getche( void );
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
27
28
29
30
31
32
33
/* getche() function is a function in C programming language which waits for any character input from keyboard and it will also echo the input character on to the output screen. Please find below the description and syntax for above file handling function. */
int chcount = 0, wdcount =0, count = 0;
char ch=' ';
cout << "Enter your text : ";
while ( ch != '\r' )
{
if ( ch !=' ' )
{
chcount++;
count++;
}
else if (count > 2)
{
wdcount++;
count=0;
}
ch = getche();
}
if (count >2) //validate that last word is counted
wdcount++;
cout<<"\nCount of words is: "<<wdcount<<"\nCount of charcters is: "<<chcount<<"\n";
system("pause");
return 0;
In this, Insert item x into the 'priority queue', maintaining heap order. Return a pointer to the node containing the new item. Find the 'smallest' item in the priority queue. Return
Insert x into the tree; duplicates are ignored. Remove x from the tree. Nothing is done if x is not found. Find the "smallest item" in the tree. Find the "largest item" in the tree. Find