Happy Codings - Programming Code Examples
Html Css Web Design Sample Codes CPlusPlus Programming Sample Codes JavaScript Programming Sample Codes C Programming Sample Codes CSharp Programming Sample Codes Java Programming Sample Codes Php Programming Sample Codes Visual Basic Programming Sample Codes

C++ Programming Code Examples

C++ > Beginners Lab Assignments Code Examples

Local Variables - in C++ programming language

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/* Local Variables - in C++ programming language Global variables are accessible in full file. But local variables are not accessible in full file. The local variable's scope is between the block of instruction that is defined between "{" and "}". Take a look on this example: */ int main() { { double price = 4.0, height = 5.1, length = 3.4; cout << "Price is " << price << endl; cout << "Length is " << length << endl; cout << "Height is " << height << endl; } weight = 3; //Now weight is equal to 3 cin.ignore(); return 0; }
Standard Output Stream (cout) in C++
The cout is a predefined object of ostream class. It is connected with the standard output device, which is usually a display screen. The cout is used in conjunction with stream insertion operator (<<) to display the output on a console. On most program environments, the standard output by default is the screen, and the C++ stream object defined to access it is cout.
Syntax for cout in C++
cout << var_name; //or cout << "Some String";
The syntax of the cout object in C++: cout << var_name; Or cout << "Some String";
is the insertion operator
is usually a variable, but can also be an array element or elements of containers like vectors, lists, maps, etc. The "c" in cout refers to "character" and "out" means "output". Hence cout means "character output". The cout object is used along with the insertion operator << in order to display a stream of characters. The << operator can be used more than once with a combination of variables, strings, and manipulators. cout is used for displaying data on the screen. The operator << called as insertion operator or put to operator. The Insertion operator can be overloaded. Insertion operator is similar to the printf() operation in C. cout is the object of ostream class. Data flow direction is from variable to output device. Multiple outputs can be displayed using cout.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/* standard output stream (cout) in C++ language */ #include <iostream> using namespace std; int main() { string str = "Do not interrupt me"; char ch = 'm'; // use cout with write() cout.write(str,6); cout << endl; // use cout with put() cout.put(ch); return 0; }
Assignment Operators in C++
As the name already suggests, these operators help in assigning values to variables. These operators help us in allocating a particular value to the operands. The main simple assignment operator is '='. We have to be sure that both the left and right sides of the operator must have the same data type. We have different levels of operators. Assignment operators are used to assign the value, variable and function to another variable. Assignment operators in C are some of the C Programming Operator, which are useful to assign the values to the declared variables. Let's discuss the various types of the assignment operators such as =, +=, -=, /=, *= and %=. The following table lists the assignment operators supported by the C language:
Simple assignment operator. Assigns values from right side operands to left side operand
Add AND assignment operator. It adds the right operand to the left operand and assign the result to the left operand.
Subtract AND assignment operator. It subtracts the right operand from the left operand and assigns the result to the left operand.
Multiply AND assignment operator. It multiplies the right operand with the left operand and assigns the result to the left operand.
Divide AND assignment operator. It divides the left operand with the right operand and assigns the result to the left operand.
Modulus AND assignment operator. It takes modulus using two operands and assigns the result to the left operand.
Left shift AND assignment operator.
Right shift AND assignment operator.
Bitwise AND assignment operator.
Bitwise exclusive OR and assignment operator.
Bitwise inclusive OR and assignment operator.
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
/* Assignment operators are used to assigning value to a variable. The left side operand of the assignment operator is a variable and right side operand of the assignment operator is a value. The value on the right side must be of the same data-type of the variable on the left side otherwise the compiler will raise an error. */ // C++ program to demonstrate working of Assignment operators #include <iostream> using namespace std; int main() { // Assigning value 10 to a // using "=" operator int a = 10; cout << "Value of a is "<<a<<"\n"; // Assigning value by adding 10 to a // using "+=" operator a += 10; cout << "Value of a is "<<a<<"\n"; // Assigning value by subtracting 10 from a // using "-=" operator a -= 10; cout << "Value of a is "<<a<<"\n"; // Assigning value by multiplying 10 to a // using "*=" operator a *= 10; cout << "Value of a is "<<a<<"\n"; // Assigning value by dividing 10 from a // using "/=" operator a /= 10; cout << "Value of a is "<<a<<"\n"; return 0; }
Return Statement in C++
A return statement ends the processing of the current function and returns control to the caller of the function. A value-returning function should include a return statement, containing an expression. If an expression is not given on a return statement in a function declared with a non-void return type, the compiler issues an error message. If the data type of the expression is different from the function return type, conversion of the return value takes place as if the value of the expression were assigned to an object with the same function return type.
Syntax for Return Statement in C++
For a function of return type void, a return statement is not strictly necessary. If the end of such a function is reached without encountering a return statement, control is passed to the caller as if a return statement without an expression were encountered. In other words, an implicit return takes place upon completion of the final statement, and control automatically returns to the calling function. If a return statement is used, it must not contain an expression. The following are examples of return statements:
return; /* Returns no value */ return result; /* Returns the value of result */ return 1; /* Returns the value 1 */ return (x * x); /* Returns the value of x * 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
/* illustrate Methods returning a value using return statement in C++ code example */ #include <iostream> using namespace std; // non-void return type // function to calculate sum int SUM(int a, int b) { int s1 = a + b; // method using the return // statement to return a value return s1; } // Driver method int main() { int num1 = 10; int num2 = 10; int sum_of = SUM(num1, num2); cout << "The sum is " << sum_of; 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 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 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; }
Comments in C++
The C++ comments are statements that are not executed by the compiler. The comments in C++ programming can be used to provide explanation of the code, variable, method or class. If we write comments on our code, it will be easier for us to understand the code in the future. Also, it will be easier for your fellow developers to understand the code. By the help of comments, you can hide the program code also. There are two types of comments in C++: • Single Line comment • Multi Line comment
Syntax for Single Line Comment in C++
/* This is a comment */
The single line comment starts with // (double slash).
Syntax for Multi Line Comment in C++
/* C++ comments can also * span multiple lines */
C++ multi line comment is used to comment multiple lines of code. It is surrounded by slash and asterisk (/* ..... */). Comments shouldn't be the substitute for a way to explain poorly written code in English. We should always write well-structured and self-explanatory code. And, then use comments.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/* program to illustrate use comments in C++ language */ #include <ostream> using namespace std; int main() { int x = 11; // x is a variable cout<<x<<"\n"; /* declare and print variable in C++ */ int x = 35; cout<<x<<"\n"; // This is a comment cout << "Hello World!"; /* Multi-line Comments in C++ */ }
Basic Ios Library ignore() Function in C++
Extract and discard characters. Extracts characters from the input sequence and discards them, until either n characters have been extracted, or one compares equal to delim. The function also stops extracting characters if the end-of-file is reached. If this is reached prematurely (before either extracting n characters or finding delim), the function sets the eofbit flag. 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.
Syntax for Basic Ios ignore() Function in C++
#include <iostream> istream& ignore (streamsize n = 1, int delim = EOF);
Maximum number of characters to extract (and ignore). If this is exactly numeric_limits<streamsize>::max(), there is no limit: As many characters are extracted as needed until delim (or the end-of-file) is found. streamsize is a signed integral type.
Delimiting character: The function stops extracting characters as soon as an extracted character compares equal to this. Note that the delimiting character is extracted, and thus the next input operation will continue on the character that follows it (if any). If this is the end-of-file value (EOF), no character will compare equal, and thus exactly n characters will be discarded (unless the function fails or the end-of-file is reached). 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: The construction of sentry failed (such as when the stream state was not good before the call). • 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 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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
/* basic_istream::ignore is used to extracts characters from the input sequence and discards them, until either n characters have been extracted, or one compares equal to delim. */ /* Extracts and discards characters from the input stream until and including delim by basic_istream::ignore function code example. */ #include <bits/stdc++.h> using namespace std; // Driver Code int main() { // Input String istringstream input( "12\n" "It is a string\n" "14\n"); for (;;) { int n; // Taking input streamed string input >> n; // Check for end of file or if // any bad bit occurs if (input.eof() || input.bad()) { break; } // If any failbit occurs else if (input.fail()) { // Clear the input input.clear(); // Use ignore to stream the given // input as per delimeter '\n' input.ignore( numeric_limits<streamsize>::max(), '\n'); } // Else print the integer in // the string else { cout << n << '\n'; } } return 0; }

Matrix addition is the "operation of adding" 2 matrices by adding the corresponding entries together. 2 dimensional array, represented in the form of "rows and columns", also suitable
In this program, "enter the size "of 2 matrix at first. To multiply two matrices, the number of columns of first matrix should be equal to the "number of rows" to second matrix. C++ Code
Return true if "empty"; else false. Remove all items. Return position to prior to first. Return "first position". Insert x after "current iterator" position p. Return position that views. ListItr
To convert binary to hexadecimal in C++, you have to ask to the user to "enter any number" in binary to convert it into hexadecimal, then display the equivalent hexadecimal value on
'C++ program' in which user enter a number, program reverse it and display the reversed number on the console. If the 'input number' is 12345 Then reversed number will be 54321