C++ Programming Code Examples
C++ > Algorithms Code Examples
Simple Calculator
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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
/* Simple Calculator */
#include"stdio.h"
#include"conio.h"
#include"dos.h"
#include"stdlib.h"
#include"string.h"
void DISPNUM(char *);
void main()
{
clrscr();
_setcursortype(0);
gotoxy(30,19);
textcolor(GREEN+BLINK);
cprintf("SIMPLE CALCULATOR");
gotoxy(50,21);
textcolor(BLUE+BLINK);
cprintf("HELLO WORLD");
getch();
// clrscr();
int x=30,y=10;
textcolor(WHITE);
gotoxy(x,y);
cprintf("7 8 9");
gotoxy(x,y+2);
cprintf("4 5 6");
gotoxy(x,y+4);
cprintf("1 2 3");
gotoxy(x,y+6);
cprintf("0");
textcolor(RED);
gotoxy(x+5,y+6);
cprintf(". =");
textcolor(GREEN);
x=x+15;
gotoxy(x,y);
cprintf("/");
gotoxy(x,y+2);
cprintf("*");
gotoxy(x,y+4);
cprintf("-");
gotoxy(x,y+6);
cprintf("+");
//Draw The For Calc//
x=28;y=5;
gotoxy(x,y);
textcolor(WHITE);
// Ú & ¿ //
cprintf("%c",218);
gotoxy(28+20,y);
cprintf("%c",191);
// Ú & ¿ //
//Horiz. Boundary
for(x=29;x<=28+19;x++)
{
gotoxy(x,y);
cprintf("%c",196);
gotoxy(x,y+12);
cprintf("%c",196);
}
//End of Horiz. Bound
// Ù & À //
cprintf("%c",217);
x=28;y=y+12;
gotoxy(x,y);
cprintf("%c",192);
//End of Ù & À //
//Vertic. Bound.
for(y=6;y<=16;y++)
{
gotoxy(x,y);
cprintf("%c",179);
gotoxy(x+20,y);
cprintf("%c",179);
}
//End of Vertic Bou.
y=6;
for(x=30;x<=30+16;x++)
{
gotoxy(x,y);
cprintf("%c",196);
gotoxy(x,y+2);
cprintf("%c",196);
}
gotoxy(30,y+1);
cprintf("%c %c",179,179);
gotoxy(30,y);
cprintf("%c",218);
gotoxy(30+16,y);
cprintf("%c",191);
gotoxy(30,y+2);
cprintf("%c",192);
gotoxy(30+16,y+2);
cprintf("%c",217);
//End of Vertic Bound.
//OutPut at X=30,Y=8//
char ch;
char operand1[15]="",operand2[15]="",BLANK[15]=" ";
char operator1,first='y';
long double num1=0,num2=0;
int i=0,ERROR=0; //Digits
int MAX=10;
DISPNUM(0);
do
{
ch=getch();
if(ch=='x1b')
{
for(int i=1000;i>=200;i=i-50)
{
sound(i);
delay(100);
}
nosound();
break;
}
//Numeric//
if((ch>='0')&&(ch<='9'))
{
if(i<MAX)
{
if(first=='y')
{
operand1[i]=ch;
DISPNUM(operand1);
i++;
}
else
{
operand2[i]=ch;
DISPNUM(operand2);
i++;
}
}
else //More than 8 digit
{
ERROR=1;
}
}
else if(ch=='.')
{
if(first=='y')
{
if(strchr(operand1,'.')==NULL)
{
operand1[i]=ch;
i++;
}
DISPNUM(operand1);
}
else
{
if(strchr(operand2,'.')==NULL)
{
operand2[i]=ch;
i++;
}
DISPNUM(operand2);
}
}
//Non Numeric
else if (ch=='*')
{
operator1='*';
first='n';
i=0;
}
else if (ch=='/')
{
operator1='/';
first='n';
i=0;
}
else if (ch=='+')
{
operator1='+';
first='n';
i=0;
}
else if (ch=='-')
{
operator1='-';
first='n';
i=0;
}
else if ((ch=='=')||(ch=='
'))
{
//Store in Floating
if(strcmpi(operand1,BLANK)!=0)
{
num1=_atold(operand1);
}
if(strcmpi(operand2,BLANK)!=0)
{
num2=_atold(operand2);
}
//Now Calculate
switch (operator1)
{
case '+':
num1=num1+num2;
break;
case '-':
num1=num1-num2;
break;
case '*':
num1=num1*num2;
break;
case '/':
num1=num1/num2;
break;
}
//ltoa(num1,operand1,10);
gcvt(num1,12,operand1);
DISPNUM(operand1);
i=0;
first='y';
strcpy(operand1,BLANK);
strcpy(operand2,BLANK);
}
else //Invalid Choice
{
ERROR=1;
}
//Beep On ERROR else ------ //
if (ERROR==0)
{
sound(920);
}
else
{
sound(100);
ERROR=0;
}
delay(250);
nosound();
gotoxy(1,1);
cprintf("%d",i);
}while(1);
// clrscr();
gotoxy(30,19);
textcolor(GREEN+BLINK);
cprintf("SIMPLE CALCULATOR");
gotoxy(50,21);
textcolor(BLUE+BLINK);
cprintf("HELLO WORLD");
// getch();
}
void DISPNUM(char *num)
{
textbackground(RED);
gotoxy(31,7);
cprintf(" ");
gotoxy(31,7);
cprintf("%s",num);
}
textbackground() Function in C++
Function textbackground is used to change current background color in text mode. To use the textbackground() function all you need to do is before printing any text call this function with a parameter defining the color in capital letters. That will be enough to change the background color of the text.
Syntax for textbackground() Function in C++
void textbackground(int color);
color
specify the color
INT VALUES corresponding to Colors:
• BLACK 0
• BLUE 1
• GREEN 2
• CYAN 3
• RED 4
• MAGENTA 5
• BROWN 6
• LIGHTGRAY 7
• DARKGRAY 8
• LIGHTBLUE 9
• LIGHTGREEN 10
• LIGHTCYAN 11
• LIGHTRED 12
• LIGHTMAGENTA 13
• YELLOW 14
• WHITE 15
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
/* In C++ programming, the background of the output screen is black and text color is in white color. We can color both the background and text color in the output screen. */
void office::of_beg()
{
int i, v;
do{
textbackground(BLUE);
textcolor(CYAN);
_setcursortype(_NORMALCURSOR);
clrscr();
for(i=0;i<10;++i)
{
box(1+7*i,1+2*i,4,4);
delay(80);
box(1+7*i,1+2*i,4,4,int(' '));
}
box(74,22,4,4);
gotoxy(25,2);
textcolor(GREEN);
cputs("WELCOME TO CREEPER OFFICE...");
gotoxy(6,6);
textcolor(CYAN);
cout<<"1. CALCULATOR";
gotoxy(6,12);
cout<<"0. MAIN MENU";
gotoxy(6,8);
cout<<"2. CREEPER FILE EXPERT ";
gotoxy(6,10);
cout<<"3. CALENDAR ";
gotoxy(25,22);
cout<<"ENTER THE CHOICE NUMBER : ";
v=int(getche()-48);
delay(100);
if(v)
{ switch(v)
{
case 1:
calc();
break;
case 2:
class File a;
break;
case 3:
calendar();
break;
default:
gotoxy(55,22);
cputs("INVALID ENTRY");
delay(1000);
break;
}
}
}while(v!=0);
}
Logical Operators in C++
Logical Operators are used to compare and connect two or more expressions or variables, such that the value of the expression is completely dependent on the original expression or value or variable.
We use logical operators to check whether an expression is true or false. If the expression is true, it returns 1 whereas if the expression is false, it returns 0.
Assume variable A holds 1 and variable B holds 0:
&&
Called Logical AND operator. If both the operands are non-zero, then condition becomes true. (A && B) is false.
The logical AND operator && returns
true - if and only if all the operands are true.
false - if one or more operands are false.
||
Called Logical OR Operator. If any of the two operands is non-zero, then condition becomes true. (A || B) is true.
The logical OR operator || returns
true - if one or more of the operands are true.
false - if and only if all the operands are false.
!
Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true, then Logical NOT operator will make false. !(A && B) is true.
The logical NOT operator ! is a unary operator i.e. it takes only one operand.
It returns true when the operand is false, and false when the operand is true.
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
/* The operator ! is the C++ operator for the Boolean operation NOT. It has only one operand, to its right, and inverts it, producing false if its operand is true, and true if its operand is false. Basically, it returns the opposite Boolean value of evaluating its operand.
The logical operators && and || are used when evaluating two expressions to obtain a single relational result. The operator && corresponds to the Boolean logical operation AND, which yields true if both its operands are true, and false otherwise. */
#include <iostream>
using namespace std;
main() {
int a = 5;
int b = 20;
int c ;
if(a && b) {
cout << "Line 1 - Condition is true"<< endl ;
}
if(a || b) {
cout << "Line 2 - Condition is true"<< endl ;
}
/* Let's change the values of a and b */
a = 0;
b = 10;
if(a && b) {
cout << "Line 3 - Condition is true"<< endl ;
} else {
cout << "Line 4 - Condition is not true"<< endl ;
}
if(!(a && b)) {
cout << "Line 5 - Condition is true"<< endl ;
}
return 0;
}
delay() Function in C++
delay() function is used to hold the program's execution for given number of milliseconds, it is declared in dos.h header file.
There can be many instances when we need to create a delay in our programs. C++ provides us with an easy way to do so. We can use a delay() function for this purpose in our code. We can run the code after a specific time in C++ using delay() function.
Syntax for delay() Function in C++
void delay(unsigned int milliseconds);
milliseconds
how many milliseconds to delay
The function takes one parameter which is unsigned integer.
Here, void suggests that this function returns nothing.
'delay' is the function name.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/* hold the program's execution for given number of milliseconds by delay() function code example. */
#include<iostream.h>
#include<dos.h> //for delay()
#include<conio.h> //for getch()
int main()
{
clrscr();
int n;
cout<<"Enter the delay (in seconds) you want to make after giving input."<<endl;
cin>>n;
delay(n*1000);
cout<<"This has been printed after "<< n <<" seconds delay";
getch();
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;
}
textcolor() Function in C++
Use the textcolor function to define what color you want to use for text. You can use this function to vary the text colors of your output. Colors must be written in all caps, or expressed as a numeral.
Now, if you want your text to blink then while calling the textcolor() function pass the color and also say BLINK. This will like this: textcolor(BLUE+BLINK).
Syntax for textcolor() Function in C++
void textcolor(int color);
color
specify the color
Change the color of drawing text where color is a integer variable
INT VALUES corresponding to Colors:
• BLACK 0
• BLUE 1
• GREEN 2
• CYAN 3
• RED 4
• MAGENTA 5
• BROWN 6
• LIGHTGRAY 7
• DARKGRAY 8
• LIGHTBLUE 9
• LIGHTGREEN 10
• LIGHTCYAN 11
• LIGHTRED 12
• LIGHTMAGENTA 13
• YELLOW 14
• WHITE 15
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/* In C++ programming, the background of the output screen is black and text color is in white color. We can color both the background and text color in the output screen. */
#include <stdio.h>
#include <iostream>
#include <conio.h>
//this should be enough I guess
using namespace std;
string a;
int main()
{
clrscr();
textcolor(2);
gotoxy(3,3);
textattr(4);
cout << "This should be underlined?";
cout << endl;
cout << "Wanna end this program? Press a key (Y) and then press enter..";
cin >> a;
}
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;
}
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;
}
strcmpi() Function in C++
strcmpi( ) function in C is same as strcmp() function. But, strcmpi( ) function is not case sensitive. i.e, "A" and "a" are treated as same characters. Where as, strcmp() function treats "A" and "a" as different characters. strcmpi() function is non standard function which may not available in standard library in C.
Both functions compare two given strings and returns zero if they are same.
If length of string1 < string2, it returns < 0 value. If length of string1 > string2, it returns > 0 value. Syntax for strcmp( ) function is given below.
Syntax for strcmpi() Function in C++
int strcmpi ( const char * str1, const char * str2 );
str1
The first string
str2
The second string
This function returns 0 if the given two strings are same, a negative value if the length of str1 is less then the length of str2 and if the length of str1 is greater then str2 then this function returns a positive value.
This is a non-standard function that works only with older versions of Microsoft C.
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
/* strcmpi compares string1 and string2 without sensitivity to case. All alphabetic characters in the two arguments string1 and string2 are converted to lowercase before the comparison. The function operates on null-ended strings. The string arguments to the function are expected to contain a null character (\0) marking the end of the string. */
/* function strcmpi() code example to compare strings ignoring case. */
#include <stdio.h>
#include <string.h>
int main(){
char str1[30];
char str2[30];
printf("Enter string1: ");
fgets(str1,30,stdin);
printf("Enter string2: ");
fgets(str2,30,stdin);
if(strcmpi(str1,str2)==0)
printf("Both strings are same.\n");
else
printf("Both strings are not same.\n");
return 0;
}
nosound() Function in C++
The nosound() function in C language is used to stop the sound played by sound() function. The nosound() function is simply silent the system.
The sound() and nosound() functions are very useful as they can create very nice music with the help of programming and our user can enjoy music during working in out the program.
Syntax for nosound() Function in C++
void nosound();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/* you can simply silent the system by nosound() function code example. */
#include <stdio.h>
//to use 'sound()', 'delay()' functions
#include <dos.h>
int main()
{
//calling the function for producing
//the sound of frequency 400.
sound(400);
//function to delay the sound for
//half of second.
delay(500);
//calling the function to stop the
//system sound.
nosound();
return 0;
}
For Loop Statement in C++
In computer programming, loops are used to repeat a block of code. For example, when you are displaying number from 1 to 100 you may want set the value of a variable to 1 and display it 100 times, increasing its value by 1 on each loop iteration. When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop. A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.
Syntax of For Loop Statement in C++
for (initialization; condition; update) {
// body of-loop
}
initialization
initializes variables and is executed only once.
condition
if true, the body of for loop is executed, if false, the for loop is terminated.
update
updates the value of initialized variables and again checks the condition.
A new range-based for loop was introduced to work with collections such as arrays and vectors.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/* For Loop Statement in C++ Language */
// C++ program to find the sum of first n natural numbers
// positive integers such as 1,2,3,...n are known as natural numbers
#include <iostream>
using namespace std;
int main() {
int num, sum;
sum = 0;
cout << "Enter a positive integer: ";
cin >> num;
for (int i = 1; i <= num; ++i) {
sum += i;
}
cout << "Sum = " << sum << endl;
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;
}
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;
}
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;
}
clrscr() Function in C++
It is a predefined function in "conio.h" (console input output header file) used to clear the console screen. It is a predefined function, by using this function we can clear the data from console (Monitor). Using of clrscr() is always optional but it should be place after variable or function declaration only.
It is often used at the beginning of the program (mostly after variable declaration but not necessarily) so that the console is clear for our output.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/* clrscr() function is also a non-standard function defined in "conio.h" header. This function is used to clear the console screen. It is often used at the beginning of the program (mostly after variable declaration but not necessarily) so that the console is clear for our output.*/
#include<iostream.h>
#include<conio.h>
void main()
{
int a=10, b=20;
int sum=0;
clrscr(); // use clrscr() after variable declaration
sum=a+b;
cout<<"Sum: "<<sum;
//clear the console screen
clrscr();
getch();
}
String Relational Operators in C++
Relational operators for string. Performs the appropriate comparison operation between the string objects lhs and rhs.
The functions use string::compare for the comparison.
These operators are overloaded in header <string>.
If strings are compared using relational operators then, their characters are compared lexicographically according to the current character traits, means it starts comparison character by character starting from the first character until the characters in both strings are equal or a NULL character is encountered.
Syntax for String Relational Operators in C++
#include <string>
//(1) == : Equal to
bool operator== (const string& lhs, const string& rhs) noexcept;
bool operator== (const char* lhs, const string& rhs);
bool operator== (const string& lhs, const char* rhs);
//(2) != : Not equal to
bool operator!= (const string& lhs, const string& rhs) noexcept;
bool operator!= (const char* lhs, const string& rhs);
bool operator!= (const string& lhs, const char* rhs);
//(3) < : Less than
bool operator< (const string& lhs, const string& rhs) noexcept;
bool operator< (const char* lhs, const string& rhs);
bool operator< (const string& lhs, const char* rhs);
//(4) <= : Less than and equal to
bool operator<= (const string& lhs, const string& rhs) noexcept;
bool operator<= (const char* lhs, const string& rhs);
bool operator<= (const string& lhs, const char* rhs);
//(5) > : Greater than
bool operator> (const string& lhs, const string& rhs) noexcept;
bool operator> (const char* lhs, const string& rhs);
bool operator> (const string& lhs, const char* rhs);
//(6) >= : Greater than and equal to
bool operator>= (const string& lhs, const string& rhs) noexcept;
bool operator>= (const char* lhs, const string& rhs);
bool operator>= (const string& lhs, const char* rhs);
lhs, rhs
Arguments to the left- and right-hand side of the operator, respectively. If of type char*, it shall point to a null-terminated character sequence.
• lhs < rhs : A string lhs is smaller than rhs string, if either, length of lhs is shorter than rhs or first mismatched character is smaller.
• lhs > rhs : A string lhs is greater than rhs string, if either, length of lhs is longer than rhs or first mismatched character is larger.
• <= and >= have almost same implementation with additional feature of being equal as well.
• If after comparing lexicographically, both strings are found same, then they are said to be equal.
• If any of the points from 1 to 3 follows up then, strings are said to be unequal.
Function returns true if the condition holds, and false otherwise.
Complexity
Unspecified, but generally up to linear in both lhs and rhs's lengths.
Iterator validity
No changes
Data races
Both objects, lhs and rhs, are accessed.
Exception safety
If an argument of type char* does not point to null-terminated character sequence, it causes undefined behavior.
For operations between string objects, exceptions are never thrown (no-throw guarantee).
For other cases, if an exception is thrown, there are no changes in the string (strong guarantee).
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
/* If strings are compared using relational operators then, their characters are compared lexicographically according to the current character traits, means it starts comparison character by character starting from the first character until the characters in both strings are equal or a NULL character is encountered. */
// CPP code example to implement relational operators on String objects
#include<iostream>
using namespace std;
void relational_operation(string s1, string s2)
{
string s3 = s1 + s2;
if(s1 != s2)
cout << s1 << " is not equal to " << s2 << endl;
if(s1 > s2)
cout << s1 << " is greater than " << s2 << endl;
else if(s1 < s2)
cout << s1 << " is smaller than " << s2 << endl;
if(s3 == s1 + s2)
cout << s3 << " is equal to " << s1 + s2 << endl;
}
// Main function
int main()
{
string s1("Happy");
string s2("Happy 8) Codings");
relational_operation(s1, s2);
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;
}
strcpy() Function in C++
Copy string. Copies the C string pointed by source into the array pointed by destination, including the terminating null character (and stopping at that point). To avoid overflows, the size of the array pointed by destination shall be long enough to contain the same C string as source (including the terminating null character), and should not overlap in memory with source.
strcpy() is a standard library function in C/C++ and is used to copy one string to another. In C it is present in string.h header file and in C++ it is present in cstring header file. It copies the whole string to the destination string. It replaces the whole string instead of appending it. It won't change the source string.
Syntax for strcpy() Function in C++
#include <cstring>
char * strcpy ( char * destination, const char * source );
destination
Pointer to the destination array where the content is to be copied.
source
C string to be copied.
destination is returned.
After copying the source string to the destination string, the strcpy() function returns a pointer to the destination string.
• This function copies the entire string to the destination string. It doesn't append the source string to the destination string. In other words, we can say that it replaces the content of destination string by the content of source string.
• It does not affect the source string. The source string remains same after copying.
• This function only works with C style strings and not C++ style strings i.e. it only works with strings of type char str[]; and not string s1; which are created using standard string data type available in C++ and not C.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/* copy a character string from source to destination by strcpy() string function code example */
#include <cstring>
#include <iostream>
using namespace std;
int main() {
char src[20] = "I am the source.";
// large enough to store content of src
char dest[30] = "I am the destination.";
cout << "dest[] before copy: " << dest << endl;
// copy contents of src to dest
strcpy(dest,src);
cout << "dest[] after copy: " << dest;
return 0;
}
strchr() Function in C++
Locate first occurrence of character in string. Returns a pointer to the first occurrence of character in the C string str. The terminating null-character is considered part of the C string. Therefore, it can also be located in order to retrieve a pointer to the end of a string.
C++ strchr() is a built-in function that is used for string handling, and it is defined under the cstring header file.
Syntax for strchr() Function in C++
#include <cstring>
const char * strchr ( const char * str, int character );
char * strchr ( char * str, int character );
str
C string
character
Character to be located. It is passed as its int promotion, but it is internally converted back to char for the comparison.
Function returns a pointer to the first occurrence of character in str.
If the character is not found, the function returns a null pointer.
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
/* strchr() function is an inbuilt function in C++ STL, which is defined in the <cstring> header file. strchr() function is used to find when the character first occurred in the string. This function returns the pointer to the location where the character first appeared in the string. If the character doesn't exist in the string the function returns the null pointer. */
/* Locate first occurrence of character in string by strchr() function code example */
#include <iostream>
#include <cstring>
using namespace std;
int main(){
char str[] = "Happy 8) Codings";
char str_2[] = " Code Examples";
char ch_1 = 'b', ch_2 = 'T';
if (strchr(str, ch_1) != NULL){
cout << ch_1 << " " << "is present in string" << endl;
}
else{
cout << ch_1 << " " << "is not present in string" << endl;
}
if (strchr(str, ch_2) != NULL){
cout << ch_2 << " " << "is present in string" << endl;
strcat(str, str_2);
cout<<"String after concatenation is : "<<str;
}
else{
cout << ch_2 <<" " << "is not present in string" << endl;
}
return 0;
}
gotoxy() Function in C++
Positions cursor in text window. The gotoxy() function places the cursor at the desired location on the screen. This means it is possible to change the cursor location on the screen using the gotoxy() function. It is basically used to print text wherever the cursor is moved.
If the coordinates are in any way invalid the call to gotoxy is ignored. Neither argument to gotoxy can be zero.
Syntax for gotoxy() Function in C++
void gotoxy(int x, int y);
x
X coordinate of the position where we want to place the cursor.
y
Y coordinate of the position where we want to place the cursor.
This function does not return any value.
Do not use this function for Win32s or Win32 GUI applications.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/* The gotoxy() function places the cursor at the desired location on the screen. This means it is possible to change the cursor location on the screen using the gotoxy() function. It is basically used to print text wherever the cursor is moved. */
// Description: prints grid at given origin (xPos, yPos)
// Arguments:
// xPos - x coordinate of origin
// yPos - y coordinate of origin
void Grid::print(int xPos, int yPos){
#ifdef EN_PRINT
for(int i = 0;i < GRID_LENGTH;i++){
for(int j = 0;j < GRID_LENGTH;j++){
int x = xPos + 6 * j;
int y = yPos + 2 * i;
gotoXY(x,y);
std::cout<<" ";
gotoXY(x,y);
std::cout<<m_data[i*GRID_LENGTH + j];
}
}
#endif
}
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()
}
sound() Function in C++
Our system can create various sounds on different frequencies. The sound() is very useful as it can create very nice music with the help of programming and our user can enjoy music during working in out the program.
Sound function produces the sound of a specified frequency. Used for adding music to a C++ program.
Syntax for sound() Function in C++
void sound(unsigned frequency);
frequency
the frequency of the sound
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/* sound() function produces the sound of a specified frequency. */
int k;
//loop to increment the value of a till 100.
for ( k = 1 ; a <= 100 ; a = k++ )
{
//calling the function for producing
//the sound of value a.
sound(a);
//delay the sound 10 miliseconds.
delay(10);
}
// function to stop the system sound.
nosound();
return 0;
C++ Program to find a search sequence using Binary search. Implement the "binary search" to find the first value of search sequence. It is there, compare remaining item 'Sequentially'
Program ask to the user to enter any number in Hexadecimal to convert it into octal, then display the result on the screen: Here first we will convert the entered hexadecimal number
For a general weighted graph, we calculate single source shortest distances in "O(VE)" time using 'Bellman-Ford Algorithm'. For a graph with no negative weights, we can do
In C++, "Constructor" is automatically called when object ("instance of class") create. It is 'special member function' of the class. It has same name of class, must be public member