## Python || Simple Math Using Int & Float

This page will display the use of int and float data types. Since python is a flexible programming language, variable data types do not need to be explicitly declared like in C/C++/Java, but they still exist within the grand scheme of things.

==== ADDING TWO NUMBERS TOGETHER ====

To add two numbers together, you will have to first declare your variables by doing something like this.

``` #1 - Adding 2 Numbers Together Python # ============================================================================= # Author: Kenneth Perkins # Date: May 29, 2013 # Updated: Feb 16, 2021 # Taken From: http://programmingnotes.org/ # File: addition.py # Description: Demonstrates adding numbers together # ============================================================================= def main(): # declare variables # NOTE: data types do not need to be declared num1 = 0; num2 = 0; total = 0; # in Python, input is automatically cast as strings # so we convert everything to integers in order to do math num1 = int(input("Please enter the first number: ")) num2 = int(input("Please enter the second number: ")) # calculate the sum of the two numbers here total = num1 + num2 # display data to the screen. The argument list is # similar to that of the "printf" function in C/C++ print("The sum of %d and %d is: %d" % (num1, num2, total)) if __name__ == "__main__": main() # http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930 # =============================================================================#    Author: Kenneth Perkins#    Date:   May 29, 2013#    Updated: Feb 16, 2021#    Taken From: http://programmingnotes.org/#    File:  addition.py#    Description: Demonstrates adding numbers together# =============================================================================def main():    # declare variables    # NOTE: data types do not need to be declared    num1 = 0;    num2 = 0;    total = 0;     # in Python, input is automatically cast as strings    # so we convert everything to integers in order to do math    num1 = int(input("Please enter the first number: "))    num2 = int(input("Please enter the second number: "))     # calculate the sum of the two numbers here    total = num1 + num2     # display data to the screen. The argument list is    # similar to that of the "printf" function in C/C++    print("The sum of %d and %d is: %d" % (num1, num2, total)) if __name__ == "__main__":    main()# http://programmingnotes.org/ ```

Notice in lines 12-14, I declared my variables, giving them a name. You can name your variables anything you want, with a rule of thumb as naming them something meaningful to your code (i.e avoid giving your variables arbitrary names like “x” or “y”). In line 22 the actual math process is taking place, storing the sum of “num1” and “num2” in a variable called “total.” I also initialized my variables to zero. You should always initialize your variables before you use them.

The above code should give you the following output:

```Please enter the first number: 25 Please enter the second number: 1 The sum of 25 and 1 is: 26```

==== SUBTRACTING TWO NUMBERS ====

Subtracting two numbers works the same way as the above code, and we would only need to edit the above code in one place to achieve that. In line 22, replace the addition symbol with a subtraction sign, and you should have something like this:

``` #2 - Subtracting 2 Numbers Together Python # ============================================================================= # Author: Kenneth Perkins # Date: May 29, 2013 # Updated: Feb 16, 2021 # Taken From: http://programmingnotes.org/ # File: subtraction.py # Description: Demonstrates subtracting numbers together # ============================================================================= def main(): # declare variables # NOTE: data types do not need to be declared num1 = 0; num2 = 0; total = 0; # in Python, input is automatically cast as strings # so we convert everything to integers in order to do math num1 = int(input("Please enter the first number: ")) num2 = int(input("Please enter the second number: ")) # calculate the difference of the two numbers here total = num1 - num2 # display data to the screen. print("The difference between %d and %d is: %d" % (num1, num2, total)) if __name__ == "__main__": main() # http://programmingnotes.org/ 1234567891011121314151617181920212223242526272829 # =============================================================================#    Author: Kenneth Perkins#    Date:   May 29, 2013#    Updated: Feb 16, 2021#    Taken From: http://programmingnotes.org/#    File:  subtraction.py#    Description: Demonstrates subtracting numbers together# =============================================================================def main():    # declare variables    # NOTE: data types do not need to be declared    num1 = 0;    num2 = 0;    total = 0;     # in Python, input is automatically cast as strings    # so we convert everything to integers in order to do math    num1 = int(input("Please enter the first number: "))    num2 = int(input("Please enter the second number: "))     # calculate the difference of the two numbers here    total = num1 - num2     # display data to the screen.    print("The difference between %d and %d is: %d" % (num1, num2, total)) if __name__ == "__main__":    main()# http://programmingnotes.org/ ```

The above code should give you the following output:

```Please enter the first number: 25 Please enter the second number: 1 The difference between 25 and 1 is: 24 ```

==== MULTIPLYING TWO NUMBERS ====

This can be achieved the same way as the 2 previous methods, simply by editing line 22, and replacing the designated math operator with the star symbol “*”.

``` #3 - Multiplying 2 Numbers Together Python # ============================================================================= # Author: Kenneth Perkins # Date: May 29, 2013 # Updated: Feb 16, 2021 # Taken From: http://programmingnotes.org/ # File: multiplication.py # Description: Demonstrates multiplying numbers together # ============================================================================= def main(): # declare variables # NOTE: data types do not need to be declared num1 = 0; num2 = 0; total = 0; # in Python, input is automatically cast as strings # so we convert everything to integers in order to do math num1 = int(input("Please enter the first number: ")) num2 = int(input("Please enter the second number: ")) # calculate the product of the two numbers here total = num1 * num2 # display data to the screen. print("The product of %d and %d is: %d" % (num1, num2, total)) if __name__ == "__main__": main() # http://programmingnotes.org/ 1234567891011121314151617181920212223242526272829 # =============================================================================#    Author: Kenneth Perkins#    Date:   May 29, 2013#    Updated: Feb 16, 2021#    Taken From: http://programmingnotes.org/#    File:  multiplication.py#    Description: Demonstrates multiplying numbers together# =============================================================================def main():    # declare variables    # NOTE: data types do not need to be declared    num1 = 0;    num2 = 0;    total = 0;     # in Python, input is automatically cast as strings    # so we convert everything to integers in order to do math    num1 = int(input("Please enter the first number: "))    num2 = int(input("Please enter the second number: "))     # calculate the product of the two numbers here    total = num1 * num2     # display data to the screen.    print("The product of %d and %d is: %d" % (num1, num2, total)) if __name__ == "__main__":    main()# http://programmingnotes.org/ ```

The above code should give you the following output:

```Please enter the first number: 8 Please enter the second number: 24 The product of 8 and 24 is: 192```

==== DIVIDING TWO NUMBERS TOGETHER ====

The resulting code will basically be the same as the other previous three, only instead of our variables being of type int within the print statement, they will be of type float.

``` #4 - Dividing 2 Numbers Together Python # ============================================================================= # Author: Kenneth Perkins # Date: May 29, 2013 # Updated: Feb 16, 2021 # Taken From: http://programmingnotes.org/ # File: division.py # Description: Demonstrates dividing numbers together # ============================================================================= def main(): # declare variables # NOTE: data types do not need to be declared num1 = 0; num2 = 0; total = 0; # in Python, input is automatically cast as strings # so we convert everything to integers in order to do math num1 = int(input("Please enter the first number: ")) num2 = int(input("Please enter the second number: ")) # calculate the quotient of the two numbers here total = num1 / num2 # display data to the screen. print("The quotient of %d and %d is: %f" % (num1, num2, total)) if __name__ == "__main__": main() # http://programmingnotes.org/ 1234567891011121314151617181920212223242526272829 # =============================================================================#    Author: Kenneth Perkins#    Date:   May 29, 2013#    Updated: Feb 16, 2021#    Taken From: http://programmingnotes.org/#    File:  division.py#    Description: Demonstrates dividing numbers together# =============================================================================def main():    # declare variables    # NOTE: data types do not need to be declared    num1 = 0;    num2 = 0;    total = 0;     # in Python, input is automatically cast as strings    # so we convert everything to integers in order to do math    num1 = int(input("Please enter the first number: "))    num2 = int(input("Please enter the second number: "))     # calculate the quotient of the two numbers here    total = num1 / num2     # display data to the screen.    print("The quotient of %d and %d is: %f" % (num1, num2, total)) if __name__ == "__main__":    main()# http://programmingnotes.org/ ```

The above code should give you the following output:

```Please enter the first number: 1 Please enter the second number: 25 The quotient of 1 and 25 is: 0.040000 ```

==== MODULUS ====

If you wanted to capture the remainder of the quotient you calculated from the above code, you would use the modulus operator (%).

From the above code, you would only need to edit line 22, from division, to modulus.

``` #5 - Getting the Remainder of 2 Numbers Python # ============================================================================= # Author: Kenneth Perkins # Date: May 29, 2013 # Updated: Feb 16, 2021 # Taken From: http://programmingnotes.org/ # File: modulus.py # Description: Demonstrates performing modulus on numbers # ============================================================================= def main(): # declare variables # NOTE: data types do not need to be declared num1 = 0; num2 = 0; total = 0; # in Python, input is automatically cast as strings # so we convert everything to integers in order to do math num1 = int(input("Please enter the first number: ")) num2 = int(input("Please enter the second number: ")) # calculate the mod of the two numbers here total = num1 % num2 # display data to the screen. print("%d mod %d is: %d" % (num1, num2, total)) if __name__ == "__main__": main() # http://programmingnotes.org/ 1234567891011121314151617181920212223242526272829 # =============================================================================#    Author: Kenneth Perkins#    Date:   May 29, 2013#    Updated: Feb 16, 2021#    Taken From: http://programmingnotes.org/#    File:  modulus.py#    Description: Demonstrates performing modulus on numbers# =============================================================================def main():    # declare variables    # NOTE: data types do not need to be declared    num1 = 0;    num2 = 0;    total = 0;     # in Python, input is automatically cast as strings    # so we convert everything to integers in order to do math    num1 = int(input("Please enter the first number: "))    num2 = int(input("Please enter the second number: "))     # calculate the mod of the two numbers here    total = num1 % num2     # display data to the screen.    print("%d mod %d is: %d" % (num1, num2, total)) if __name__ == "__main__":    main()# http://programmingnotes.org/ ```

The above code should give you the following output:

```Please enter the first number: 1 Please enter the second number: 25 1 mod 25 is: 1 ```

## C++ || Snippet – How To Convert A Decimal Number Into Binary

This page will demonstrate how to convert a decimal number (i.e a whole number) into its binary equivalent. So for example, if the decimal number of 26 was entered into the program, it would display the converted binary value of 11010.

REQUIRED KNOWLEDGE FOR THIS SNIPPET

```How To Count In Binary The "Long" Datatype - What Is It? While Loops Online Binary to Decimal Converter - Verify For Correct Results How To Reverse A String ```

If you are looking for sample code which converts binary to decimal, check back here soon!

``` Convert A Decimal Number Into Binary C++ #include <iostream> #include <string> #include <algorithm> using namespace std; // function prototype string DecToBin(long long decNum); int main() { // declare variables long long decNum = 0; string binaryNum=""; // use a string instead of an int to avoid // overflow, because binary numbers can grow large quick cout<<"Please enter an integer value: "; cin >> decNum; if(decNum < 0) { binaryNum = "-"; } // call function to convert decimal to binary binaryNum += DecToBin(decNum); // display data to user cout<<"nThe integer value of "<<decNum<<" = "<<binaryNum<<" in binary"<<endl; return 0; } string DecToBin(long long decNum) { string binary = ""; // use this string to save the binary number if(decNum < 0) // if input is a neg number, make it positive { decNum *= -1; } // converts decimal to binary using division and modulus while(decNum > 0) { binary += (decNum % 2)+'0'; // convert int to char decNum /= 2; } // reverse the string reverse(binary.begin(), binary.end()); return binary; }// http://programmingnotes.org/ 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253 #include <iostream>#include <string>#include <algorithm> using namespace std; // function prototypestring DecToBin(long long decNum); int main(){ // declare variables long long decNum = 0; string binaryNum=""; // use a string instead of an int to avoid   // overflow, because binary numbers can grow large quick  cout<<"Please enter an integer value: "; cin >> decNum;  if(decNum < 0) { binaryNum = "-"; }  // call function to convert decimal to binary binaryNum += DecToBin(decNum);  // display data to user cout<<"nThe integer value of "<<decNum<<" = "<<binaryNum<<" in binary"<<endl;  return 0;} string DecToBin(long long decNum){ string binary = ""; // use this string to save the binary number  if(decNum < 0) // if input is a neg number, make it positive {               decNum *= -1; }                     // converts decimal to binary using division and modulus while(decNum > 0) { binary += (decNum % 2)+'0'; // convert int to char decNum /= 2; }  // reverse the string reverse(binary.begin(), binary.end());  return binary;}// http://programmingnotes.org/ ```

The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output
Note: The code was compiled 3 separate times to display different output

`====== RUN 1 ======`

``` Please enter an integer value: 1987 The integer value of 1987 = 11111000011 in binary ====== RUN 2 ====== Please enter an integer value: -26 The integer value of -26 = -11010 in binary ====== RUN 3 ====== Please enter an integer value: 12345678910 ```

```The integer value of 12345678910 = 1011011111110111000001110000111110 in binary ```

## Java || Snippet – How To Do Simple Math Using Integer Arrays

This page will consist of simple programs which demonstrate the process of doing simple math with numbers that are stored in an integer array.

REQUIRED KNOWLEDGE FOR THIS SNIPPET

```Integer Arrays The "Random" Class For Loops Assignment Operators - Simple Math Operations Custom Setw/Setfill In Java ```

Note: In all of the examples on this page, a random number generator was used to place numbers into the array. If you do not know how to obtain data from the user, or if you do not know how to insert data into an array, click here for a demonstration.

The first code snippet will demonstrate how to add numbers together which are stored in an integer array. This example uses the “+=” assignment operator.

``` #1 - Addition Using An Int Array Java import java.util.Random; public class Addition { // global variable declaration static Random rand = new Random(); static final int NUM_INTS = 12; // const int allocating space for the array public static void main(String[] args) { // declare & initialize variables int[] arry = new int[NUM_INTS]; // array is initialized using a const variable int totalSum = 0; System.out.println("Welcome to My Programming Notes' Java Program.n"); // place random numbers into the array for(int x = 0; x < NUM_INTS; ++x) { arry[x] = rand.nextInt(100)+1; } System.out.println("Original array values:"); // Display the original array values for(int x = 0; x < NUM_INTS; ++x) { System.out.print(arry[x]+" "); } // creates a line seperator if user wants to enter new data System.out.println(""); setwRF("", 50, '-'); System.out.print("nThe sum of the items in the array is: "); // Find the sum of the values in the array for(int x = 0; x < NUM_INTS; ++x) { // the code below literally means // totalSum = totalSum + arry[x] totalSum += arry[x]; } // after the calculations are complete, display the total to the user System.out.println(totalSum); }// end of main public static void setwRF(String str, int width, char fill) { System.out.print(str); for (int x = str.length(); x < width; ++x) { System.out.print(fill); } }// end of setwRF }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 import java.util.Random; public class Addition{ // global variable declaration static Random rand = new Random(); static final int NUM_INTS = 12; // const int allocating space for the array public static void main(String[] args) { // declare & initialize variables int[] arry = new int[NUM_INTS]; // array is initialized using a const variable int totalSum = 0; System.out.println("Welcome to My Programming Notes' Java Program.n"); // place random numbers into the array for(int x = 0; x < NUM_INTS; ++x) { arry[x] = rand.nextInt(100)+1; } System.out.println("Original array values:"); // Display the original array values for(int x = 0; x < NUM_INTS; ++x) { System.out.print(arry[x]+"  "); } // creates a line seperator if user wants to enter new data System.out.println(""); setwRF("", 50, '-'); System.out.print("nThe sum of the items in the array is: "); // Find the sum of the values in the array for(int x = 0; x < NUM_INTS; ++x) { // the code below literally means // totalSum = totalSum + arry[x] totalSum += arry[x]; } // after the calculations are complete, display the total to the user System.out.println(totalSum); }// end of main public static void setwRF(String str, int width, char fill) { System.out.print(str); for (int x = str.length(); x < width; ++x) { System.out.print(fill);     } }// end of setwRF }// http://programmingnotes.org/ ```

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

SAMPLE OUTPUT

`Welcome to My Programming Notes' Java Program.`

``` ```

```Original array values: 22 26 41 89 35 90 15 99 85 5 95 86 -------------------------------------------------- The sum of the items in the array is: 688 ```

===== SUBTRACTION =====

The second code snippet will demonstrate how to subtract numbers which are stored in an integer array. This example uses the “-=” assignment operator.

``` #2 - Subtraction Using An Int Array Java import java.util.Random; public class Subtraction { // global variable declaration static Random rand = new Random(); static final int NUM_INTS = 12; // const int allocating space for the array public static void main(String[] args) { // declare & initialize variables int[] arry = new int[NUM_INTS]; // array is initialized using a const variable int totalSum = 0; System.out.println("Welcome to My Programming Notes' Java Program.n"); // place random numbers into the array for(int x = 0; x < NUM_INTS; ++x) { arry[x] = rand.nextInt(100)+1; } System.out.println("Original array values:"); // Display the original array values for(int x = 0; x < NUM_INTS; ++x) { System.out.print(arry[x]+" "); } // creates a line seperator if user wants to enter new data System.out.println(""); setwRF("", 50, '-'); System.out.print("nThe difference of the items in the array is: "); // Find the sum of the values in the array for(int x = 0; x < NUM_INTS; ++x) { // the code below literally means // totalSum = totalSum - arry[x] totalSum -= arry[x]; } // after the calculations are complete, display the total to the user System.out.println(totalSum); }// end of main public static void setwRF(String str, int width, char fill) { System.out.print(str); for (int x = str.length(); x < width; ++x) { System.out.print(fill); } }// end of setwRF }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 import java.util.Random; public class Subtraction{ // global variable declaration static Random rand = new Random(); static final int NUM_INTS = 12; // const int allocating space for the array public static void main(String[] args) { // declare & initialize variables int[] arry = new int[NUM_INTS]; // array is initialized using a const variable int totalSum = 0; System.out.println("Welcome to My Programming Notes' Java Program.n"); // place random numbers into the array for(int x = 0; x < NUM_INTS; ++x) { arry[x] = rand.nextInt(100)+1; } System.out.println("Original array values:"); // Display the original array values for(int x = 0; x < NUM_INTS; ++x) { System.out.print(arry[x]+"  "); } // creates a line seperator if user wants to enter new data System.out.println(""); setwRF("", 50, '-'); System.out.print("nThe difference of the items in the array is: "); // Find the sum of the values in the array for(int x = 0; x < NUM_INTS; ++x) { // the code below literally means // totalSum = totalSum - arry[x] totalSum -= arry[x]; } // after the calculations are complete, display the total to the user System.out.println(totalSum); }// end of main public static void setwRF(String str, int width, char fill) { System.out.print(str); for (int x = str.length(); x < width; ++x) { System.out.print(fill);     } }// end of setwRF }// http://programmingnotes.org/ ```

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

SAMPLE OUTPUT

`Welcome to My Programming Notes' Java Program.`

``` ```

```Original array values: 99 92 91 26 1 52 98 62 51 22 64 65 -------------------------------------------------- The difference of the items in the array is: -723 ```

===== MULTIPLICATION =====

The third code snippet will demonstrate how to multiply numbers which are stored in an integer array. This example uses the “*=” assignment operator.

``` #3 - Multiplication Using An Int Array Java import java.util.Random; public class Multiplication { // global variable declaration static Random rand = new Random(); static final int NUM_INTS = 12; // const int allocating space for the array public static void main(String[] args) { // declare & initialize variables int[] arry = new int[NUM_INTS]; // array is initialized using a const variable int totalSum = 1; System.out.println("Welcome to My Programming Notes' Java Program.n"); // place random numbers into the array for(int x = 0; x < NUM_INTS; ++x) { arry[x] = rand.nextInt(100)+1; } System.out.println("Original array values:"); // Display the original array values for(int x = 0; x < NUM_INTS; ++x) { System.out.print(arry[x]+" "); } // creates a line seperator if user wants to enter new data System.out.println(""); setwRF("", 50, '-'); System.out.print("nThe product of the items in the array is: "); // Find the sum of the values in the array for(int x = 0; x < NUM_INTS; ++x) { // the code below literally means // totalSum = totalSum * arry[x] totalSum *= arry[x]; } // after the calculations are complete, display the total to the user System.out.println(totalSum); }// end of main public static void setwRF(String str, int width, char fill) { System.out.print(str); for (int x = str.length(); x < width; ++x) { System.out.print(fill); } }// end of setwRF }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 import java.util.Random; public class Multiplication{ // global variable declaration static Random rand = new Random(); static final int NUM_INTS = 12; // const int allocating space for the array public static void main(String[] args) { // declare & initialize variables int[] arry = new int[NUM_INTS]; // array is initialized using a const variable int totalSum = 1; System.out.println("Welcome to My Programming Notes' Java Program.n"); // place random numbers into the array for(int x = 0; x < NUM_INTS; ++x) { arry[x] = rand.nextInt(100)+1; } System.out.println("Original array values:"); // Display the original array values for(int x = 0; x < NUM_INTS; ++x) { System.out.print(arry[x]+"  "); } // creates a line seperator if user wants to enter new data System.out.println(""); setwRF("", 50, '-'); System.out.print("nThe product of the items in the array is: "); // Find the sum of the values in the array for(int x = 0; x < NUM_INTS; ++x) { // the code below literally means // totalSum = totalSum * arry[x] totalSum *= arry[x]; } // after the calculations are complete, display the total to the user System.out.println(totalSum); }// end of main public static void setwRF(String str, int width, char fill) { System.out.print(str); for (int x = str.length(); x < width; ++x) { System.out.print(fill);     } }// end of setwRF }// http://programmingnotes.org/ ```

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

SAMPLE OUTPUT

`Welcome to My Programming Notes' Java Program.`

``` ```

```Original array values: 95 63 32 19 93 83 71 35 32 37 66 95 -------------------------------------------------- The product of the items in the array is: 494770176 ```

===== DIVISION =====

The fourth code snippet will demonstrate how to divide numbers which are stored in an integer array. This example uses the “/=” assignment operator.

``` #4 - Division Using An Int Array Java import java.util.Random; public class Division { // global variable declaration static Random rand = new Random(); static final int NUM_INTS = 12; // const int allocating space for the array public static void main(String[] args) { // declare & initialize variables int[] arry = new int[NUM_INTS]; // array is initialized using a const variable double totalSum = 1; System.out.println("Welcome to My Programming Notes' Java Program.n"); // place random numbers into the array for(int x = 0; x < NUM_INTS; ++x) { arry[x] = rand.nextInt(100)+1; } System.out.println("Original array values:"); // Display the original array values for(int x = 0; x < NUM_INTS; ++x) { System.out.print(arry[x]+" "); } // creates a line seperator if user wants to enter new data System.out.println(""); setwRF("", 50, '-'); System.out.print("nThe quotient of the items in the array is: "); // Find the sum of the values in the array for(int x = 0; x < NUM_INTS; ++x) { // the code below literally means // totalSum = totalSum / arry[x] totalSum /= arry[x]; } // after the calculations are complete, display the total to the user System.out.println(totalSum); }// end of main public static void setwRF(String str, int width, char fill) { System.out.print(str); for (int x = str.length(); x < width; ++x) { System.out.print(fill); } }// end of setwRF }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 import java.util.Random; public class Division{ // global variable declaration static Random rand = new Random(); static final int NUM_INTS = 12; // const int allocating space for the array public static void main(String[] args) { // declare & initialize variables int[] arry = new int[NUM_INTS]; // array is initialized using a const variable double totalSum = 1; System.out.println("Welcome to My Programming Notes' Java Program.n"); // place random numbers into the array for(int x = 0; x < NUM_INTS; ++x) { arry[x] = rand.nextInt(100)+1; } System.out.println("Original array values:"); // Display the original array values for(int x = 0; x < NUM_INTS; ++x) { System.out.print(arry[x]+"  "); } // creates a line seperator if user wants to enter new data System.out.println(""); setwRF("", 50, '-'); System.out.print("nThe quotient of the items in the array is: "); // Find the sum of the values in the array for(int x = 0; x < NUM_INTS; ++x) { // the code below literally means // totalSum = totalSum / arry[x] totalSum /= arry[x]; } // after the calculations are complete, display the total to the user System.out.println(totalSum); }// end of main public static void setwRF(String str, int width, char fill) { System.out.print(str); for (int x = str.length(); x < width; ++x) { System.out.print(fill);     } }// end of setwRF }// http://programmingnotes.org/ ```

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

SAMPLE OUTPUT

`Welcome to My Programming Notes' Java Program.`

``` ```

```Original array values: 28 85 90 52 1 64 93 85 4 22 4 28 -------------------------------------------------- The quotient of the items in the array is: 1.8005063061510687E-17 ```

## Java || Snippet – How To Convert A Decimal Number Into Binary

This page will demonstrate how to convert a decimal number (i.e a whole number) into its binary equivalent. So for example, if the decimal number of 25 was entered into the program, it would display the converted binary value of 11001.

REQUIRED KNOWLEDGE FOR THIS SNIPPET

```How To Count In Binary The "Long" Datatype - What Is It? Methods (A.K.A "Functions") - What Are They? While Loops Online Binary to Decimal Converter - Verify For Correct Results ```

If you are looking for sample code which converts binary to decimal, check back here soon!

``` Convert A Decimal Number Into Binary Java import java.util.Scanner; public class DecimalToBinary { // global variable declaration static Scanner cin = new Scanner(System.in); public static void main(String[] args) { // declare variables long decNum = 0; String binaryNum = ""; // use a string instead of an int to avoid // overflow, because binary numbers can grow large quick // display message to screen System.out.println("Welcome to My Programming Notes' Java Program.n"); // get decimal number from user System.out.print("Please enter an integer value: "); decNum = cin.nextLong(); if(decNum < 0) // if user inputs a neg number, make the binary num neg too { binaryNum = "-"; } // method call to convert decimal to binary binaryNum += DecToBin(decNum); // display data to user System.out.println("nThe integer value of "+ decNum + " = " + binaryNum + " in binary"); }// end of main public static String DecToBin(long decNum) { // use this string to save the binary number String binary = ""; if(decNum < 0) // if input is a neg number, make it positive { decNum *= -1; } // converts decimal to binary using division and modulus while(decNum > 0) { binary += (decNum % 2); decNum /= 2; } // return the reversed string to main return new StringBuffer(binary).reverse().toString(); } }// http://programmingnotes.org/ 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 import java.util.Scanner; public class DecimalToBinary{ // global variable declaration static Scanner cin = new Scanner(System.in); public static void main(String[] args) { // declare variables long decNum = 0; String binaryNum = ""; // use a string instead of an int to avoid                   // overflow, because binary numbers can grow large quick // display message to screen System.out.println("Welcome to My Programming Notes' Java Program.n"); // get decimal number from user System.out.print("Please enter an integer value: "); decNum = cin.nextLong(); if(decNum < 0) // if user inputs a neg number, make the binary num neg too { binaryNum = "-"; } // method call to convert decimal to binary binaryNum += DecToBin(decNum); // display data to user System.out.println("nThe integer value of "+ decNum + " = " + binaryNum + " in binary"); }// end of main  public static String DecToBin(long decNum) { // use this string to save the binary number String binary = ""; if(decNum < 0) // if input is a neg number, make it positive { decNum *= -1; } // converts decimal to binary using division and modulus while(decNum > 0) { binary += (decNum % 2); decNum /= 2; } // return the reversed string to main return new StringBuffer(binary).reverse().toString(); }}// http://programmingnotes.org/ ```

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output
Note: The code was compiled 3 separate times to display different output

`====== RUN 1 ======`

``` Welcome to My Programming Notes' Java Program. Please enter an integer value: 5 The integer value of 5 = 101 in binary ====== RUN 2 ====== Welcome to My Programming Notes' Java Program. Please enter an integer value: -25 The integer value of -25 = -11001 in binary ====== RUN 3 ====== Welcome to My Programming Notes' Java Program. Please enter an integer value: 12345678910 ```

```The integer value of 12345678910 = 1011011111110111000001110000111110 in binary ```

## Java || Find The Prime, Perfect & All Known Divisors Of A Number Using A For, While & Do/While Loop

This program was designed to better understand how to use different loops which are available in Java, as well as more practice using objects with classes.

This program first asks the user to enter a non negative number. After it obtains a non negative integer from the user, the program determines if the user obtained number is a prime number or not, aswell as determining if the user obtained number is a perfect number or not. After it obtains its results, the program will display to the screen if the user inputted number is prime/perfect number or not. The program will also display a list of all the possible divisors of the user obtained number via stdout.

REQUIRED KNOWLEDGE FOR THIS PROGRAM

```Class Objects - How TO Use Constructors - What Are They? Do/While Loop While Loop For Loop Modulus Basic Math - Prime Numbers Basic Math - Perfect Numbers Basic Math - Divisors ```

``` Is It Prime or Perfect? List All Possible Divisors Java import java.util.Scanner; public class PrimePerfectNums { // global variable declaration int userInput = 0; static Scanner cin = new Scanner(System.in); public PrimePerfectNums(int input) {// this is the constructor // give the global variable a value userInput = input; }// end of PrimePerfectNums public void CalcPrimePerfect() { // declare variables int divisor = 0; int sumOfDivisors = 0; System.out.print("nInput number: " + userInput); // for loop adds sum of all possible divisors for(int counter=1; counter <= userInput; ++counter) { divisor = (userInput % counter); if(divisor == 0) { // this will repeatedly add the found divisors together sumOfDivisors += counter; } } System.out.println(""); // uses the 'sumOfDivisors' variable from ^ above for loop to // check if 'userInput' is prime if(userInput == (sumOfDivisors - 1)) { System.out.print(userInput + " is a prime number."); } else { System.out.print(userInput + " is not a prime number."); } System.out.println(""); // uses the 'sumOfDivisors' variable from ^ above for loop to // check if 'userInput' is a perfect number if (userInput == (sumOfDivisors - userInput)) { System.out.print(userInput + " is a perfect number."); } else { System.out.print(userInput + " is not a perfect number."); } System.out.print("nDivisors of " + userInput + " are: "); // for loop lists all the possible divisors for the // 'userInput' variable by using the modulus operator for(int counter=1; counter <= userInput; ++counter) { divisor = (userInput % counter); if(divisor == 0 && counter !=userInput) { System.out.print(counter + ", "); } } System.out.print("and " + userInput); }// end of CalcPrimePerfect public static void main(String[] args) { // declare variables int input = 0; char response ='n'; do{ // this is the start of the do/while loop System.out.print("Enter a number: "); input = cin.nextInt(); // if the user inputs a negative number, do this code while(input < 0) { System.out.print("ntSorry, but the number entered is less " + "than the allowable limit.ntPlease try again....."); System.out.print("nnEnter an number: "); input = cin.nextInt(); } // entry point to class declaration PrimePerfectNums myClass = new PrimePerfectNums(input); // function call to obtain data using the number // which was passed from main to the constructor myClass.CalcPrimePerfect(); // asks user if they want to enter new data System.out.print("nntDo you want to input another number?(Y/N): "); response = cin.next().toLowerCase().charAt(0); System.out.println("---------------------------" + "---------------------------------"); }while(response =='y'); // ^ End of the do/while loop. As long as the user chooses // 'Y' the loop will keep going. // It stops when the user chooses the letter 'N' System.out.println("BYE!"); }// end of main }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113 import java.util.Scanner; public class PrimePerfectNums{ // global variable declaration int userInput = 0; static Scanner cin = new Scanner(System.in); public PrimePerfectNums(int input) {// this is the constructor // give the global variable a value userInput = input;  }// end of PrimePerfectNums public void CalcPrimePerfect() { // declare variables int divisor = 0; int sumOfDivisors = 0; System.out.print("nInput number: " + userInput); // for loop adds sum of all possible divisors for(int counter=1; counter <= userInput; ++counter) { divisor = (userInput % counter); if(divisor == 0) { // this will repeatedly add the found divisors together sumOfDivisors += counter; } } System.out.println(""); // uses the 'sumOfDivisors' variable from ^ above for loop to // check if 'userInput' is prime if(userInput == (sumOfDivisors - 1)) { System.out.print(userInput + " is a prime number."); } else { System.out.print(userInput + " is not a prime number."); } System.out.println(""); // uses the 'sumOfDivisors' variable from ^ above for loop to // check if 'userInput' is a perfect number if (userInput == (sumOfDivisors - userInput)) { System.out.print(userInput + " is a perfect number."); } else { System.out.print(userInput + " is not a perfect number."); } System.out.print("nDivisors of " + userInput + " are: "); // for loop lists all the possible divisors for the // 'userInput' variable by using the modulus operator for(int counter=1; counter <= userInput; ++counter) { divisor = (userInput % counter); if(divisor == 0 && counter !=userInput) { System.out.print(counter + ", "); } } System.out.print("and " + userInput); }// end of CalcPrimePerfect public static void main(String[] args) { // declare variables int input = 0; char response ='n'; do{ // this is the start of the do/while loop System.out.print("Enter a number: "); input = cin.nextInt(); // if the user inputs a negative number, do this code while(input < 0) { System.out.print("ntSorry, but the number entered is less " + "than the allowable limit.ntPlease try again....."); System.out.print("nnEnter an number: "); input = cin.nextInt(); } // entry point to class declaration PrimePerfectNums myClass = new PrimePerfectNums(input); // function call to obtain data using the number // which was passed from main to the constructor myClass.CalcPrimePerfect(); // asks user if they want to enter new data System.out.print("nntDo you want to input another number?(Y/N): "); response = cin.next().toLowerCase().charAt(0); System.out.println("---------------------------" + "---------------------------------"); }while(response =='y'); // ^ End of the do/while loop. As long as the user chooses // 'Y' the loop will keep going. // It stops when the user chooses the letter 'N' System.out.println("BYE!"); }// end of main }// http://programmingnotes.org/ ```

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output:

`Enter a number: 41`

``` Input number: 41 41 is a prime number. 41 is not a perfect number. Divisors of 41 are: 1, and 41 Do you want to input another number?(Y/N): y ------------------------------------------------------------ Enter a number: 496 Input number: 496 496 is not a prime number. 496 is a perfect number. Divisors of 496 are: 1, 2, 4, 8, 16, 31, 62, 124, 248, and 496 Do you want to input another number?(Y/N): y ------------------------------------------------------------ Enter a number: 1858 Input number: 1858 1858 is not a prime number. 1858 is not a perfect number. Divisors of 1858 are: 1, 2, 929, and 1858 Do you want to input another number?(Y/N): y ------------------------------------------------------------ Enter a number: -9 Sorry, but the number entered is less than the allowable limit. Please try again..... Enter an number: 12 Input number: 12 12 is not a prime number. 12 is not a perfect number. Divisors of 12 are: 1, 2, 3, 4, 6, and 12 ```

``` Do you want to input another number?(Y/N): n ------------------------------------------------------------ BYE! ```

## Java || Find The Average Using an Array – Omit Highest And Lowest Scores

This page will consist of two programs which calculates the average of a specific amount of numbers using an array.

REQUIRED KNOWLEDGE FOR BOTH PROGRAMS

```Double Data Type Final Variables Arrays For Loops Assignment Operators Basic Math - How To Find The Average ```

====== FIND THE AVERAGE USING AN ARRAY ======

The first program is fairly simple, and it was used to introduce the array concept. The program prompts the user to enter the total amount of numbers they want to find the average for, then the program displays the answer to them via stdout.

``` #1 - Find The Average Java import java.util.Scanner; public class FindTheAverage { // global variable declaration static Scanner cin = new Scanner(System.in); public static void main(String[] args) { // declare variables int numElems = 0; double sum = 0; double[] average = new double[100]; // declare array which has the ability to hold 100 elements // display message to screen System.out.println("Welcome to My Programming Notes' Java Program.n"); // determine how many numbers the user wants in the array System.out.print("How many numbers do you want to find the average for?: "); numElems = cin.nextInt(); System.out.println(""); // user enters data into array using a for loop // you can also use a while loop, but for loops are more common // when dealing with arrays for(int index=0; index < numElems; ++index) { System.out.print("Enter value #" +(index+1)+ ": "); average[index] = cin.nextDouble(); sum += average[index]; } // find the average. // Note: the expression below literally // means: sum = sum / numElems; sum /= numElems; System.out.println("nThe average of the " + numElems + " numbers is " + sum); }// end of main }// http://programmingnotes.org/ 1234567891011121314151617181920212223242526272829303132333435363738394041 import java.util.Scanner; public class FindTheAverage{ // global variable declaration static Scanner cin = new Scanner(System.in); public static void main(String[] args) { // declare variables int numElems = 0; double sum = 0; double[] average = new double[100]; // declare array which has the ability to hold 100 elements // display message to screen System.out.println("Welcome to My Programming Notes' Java Program.n"); // determine how many numbers the user wants in the array System.out.print("How many numbers do you want to find the average for?: "); numElems = cin.nextInt(); System.out.println(""); // user enters data into array using a for loop // you can also use a while loop, but for loops are more common // when dealing with arrays for(int index=0; index < numElems; ++index) { System.out.print("Enter value #" +(index+1)+ ": "); average[index] = cin.nextDouble(); sum += average[index]; } // find the average. // Note: the expression below literally // means: sum = sum / numElems; sum /= numElems; System.out.println("nThe average of the " + numElems + " numbers is " + sum); }// end of main}// http://programmingnotes.org/ ```

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

ARRAY
Notice the array declaration on line #13. The type of array being used in this program is a dynamic array, which has the ability to store up to 100 integer elements in the array. You can change the number of elements its able to store to a higher or lower number if you wish.

FOR LOOP
Lines 27-32 contains a for loop, which is used to actually store the data inside of the array. Without some type of loop, it is virtually impossible for the user to input data into the array; that is, unless you want to add 100 different println statements into your code asking the user to input data. Line 31 uses the assignment operator “+=” which gives us a running total of the data that is being inputted into the array. Note the loop only stores as many elements as the user so desires, so if the user only wants to input 3 numbers into the array, the for loop will only execute 3 times.

Once compiled, you should get this as your output:

`Welcome to My Programming Notes' Java Program.`

``` ```

```How many numbers do you want to find the average for?: 4 Enter value #1: 21 Enter value #2: 24 Enter value #3: 19 Enter value #4: 17 The average of the 4 numbers is 20.25 ```

====== FIND THE AVERAGE – OMIT HIGHEST AND LOWEST SCORES ======

The second program is really practical in a real world setting. We were asked to create a program for a fictional competition which had 6 judges. The 6 judges each gave a score of the performance for a competitor in a competition, (i.e a score of 1-10), and we were asked to find the average of those scores, omitting the highest/lowest results. The program was to store the scores into an array, display the scores back to the user via stdout, display the highest and lowest scores among the 6 obtained, display the average of the 6 scores, and finally display the average adjusted scores omitting the highest and lowest result.

``` #2 - Find The Average Omitting The Highest/Lowest Score Java import java.util.Scanner; public class FindOmittedAverage { // global variable declaration static Scanner cin = new Scanner(System.in); static final int NUM_JUDGES = 6; public static void main(String[] args) { // declare variables double highestScore = -999999; double lowestScore = 999999; double sumOfScores = 0; double avgScores = 0; double[] scores = new double[NUM_JUDGES]; // array is initialized using a final variable // display message to screen System.out.println("Welcome to My Programming Notes' Java Program.n"); System.out.print("Judges, enter one score each for the current competitor: "); // use a for loop to obtain data from user using the final variable for(int index=0; index < NUM_JUDGES; ++index) { // this puts data into the current array index scores[index] = cin.nextDouble(); // this calculates a running total of all the scores // adding each element in the array together sumOfScores += scores[index]; // if current score in the array index is bigger than the current 'highestScore' // value, then set 'highestScore' equal to the current value in the array if(scores[index] > highestScore) { highestScore = scores[index]; } // if current score in the array index is smaller than the current 'lowestScore' // value, then set 'lowestScore' equal to the current value in the array if(lowestScore > scores[index]) { lowestScore = scores[index]; } } System.out.print("nThese are the scores from the " + NUM_JUDGES + " judges: "); // use another for loop to redisplay the data back to the user via stdout for(int index=0; index < NUM_JUDGES; ++index) { System.out.print("nThe score for judge #"+(index+1)+" is: "+scores[index]); } // display the highest/lowest numbers to the screen System.out.print("nnThese are the highest and lowest scores: "); System.out.print("ntHighest: "+ highestScore); System.out.print("ntLowest: "+ lowestScore); // find the average avgScores = sumOfScores/NUM_JUDGES; System.out.print("nThe average score is: "+ avgScores); // reset data back to 0 so we can find the ommitted average sumOfScores = 0; avgScores = 0; System.out.print("nThe average adjusted score omitting the highest and lowest result is: "); // final loop, which calculates a running total, adding each element // in the array together, this time omitting the highest/lowest scores for(int index=0; index < NUM_JUDGES; ++index) { // IF(current score isnt equal to the highest elem) AND (current score isnt equal lowest elem) // THEN create a running total if((scores[index] != highestScore) && (scores[index] != lowestScore)) { sumOfScores += scores[index]; } } // find the average, minus the 2 scores avgScores = sumOfScores/(NUM_JUDGES-2); System.out.print(avgScores); }// end of main }// http://programmingnotes.org/ 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 import java.util.Scanner; public class FindOmittedAverage{ // global variable declaration static Scanner cin = new Scanner(System.in); static final int NUM_JUDGES = 6; public static void main(String[] args) { // declare variables double highestScore = -999999; double lowestScore = 999999; double sumOfScores = 0; double avgScores = 0; double[] scores = new double[NUM_JUDGES]; // array is initialized using a final variable // display message to screen System.out.println("Welcome to My Programming Notes' Java Program.n"); System.out.print("Judges, enter one score each for the current competitor: "); // use a for loop to obtain data from  user using the final variable for(int index=0; index < NUM_JUDGES; ++index) { // this puts data into the current array index scores[index] = cin.nextDouble(); // this calculates a running total of all the scores // adding each element in the array together sumOfScores += scores[index]; // if current score in the array index is bigger than the current 'highestScore' // value, then set 'highestScore' equal to the current value in the array if(scores[index] > highestScore) { highestScore = scores[index]; } // if current score in the array index is smaller than the current 'lowestScore' // value, then set 'lowestScore' equal to the current value in the array if(lowestScore > scores[index]) { lowestScore = scores[index]; } } System.out.print("nThese are the scores from the " + NUM_JUDGES + " judges: "); // use another for loop to redisplay the data back to the user via stdout for(int index=0; index < NUM_JUDGES; ++index) { System.out.print("nThe score for judge #"+(index+1)+" is: "+scores[index]); } // display the highest/lowest numbers to the screen System.out.print("nnThese are the highest and lowest scores: "); System.out.print("ntHighest: "+ highestScore); System.out.print("ntLowest: "+ lowestScore); // find the average avgScores = sumOfScores/NUM_JUDGES; System.out.print("nThe average score is: "+ avgScores); // reset data back to 0 so we can find the ommitted average sumOfScores = 0; avgScores = 0; System.out.print("nThe average adjusted score omitting the highest and lowest result is: "); // final loop, which calculates a running total, adding each element // in the array together, this time omitting the highest/lowest scores for(int index=0; index < NUM_JUDGES; ++index) { // IF(current score isnt equal to the highest elem) AND (current score isnt equal lowest elem) // THEN create a running total if((scores[index] != highestScore) && (scores[index] != lowestScore)) { sumOfScores += scores[index]; } } // find the average, minus the 2 scores avgScores = sumOfScores/(NUM_JUDGES-2); System.out.print(avgScores); }// end of main}// http://programmingnotes.org/ ```

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

FINAL
A final variable was declared and used to initialize the array (line 7). This was used to initialize the size of the array.

FOR LOOPS
Once again loops were used to traverse the array, as noted on lines 24, 51 and 73. The final variable was also used within the for loops, making it easier to modify the code if its necessary to reduce or increase the number of available judges.

HIGHEST/LOWEST SCORES
This is noted on lines 35-45, and it is really simple to understand the process once you see the code.

OMITTING HIGHEST/LOWEST SCORE
Lines 73-81 highlights this process. The loop basically traverses the array, skipping over the highest/lowest elements.

Once compiled, you should get this as your output

`Welcome to My Programming Notes' Java Program.`

``` Judges, enter one score each for the current competitor: 123 453 -789 2 23345 987 These are the scores from the 6 judges: The score for judge #1 is: 123.0 The score for judge #2 is: 453.0 The score for judge #3 is: -789.0 The score for judge #4 is: 2.0 The score for judge #5 is: 23345.0 The score for judge #6 is: 987.0 ```

```These are the highest and lowest scores: Highest: 23345.0 Lowest: -789.0 The average score is: 4020.1666666666665 The average adjusted score omitting the highest and lowest result is: 391.25 ```

## C++ || Convert Time From Seconds Into Hours, Min, Sec Format

Here is another simple programming assignment. This page will demonstrate how to convert time from -seconds- into HH::MM::SS (hours, minutes seconds) format. So for example, if you had an input time of 9630 seconds, the program would display the converted time of 2 hours, 40 minutes, and 30 seconds.

Using simple math, this program utilizes the modulus operator, and the division operator during the conversion process.

REQUIRED KNOWLEDGE FOR THIS PROGRAM

```Modulus - What is it? How Many Seconds Are In One Hour? How Many Seconds Are In One Minute? ```

``` Convert Seconds Into HH::MM::SS Format C++ // ============================================================================ // Author: Kenneth Perkins // Date: May 30, 2012 // Taken From: http://programmingnotes.org/ // File: Convert-Time.cpp // Description: Demonstrates how to convert time from -seconds- into // HH::MM::SS (hours, minutes, seconds) format // ============================================================================ #include <iostream> using namespace std; int main() { // declare variables int time = 0; int hour = 0; int min = 0; int sec = 0; // obtain data from user cout << "Enter a time in seconds: "; cin >> time; // using the time from ^ above, convert // secs to HH:MM:SS format using division // and modulus hour = time/3600; time = time%3600; min = time/60; time = time%60; sec = time; // display data to user cout<<"\nThe time in HH:MM:SS format is: "<<hour<<" hours, " <<min<<" minutes, and "<<sec<<" seconds!\n"; return 0; }// http://programmingnotes.org/ 1234567891011121314151617181920212223242526272829303132333435363738 // ============================================================================//    Author: Kenneth Perkins//    Date:   May 30, 2012//    Taken From: http://programmingnotes.org///    File:  Convert-Time.cpp//    Description: Demonstrates how to convert time from -seconds- into//      HH::MM::SS (hours, minutes, seconds) format// ============================================================================#include <iostream>using namespace std; int main(){    // declare variables    int time = 0;    int hour = 0;    int min = 0;    int sec = 0;     // obtain data from user    cout << "Enter a time in seconds: ";    cin >> time;     // using the time from ^ above, convert    // secs to HH:MM:SS format using division    // and modulus    hour = time/3600;    time = time%3600;    min = time/60;    time = time%60;    sec = time;     // display data to user    cout<<"\nThe time in HH:MM:SS format is: "<<hour<<" hours, "        <<min<<" minutes, and "<<sec<<" seconds!\n";     return 0;}// http://programmingnotes.org/ ```

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output
(Note: the code was compiled five separate times to display different output)

`====== RUN 1 ======`

``` Enter a time in seconds: 9630 The time in HH:MM:SS format is: 2 hours, 40 minutes, and 30 seconds! ====== RUN 2 ====== Enter a time in seconds: 7200 The time in HH:MM:SS format is: 2 hours, 0 minutes, and 0 seconds! ====== RUN 3 ====== Enter a time in seconds: 45 The time in HH:MM:SS format is: 0 hours, 0 minutes, and 45 seconds! ====== RUN 4 ====== Enter a time in seconds: 134 The time in HH:MM:SS format is: 0 hours, 2 minutes, and 14 seconds! ====== RUN 5 ====== Enter a time in seconds: 31536000 ```

```The time in HH:MM:SS format is: 8760 hours, 0 minutes, and 0 seconds! ```

## Java || Simple Math Using Int & Double

This page will display the use of int and double data types.

==== ADDING TWO NUMBERS TOGETHER ====

To add two numbers together, you will have to first declare your variables by doing something like this.

``` #1 - Adding 2 Numbers Together Java // ============================================================================ // Author: Kenneth Perkins // Date: Mar 4, 2012 // Updated: Mar 7, 2021 // Taken From: http://programmingnotes.org/ // File: Add.java // Description: Demonstrates adding numbers together // ============================================================================ import java.util.Scanner; public class Add { public static void main(String[] args) { // declare variables int num1 = 0; int num2 = 0; int sum = 0; // prepare Scanner for integer data input Scanner cin = new Scanner(System.in); // get data from user System.out.print("Please enter the first number: "); num1 = cin.nextInt(); System.out.print("Please enter the second number: "); num2 = cin.nextInt(); // calculate the sum of the two numbers sum = num1 + num2; // display results to the user System.out.println("The sum of " + num1 + " and " + num2 + " is: " + sum); }// end main }// http://programmingnotes.org/ 12345678910111213141516171819202122232425262728293031323334 // ============================================================================//    Author: Kenneth Perkins//    Date:   Mar 4, 2012//    Updated: Mar 7, 2021//    Taken From: http://programmingnotes.org///    File:  Add.java//    Description: Demonstrates adding numbers together// ============================================================================import java.util.Scanner; public class Add {    public static void main(String[] args) {        // declare variables        int num1 = 0;        int num2 = 0;        int sum = 0;         // prepare Scanner for integer data input        Scanner cin = new Scanner(System.in);         // get data from user        System.out.print("Please enter the first number: ");        num1 = cin.nextInt();         System.out.print("Please enter the second number: ");        num2 = cin.nextInt();         // calculate the sum of the two numbers        sum = num1 + num2;         // display results to the user        System.out.println("The sum of " + num1 + " and " + num2 + " is: " + sum);    }// end main}// http://programmingnotes.org/ ```

Notice in lines 14-16, I declared my variables, giving them a name. You can name your variables anything you want, with a rule of thumb as naming them something meaningful to your code (i.e avoid giving your variables arbitrary names like “x” or “y”). In line 29 the actual math process is taking place, storing the sum of “num1” and “num2” in a variable called “sum.” I also initialized my variables to zero. You should always initialize your variables.

I obtained data from the user by using the Scanner Class.

===== HOW TO COMPILE CODE USING THE TERMINAL =====

*** This can be achieved by typing the following command:
(Notice the .java source file is named exactly the same as the class header)

`javac Add.java`

*** To run the compiled program, simply type this command:

` java Add`

The above code should give you the following output:

```Please enter the first number: 8 Please enter the second number: 24 The sum of 8 and 24 is: 32```

==== SUBTRACTING TWO NUMBERS ====

Subtracting two ints works the same way as the above code, and we would only need to edit the above code in one place to achieve that. In line 29, replace the addition symbol with a subtraction sign, and you should have something like this

``` #2 - Subtracting 2 Numbers Together Java // ============================================================================ // Author: Kenneth Perkins // Date: Mar 4, 2012 // Updated: Mar 7, 2021 // Taken From: http://programmingnotes.org/ // File: Subtract.java // Description: Demonstrates subtracting numbers together // ============================================================================ import java.util.Scanner; public class Subtract { public static void main(String[] args) { // declare variables int num1 = 0; double num2 = 0; double sum = 0; // prepare Scanner for integer data input Scanner cin = new Scanner(System.in); // get data from user System.out.print("Please enter the first number: "); num1 = cin.nextInt(); System.out.print("Please enter the second number: "); num2 = cin.nextDouble(); // calculate the difference of the two numbers sum = num1 - num2; // display results to the user System.out.println("The difference between " + num1 + " and " + num2 + " is: " + sum); }// end main }// http://programmingnotes.org/ 12345678910111213141516171819202122232425262728293031323334 // ============================================================================//    Author: Kenneth Perkins//    Date:   Mar 4, 2012//    Updated: Mar 7, 2021//    Taken From: http://programmingnotes.org///    File:  Subtract.java//    Description: Demonstrates subtracting numbers together// ============================================================================import java.util.Scanner; public class Subtract {    public static void main(String[] args) {        // declare variables        int num1 = 0;        double num2 = 0;        double sum = 0;         // prepare Scanner for integer data input        Scanner cin = new Scanner(System.in);         // get data from user        System.out.print("Please enter the first number: ");        num1 = cin.nextInt();         System.out.print("Please enter the second number: ");        num2 = cin.nextDouble();         // calculate the difference of the two numbers        sum = num1 - num2;         // display results to the user        System.out.println("The difference between " + num1 + " and " + num2 + " is: " + sum);    }// end main}// http://programmingnotes.org/ ```

Note: In the above example, “cin.nextDouble()” was used on line 26 in place of “nextInt.” The declaration “nextDouble” can be used in place of “nextInt” in case you want to obtain floating point data from the user.

===== HOW TO COMPILE CODE USING THE TERMINAL =====

*** This can be achieved by typing the following command:
(Notice the .java source file is named exactly the same as the class header)

`javac Subtract.java`

*** To run the compiled program, simply type this command:

` java Subtract`

The above code should give you the following output

```Please enter the first number: 8 Please enter the second number: 23.99999 The difference between 8 and 23.99999 is: -15.99999```

==== MULTIPLYING TWO NUMBERS ====

This can be achieved the same way as the 2 previous methods, simply by editing line 29, and replacing the designated math operator with the star symbol “*”.

``` #3 - Multiplying 2 Numbers Together Java // ============================================================================ // Author: Kenneth Perkins // Date: Mar 4, 2012 // Updated: Mar 7, 2021 // Taken From: http://programmingnotes.org/ // File: Multiply.java // Description: Demonstrates multiplying numbers together // ============================================================================ import java.util.Scanner; public class Multiply { public static void main(String[] args) { // declare variables double num1 = 0; int num2 = 0; double sum = 0; // prepare Scanner for integer data input Scanner cin = new Scanner(System.in); // get data from user System.out.print("Please enter the first number: "); num1 = cin.nextDouble(); System.out.print("Please enter the second number: "); num2 = cin.nextInt(); // calculate the product of the two numbers sum = num1 * num2; // display results to the user System.out.println("The product of " + num1 + " and " + num2 + " is: " + sum); }// end main }// http://programmingnotes.org/ 12345678910111213141516171819202122232425262728293031323334 // ============================================================================//    Author: Kenneth Perkins//    Date:   Mar 4, 2012//    Updated: Mar 7, 2021//    Taken From: http://programmingnotes.org///    File:  Multiply.java//    Description: Demonstrates multiplying numbers together// ============================================================================import java.util.Scanner; public class Multiply {    public static void main(String[] args) {        // declare variables        double num1 = 0;        int num2 = 0;        double sum = 0;         // prepare Scanner for integer data input        Scanner cin = new Scanner(System.in);         // get data from user        System.out.print("Please enter the first number: ");        num1 = cin.nextDouble();         System.out.print("Please enter the second number: ");        num2 = cin.nextInt();         // calculate the product of the two numbers        sum = num1 * num2;         // display results to the user        System.out.println("The product of " + num1 + " and " + num2 + " is: " + sum);    }// end main}// http://programmingnotes.org/ ```

===== HOW TO COMPILE CODE USING THE TERMINAL =====

*** This can be achieved by typing the following command:
(Notice the .java source file is named exactly the same as the class header)

`javac Multiply.java`

*** To run the compiled program, simply type this command:

` java Multiply`

The above code should give you the following output

```Please enter the first number: 7.999999 Please enter the second number: 24 The product of 7.999999 and 24 is: 191.99997```

==== DIVIDING TWO NUMBERS TOGETHER ====

In division, when you divide numbers together, sometimes they end in decimals. Int data types can not store decimal data (try it yourself and see), so here is where the use of the double data type is mandatory.

``` #4 - Dividing 2 Numbers Together Java // ============================================================================ // Author: Kenneth Perkins // Date: Mar 4, 2012 // Updated: Mar 7, 2021 // Taken From: http://programmingnotes.org/ // File: Divide.java // Description: Demonstrates dividing numbers together // ============================================================================ import java.util.Scanner; public class Divide { public static void main(String[] args) { // declare variables double num1 = 0; double num2 = 0; double sum = 0; // prepare Scanner for integer data input Scanner cin = new Scanner(System.in); // get data from user System.out.print("Please enter the first number: "); num1 = cin.nextDouble(); System.out.print("Please enter the second number: "); num2 = cin.nextDouble(); // calculate the quotient of the two numbers sum = num1 / num2; // display results to the user System.out.println("The quotient of " + num1 + " and " + num2 + " is: " + sum); }// end main }// http://programmingnotes.org/ 12345678910111213141516171819202122232425262728293031323334 // ============================================================================//    Author: Kenneth Perkins//    Date:   Mar 4, 2012//    Updated: Mar 7, 2021//    Taken From: http://programmingnotes.org///    File:  Divide.java//    Description: Demonstrates dividing numbers together// ============================================================================import java.util.Scanner; public class Divide {    public static void main(String[] args) {        // declare variables        double num1 = 0;        double num2 = 0;        double sum = 0;         // prepare Scanner for integer data input        Scanner cin = new Scanner(System.in);         // get data from user        System.out.print("Please enter the first number: ");        num1 = cin.nextDouble();         System.out.print("Please enter the second number: ");        num2 = cin.nextDouble();         // calculate the quotient of the two numbers        sum = num1 / num2;         // display results to the user        System.out.println("The quotient of " + num1 + " and " + num2 + " is: " + sum);    }// end main}// http://programmingnotes.org/ ```

===== HOW TO COMPILE CODE USING THE TERMINAL =====

*** This can be achieved by typing the following command:
(Notice the .java source file is named exactly the same as the class header)

`javac Divide.java`

*** To run the compiled program, simply type this command:

` java Divide`

The above code should give the following output

```Please enter the first number: 7.99999 Please enter the second number: 23.99999 The quotient of 7.99999 and 23.99999 is: 0.33333305```

==== MODULUS ====

If you wanted to capture the remainder of the quotient you calculated from the above code, you would use the modulus operator (%).

From the above code, you would only need to edit line 29, from division, to modulus.

``` #5 - Getting the Remainder of 2 Numbers Java // ============================================================================ // Author: Kenneth Perkins // Date: Mar 4, 2012 // Updated: Mar 7, 2021 // Taken From: http://programmingnotes.org/ // File: Modulus.java // Description: Demonstrates performing modulus on numbers // ============================================================================ import java.util.Scanner; public class Modulus { public static void main(String[] args) { // declare variables double num1 = 0; int num2 = 0; double remainder = 0; // prepare Scanner for integer data input Scanner cin = new Scanner(System.in); // get data from user System.out.print("Please enter the first number: "); num1 = cin.nextDouble(); System.out.print("Please enter the second number: "); num2 = cin.nextInt(); // calculate the remainder of the two numbers remainder = num1 % num2; // display results to the user System.out.println("The remainder of " + num1 + " and " + num2 + " is: " + remainder); }// end main }// http://programmingnotes.org/ 12345678910111213141516171819202122232425262728293031323334 // ============================================================================//    Author: Kenneth Perkins//    Date:   Mar 4, 2012//    Updated: Mar 7, 2021//    Taken From: http://programmingnotes.org///    File:  Modulus.java//    Description: Demonstrates performing modulus on numbers// ============================================================================import java.util.Scanner; public class Modulus {    public static void main(String[] args) {        // declare variables        double num1 = 0;        int num2 = 0;        double remainder = 0;         // prepare Scanner for integer data input        Scanner cin = new Scanner(System.in);         // get data from user        System.out.print("Please enter the first number: ");        num1 = cin.nextDouble();         System.out.print("Please enter the second number: ");        num2 = cin.nextInt();         // calculate the remainder of the two numbers        remainder = num1 % num2;         // display results to the user        System.out.println("The remainder of " + num1 + " and " + num2 + " is: " + remainder);    }// end main}// http://programmingnotes.org/ ```

===== HOW TO COMPILE CODE USING THE TERMINAL =====

*** This can be achieved by typing the following command:
(Notice the .java source file is named exactly the same as the class header)

`javac Modulus.java`

*** To run the compiled program, simply type this command:

` java Modulus`

The above code should give the following output

```Please enter the first number: 23.99999 Please enter the second number: 8 The remainder of 23.99999 and 8 is: 7.9999905```

## C++ || Cash Register Simulation – Display The Total Sales Amount In Dollars & Cents Using Modulus

The following is a simple program which demonstrates more use of the modulus (%) function to manipulate integer data.

REQUIRED KNOWLEDGE FOR THIS PROGRAM

```Modulus Type Casting - Int The Value Of U.S Currency ```

This program first prompts the user to enter in a monetary amount into the system. This number can be a decimal number, or a whole number. Once the user enters in an amount, the program will use the modulus operator to determine exactly how many 1 dollar bills, quarters, dimes, nickles, and pennies consisted of the amount that the user entered into the program. So for example, if the user entered the value of 2.34, the program would display the result of 2 dollars, 1 quarters, 0 dimes, 1 nickels, and 4 pennies.

``` Cash Register Simulation C++ // ============================================================================ // Author: Kenneth Perkins // Date: Feb 28, 2012 // Taken From: http://programmingnotes.org/ // File: MakeChange.cpp // Description: The following is a simple program which demonstrates // how to make change. // ============================================================================ #include<iostream> using namespace std; int main() { // declare variables double initialAmount = 0; int remainingAmount = 0; int numberOfOneDollars = 0; int numberOfQuarters = 0; int numberOfDimes = 0; int numberOfNickels = 0; int numberOfPennies = 0; // Receive the amount cout << "Enter the total sales amount in dollars & cents (for example 19.87): "; cin >> initialAmount; // convert a 'double' to 'int' value remainingAmount = static_cast<int>(initialAmount * 100); // Find the number of one dollars numberOfOneDollars = remainingAmount / 100; remainingAmount = remainingAmount % 100; // Find the number of quarters in the remaining amount numberOfQuarters = remainingAmount / 25; remainingAmount = remainingAmount % 25; // Find the number of dimes in the remaining amount numberOfDimes = remainingAmount / 10; remainingAmount = remainingAmount % 10; // Find the number of nickels in the remaining amount numberOfNickels = remainingAmount / 5; remainingAmount = remainingAmount % 5; // Find the number of pennies in the remaining amount numberOfPennies = remainingAmount; // Display the results cout << "\nThe amount of \$" << initialAmount << " consists of: \n" << "\t" << numberOfOneDollars << " dollar(s)\n" << "\t" << numberOfQuarters << " quarter(s)\n" << "\t" << numberOfDimes << " dime(s)\n" << "\t" << numberOfNickels << " nickel(s)\n" << "\t" << numberOfPennies << " pennie(s)\n"; return 0; }// http://programmingnotes.org/ 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 // ============================================================================//    Author: Kenneth Perkins//    Date:   Feb 28, 2012//    Taken From: http://programmingnotes.org///    File:  MakeChange.cpp//    Description: The following is a simple program which demonstrates//          how to make change. // ============================================================================#include<iostream>using namespace std; int main(){ // declare variables double initialAmount = 0; int remainingAmount = 0; int numberOfOneDollars = 0; int numberOfQuarters = 0; int numberOfDimes = 0; int numberOfNickels = 0; int numberOfPennies = 0;  // Receive the amount cout << "Enter the total sales amount in dollars & cents (for example 19.87): "; cin >> initialAmount;  // convert a 'double' to 'int' value remainingAmount = static_cast<int>(initialAmount * 100);  // Find the number of one dollars numberOfOneDollars = remainingAmount / 100; remainingAmount = remainingAmount % 100;  // Find the number of quarters in the remaining amount numberOfQuarters = remainingAmount / 25; remainingAmount = remainingAmount % 25;  // Find the number of dimes in the remaining amount numberOfDimes = remainingAmount / 10; remainingAmount = remainingAmount % 10;  // Find the number of nickels in the remaining amount numberOfNickels = remainingAmount / 5; remainingAmount = remainingAmount % 5;  // Find the number of pennies in the remaining amount numberOfPennies = remainingAmount;  // Display the results cout << "\nThe amount of \$" << initialAmount << " consists of: \n" << "\t" << numberOfOneDollars << " dollar(s)\n" << "\t" << numberOfQuarters << " quarter(s)\n" << "\t" << numberOfDimes << " dime(s)\n" << "\t" << numberOfNickels << " nickel(s)\n" << "\t" << numberOfPennies << " pennie(s)\n";  return 0;}// http://programmingnotes.org/ ```

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output
(Note: the code was compile three separate times to display different output)

`====== RUN 1 ======`

``` Enter the total sales amount in dollars & cents (for example 19.87): 19.87 The amount of \$19.87 consists of: 19 dollar(s) 3 quarter(s) 1 dime(s) 0 nickel(s) 2 pennie(s) ====== RUN 2 ====== Enter the total sales amount in dollars & cents (for example 19.87): 11.93 The amount of \$11.93 consists of: 11 dollar(s) 3 quarter(s) 1 dime(s) 1 nickel(s) 3 pennie(s) ====== RUN 3 ====== Enter the total sales amount in dollars & cents (for example 19.87): 3.00 ```

```The amount of \$3 consists of: 3 dollar(s) 0 quarter(s) 0 dime(s) 0 nickel(s) 0 pennie(s)```

## C++ || Snippet – How To Do Simple Math Using Integer Arrays

This page will consist of simple programs which demonstrate the process of doing simple math with numbers that are stored in an integer array.

REQUIRED KNOWLEDGE FOR THIS SNIPPET

```Integer Arrays For Loops Assignment Operators - Simple Math Operations Setw```

Note: In all of the examples on this page, a random number generator was used to place numbers into the array. If you do not know how to obtain data from the user, or if you do not know how to insert data into an array, click here for a demonstration.

The first code snippet will demonstrate how to add numbers together which are stored in an integer array. This example uses the “+=” assignment operator.

``` #1 - Addition Using An Int Array C++ #include <iostream> #include <iomanip> // used for setw #include <ctime> // used for srand & rand using namespace std; // const int allocating space for the array const int NUM_INTS = 12; int main() { // declare variables int arry[NUM_INTS]; // array is initialized using a const variable int totalSum =0; srand(time(NULL)); // place random numbers into the array for(int i = 0; i < NUM_INTS; i++) { arry[i] =rand()%100+1; } cout << "Original array values" << endl; // Display the original array values for(int i = 0; i < NUM_INTS; i++) { cout << setw(4) << arry[i]; } // creates a line seperator cout << "n--------------------------------------------------------"; cout<<"nThe sum of the items in the array is: "; // Find the sum of the values in the array for(int i = 0; i < NUM_INTS; i++) { // the code below literally means // totalSum = totalSum + arry[i] totalSum += arry[i]; } // after the calculations are complete, display the total to the user cout<< totalSum <<endl; return 0; }// http://programmingnotes.org/ 1234567891011121314151617181920212223242526272829303132333435363738394041424344 #include <iostream>#include <iomanip>  // used for setw#include <ctime>   // used for srand & randusing namespace std; // const int allocating space for the arrayconst int NUM_INTS = 12; int main(){     // declare variables     int arry[NUM_INTS]; // array is initialized using a const variable     int totalSum =0;     srand(time(NULL));      // place random numbers into the array     for(int i = 0; i < NUM_INTS; i++)     {          arry[i] =rand()%100+1;     }       cout << "Original array values" << endl;     // Display the original array values     for(int i = 0; i < NUM_INTS; i++)     {          cout << setw(4) << arry[i];     }      // creates a line seperator      cout << "n--------------------------------------------------------";      cout<<"nThe sum of the items in the array is: ";     // Find the sum of the values in the array     for(int i = 0; i < NUM_INTS; i++)     {         // the code below literally means         // totalSum = totalSum + arry[i]         totalSum += arry[i];     }     // after the calculations are complete, display the total to the user     cout<< totalSum <<endl;      return 0;}// http://programmingnotes.org/ ```

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

SAMPLE OUTPUT

```Original array values 64 85 44 31 35 2 94 67 12 80 97 10 -------------------------------------------------------- The sum of the items in the array is: 621```

===== SUBTRACTION =====

The second code snippet will demonstrate how to subtract numbers which are stored in an integer array. This example uses the “-=” assignment operator.

``` #2 - Subtraction Using An Int Array C++ #include <iostream> #include <iomanip> // used for setw #include <ctime> // used for srand & rand using namespace std; // const int allocating space for the array const int NUM_INTS = 12; int main() { // declare variables int arry[NUM_INTS]; // array is initialized using a const variable int totalDiffetence =0; srand(time(NULL)); // place random numbers into the array for(int i = 0; i < NUM_INTS; i++) { arry[i] =rand()%100+1; } cout << "Original array values" << endl; // Display the original array values for(int i = 0; i < NUM_INTS; i++) { cout << setw(4) << arry[i]; } // creates a line seperator cout << "n--------------------------------------------------------"; cout<<"nThe difference of the items in the array is: "; // Find the difference of the values in the array for(int i = 0; i < NUM_INTS; i++) { // the code below literally means // totalDiffetence = totalDiffetence - arry[i] totalDiffetence -= arry[i]; } // after the calculations are complete, display the total to the user cout<< totalDiffetence <<endl; return 0; }// http://programmingnotes.org/ 1234567891011121314151617181920212223242526272829303132333435363738394041424344 #include <iostream>#include <iomanip>  // used for setw#include <ctime>   // used for srand & randusing namespace std; // const int allocating space for the arrayconst int NUM_INTS = 12; int main(){     // declare variables     int arry[NUM_INTS]; // array is initialized using a const variable     int totalDiffetence =0;     srand(time(NULL));      // place random numbers into the array     for(int i = 0; i < NUM_INTS; i++)     {          arry[i] =rand()%100+1;     }       cout << "Original array values" << endl;     // Display the original array values     for(int i = 0; i < NUM_INTS; i++)     {          cout << setw(4) << arry[i];     }      // creates a line seperator      cout << "n--------------------------------------------------------";      cout<<"nThe difference of the items in the array is: ";     // Find the difference of the values in the array     for(int i = 0; i < NUM_INTS; i++)     {         // the code below literally means         // totalDiffetence = totalDiffetence - arry[i]         totalDiffetence -= arry[i];     }     // after the calculations are complete, display the total to the user     cout<< totalDiffetence <<endl;      return 0;}// http://programmingnotes.org/ ```

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

SAMPLE OUTPUT

```Original array values 10 43 77 10 2 17 87 67 6 95 57 18 -------------------------------------------------------- The difference of the items in the array is: -489```

===== MULTIPLICATION =====

The third code snippet will demonstrate how to multiply numbers which are stored in an integer array. This example uses the “*=” assignment operator.

``` #3 - Multiplication Using An Int Array C++ #include <iostream> #include <iomanip> // used for setw #include <ctime> // used for srand & rand using namespace std; // const int allocating space for the array const int NUM_INTS = 12; int main() { // declare variables int arry[NUM_INTS]; // array is initialized using a const variable int totalProduct =1; srand(time(NULL)); // place random numbers into the array for(int i = 0; i < NUM_INTS; i++) { arry[i] =rand()%100+1; } cout << "Original array values" << endl; // Display the original array values for(int i = 0; i < NUM_INTS; i++) { cout << setw(4) << arry[i]; } // creates a line seperator cout << "n--------------------------------------------------------"; cout<<"nThe product of the items in the array is: "; // Find the product of the values in the array for(int i = 0; i < NUM_INTS; i++) { // the code below literally means // totalProduct = totalProduct * arry[i]; totalProduct *= arry[i]; } // after the calculations are complete, display the total to the user cout<< totalProduct <<endl; return 0; }// http://programmingnotes.org/ 1234567891011121314151617181920212223242526272829303132333435363738394041424344 #include <iostream>#include <iomanip>  // used for setw#include <ctime>   // used for srand & randusing namespace std; // const int allocating space for the arrayconst int NUM_INTS = 12; int main(){     // declare variables     int arry[NUM_INTS]; // array is initialized using a const variable     int totalProduct =1;     srand(time(NULL));      // place random numbers into the array     for(int i = 0; i < NUM_INTS; i++)     {          arry[i] =rand()%100+1;     }       cout << "Original array values" << endl;     // Display the original array values     for(int i = 0; i < NUM_INTS; i++)     {          cout << setw(4) << arry[i];     }      // creates a line seperator      cout << "n--------------------------------------------------------";      cout<<"nThe product of the items in the array is: ";     // Find the product of the values in the array     for(int i = 0; i < NUM_INTS; i++)     {         // the code below literally means         // totalProduct = totalProduct * arry[i];         totalProduct *= arry[i];     }     // after the calculations are complete, display the total to the user     cout<< totalProduct <<endl;      return 0;}// http://programmingnotes.org/ ```

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

SAMPLE OUTPUT

```Original array values 33 36 52 28 4 99 97 17 42 81 83 33 -------------------------------------------------------- The product of the items in the array is: 1803759104```

===== DIVISION =====

The fourth code snippet will demonstrate how to divide numbers which are stored in an integer array. This example uses the “/=” assignment operator.

``` #4 - Division Using An Int Array C++ #include <iostream> #include <iomanip> // used for setw #include <ctime> // used for srand & rand using namespace std; // const int allocating space for the array const int NUM_INTS = 12; int main() { // declare variables int arry[NUM_INTS]; // array is initialized using a const variable float totalQuotient =1; // need to save the variable as a float, not an int srand(time(NULL)); // place random numbers into the array for(int i = 0; i < NUM_INTS; i++) { arry[i] =rand()%100+1; } cout << "Original array values" << endl; // Display the original array values for(int i = 0; i < NUM_INTS; i++) { cout << setw(4) << arry[i]; } // creates a line seperator cout << "n--------------------------------------------------------"; cout<<"nThe quotient of the items in the array is: "; // Find the quotient of the values in the array for(int i = 0; i < NUM_INTS; i++) { // the code below literally means // totalQuotient = totalQuotient / arry[i]; totalQuotient /= arry[i]; } // after the calculations are complete, display the total to the user cout<< totalQuotient <<endl; return 0; }// http://programmingnotes.org/ 1234567891011121314151617181920212223242526272829303132333435363738394041424344 #include <iostream>#include <iomanip>  // used for setw#include <ctime>   // used for srand & randusing namespace std; // const int allocating space for the arrayconst int NUM_INTS = 12; int main(){     // declare variables     int arry[NUM_INTS]; // array is initialized using a const variable     float totalQuotient =1; // need to save the variable as a float, not an int     srand(time(NULL));      // place random numbers into the array     for(int i = 0; i < NUM_INTS; i++)     {          arry[i] =rand()%100+1;     }       cout << "Original array values" << endl;     // Display the original array values     for(int i = 0; i < NUM_INTS; i++)     {          cout << setw(4) << arry[i];     }      // creates a line seperator      cout << "n--------------------------------------------------------";      cout<<"nThe quotient of the items in the array is: ";     // Find the quotient of the values in the array     for(int i = 0; i < NUM_INTS; i++)     {         // the code below literally means         // totalQuotient = totalQuotient / arry[i];         totalQuotient /= arry[i];     }     // after the calculations are complete, display the total to the user     cout<< totalQuotient <<endl;      return 0;}// http://programmingnotes.org/ ```

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

SAMPLE OUTPUT

```Original array values 75 38 59 14 53 42 29 88 92 27 69 16 -------------------------------------------------------- The quotient of the items in the array is: 2.72677e-020```

## C++ || Simple Math Using Integer & Double

This page will display the use of int and double data types.

==== ADDING TWO NUMBERS TOGETHER ====

To add two numbers together, you will have to first declare your variables by doing something like this.

``` Adding 2 Numbers Together C++ // ============================================================================ // Author: Kenneth Perkins // Date: Jan 4, 2012 // Updated: Feb 15, 2021 // Taken From: http://programmingnotes.org/ // File: addition.cpp // Description: Demonstrates adding numbers together // ============================================================================ #include <iostream> int main() { int num1 = 0; int num2 = 0; int sum = 0; std::cout << "Please enter the first number: "; std::cin >> num1; std::cout << "\nPlease enter the second number: "; std::cin >> num2; // calculate the sum of the two numbers here sum = num1 + num2; std::cout << "\nThe sum of " <<num1<<" and "<<num2<< " is: "<< sum; return 0; }// http://programmingnotes.org/ 1234567891011121314151617181920212223242526 // ============================================================================//    Author: Kenneth Perkins//    Date:   Jan 4, 2012//    Updated: Feb 15, 2021//    Taken From: http://programmingnotes.org///    File:  addition.cpp//    Description: Demonstrates adding numbers together// ============================================================================#include <iostream>int main(){    int num1 = 0;    int num2 = 0;    int sum = 0;     std::cout << "Please enter the first number: ";    std::cin >> num1;    std::cout << "\nPlease enter the second number: ";    std::cin >> num2;     // calculate the sum of the two numbers here    sum = num1 + num2;     std::cout << "\nThe sum of " <<num1<<" and "<<num2<< " is: "<< sum;    return 0;}// http://programmingnotes.org/ ```

Notice in lines 12-14, I declared my variables, giving them a name. You can name your variables anything you want, with a rule of thumb as naming them something meaningful to your code (i.e avoid giving your variables arbitrary names like “x” or “y”). In line 22 the actual math process is taking place, storing the sum of “num1” and “num2” in a variable called “sum.” I also initialized my variables to zero. You should always initialize your variables.

The above code should give you the following output:

```Please enter the first number: 8 Please enter the second number: 24 The sum of 8 and 24 is: 32```

==== SUBTRACTING TWO NUMBERS ====

Subtracting two numbers works the same way as the above code, and we would only need to edit the above code in one place to achieve that. In line 22, replace the addition symbol with a subtraction sign, and you should have something like this:

``` Subtracting 2 Numbers Together C++ // ============================================================================ // Author: Kenneth Perkins // Date: Jan 4, 2012 // Updated: Feb 15, 2021 // Taken From: http://programmingnotes.org/ // File: subtraction.cpp // Description: Demonstrates subtracting numbers together // ============================================================================ #include <iostream> int main() { int num1 = 0; int num2 = 0; int sum = 0; std::cout << "Please enter the first number: "; std::cin >> num1; std::cout << "\nPlease enter the second number: "; std::cin >> num2; // calculate the difference of the two numbers here sum = num1 - num2; std::cout << "\nThe difference between " <<num1<<" and "<<num2<< " is: "<< sum; return 0; }// http://programmingnotes.org/ 1234567891011121314151617181920212223242526 // ============================================================================//    Author: Kenneth Perkins//    Date:   Jan 4, 2012//    Updated: Feb 15, 2021//    Taken From: http://programmingnotes.org///    File:  subtraction.cpp//    Description: Demonstrates subtracting numbers together// ============================================================================#include <iostream>int main(){    int num1 = 0;    int num2 = 0;    int sum = 0;     std::cout << "Please enter the first number: ";    std::cin >> num1;    std::cout << "\nPlease enter the second number: ";    std::cin >> num2;     // calculate the difference of the two numbers here    sum = num1 - num2;     std::cout << "\nThe difference between " <<num1<<" and "<<num2<< " is: "<< sum;    return 0;}// http://programmingnotes.org/ ```

The above code should give you the following output:

```Please enter the first number: 8 Please enter the second number: 24 The difference between 8 and 24 is: -16```

==== MULTIPLYING TWO NUMBERS ====

This can be achieved the same way as the 2 previous methods, simply by editing line 22, and replacing the designated math operator with the star symbol “*”.

``` Multiplying 2 Numbers Together C++ // ============================================================================ // Author: Kenneth Perkins // Date: Jan 4, 2012 // Updated: Feb 15, 2021 // Taken From: http://programmingnotes.org/ // File: multiplication.cpp // Description: Demonstrates multiplying numbers together // ============================================================================ #include <iostream> int main() { int num1 = 0; int num2 = 0; int sum = 0; std::cout << "Please enter the first number: "; std::cin >> num1; std::cout << "\nPlease enter the second number: "; std::cin >> num2; // calculate the product of the two numbers here sum = num1 * num2; std::cout << "\nThe product of " <<num1<<" and "<<num2<< " is: "<< sum; return 0; }// http://programmingnotes.org/ 1234567891011121314151617181920212223242526 // ============================================================================//    Author: Kenneth Perkins//    Date:   Jan 4, 2012//    Updated: Feb 15, 2021//    Taken From: http://programmingnotes.org///    File:  multiplication.cpp//    Description: Demonstrates multiplying numbers together// ============================================================================#include <iostream>int main(){    int num1 = 0;    int num2 = 0;    int sum = 0;     std::cout << "Please enter the first number: ";    std::cin >> num1;    std::cout << "\nPlease enter the second number: ";    std::cin >> num2;     // calculate the product of the two numbers here    sum = num1 * num2;     std::cout << "\nThe product of " <<num1<<" and "<<num2<< " is: "<< sum;    return 0;}// http://programmingnotes.org/ ```

The above code should give you the following output:

```Please enter the first number: 8 Please enter the second number: 24 The product of 8 and 24 is: 192```

==== DIVIDING TWO NUMBERS TOGETHER ====

This one is a little different from the other three. Before we would use integer variables to store our data. In division, when you divide numbers together, sometimes they end in decimals. Integer data types can not store decimal data (try it yourself and see), so here is where we use a floating point data type to store the values.

So the resulting code will basically be the same as the other previous three, only instead of our variables being of type int, they will be of type double.

``` Dividing 2 Numbers Together C++ // ============================================================================ // Author: Kenneth Perkins // Date: Jan 4, 2012 // Updated: Feb 15, 2021 // Taken From: http://programmingnotes.org/ // File: division.cpp // Description: Demonstrates dividing numbers together // ============================================================================ #include <iostream> int main() { int num1 = 0; int num2 = 0; double sum = 0; std::cout << "Please enter the first number: "; std::cin >> num1; std::cout << "\nPlease enter the second number: "; std::cin >> num2; // calculate the quotient of the two numbers here sum = (double)num1 / num2; std::cout << "\nThe quotient of " <<num1<<" and "<<num2<< " is: "<< sum; return 0; }// http://programmingnotes.org/ 1234567891011121314151617181920212223242526 // ============================================================================//    Author: Kenneth Perkins//    Date:   Jan 4, 2012//    Updated: Feb 15, 2021//    Taken From: http://programmingnotes.org///    File:  division.cpp//    Description: Demonstrates dividing numbers together// ============================================================================#include <iostream>int main(){    int num1 = 0;    int num2 = 0;    double sum = 0;     std::cout << "Please enter the first number: ";    std::cin >> num1;    std::cout << "\nPlease enter the second number: ";    std::cin >> num2;     // calculate the quotient of the two numbers here    sum = (double)num1 / num2;     std::cout << "\nThe quotient of " <<num1<<" and "<<num2<< " is: "<< sum;    return 0;}// http://programmingnotes.org/ ```

The above code should give the following output:

```Please enter the first number: 8 Please enter the second number: 24 The quotient of 8 and 24 is: 0.333333```

==== MODULUS ====

If you wanted to capture the remainder of the quotient you calculated from the above code, you would use the modulus operator (%).

From the above code, you would only need to edit line 22, from division, to modulus.

``` Getting the Remainder of 2 Numbers C++ // ============================================================================ // Author: Kenneth Perkins // Date: Jan 4, 2012 // Updated: Feb 15, 2021 // Taken From: http://programmingnotes.org/ // File: modulus.cpp // Description: Demonstrates performing modulus on numbers // ============================================================================ #include <iostream> int main() { int num1 = 0; int num2 = 0; int remainder = 0; std::cout << "Please enter the first number: "; std::cin >> num1; std::cout << "\nPlease enter the second number: "; std::cin >> num2; // find the remainder of the two numbers here remainder = num1 % num2; std::cout << "\nThe remainder of " <<num1<<" and "<<num2<< " is: "<< remainder; return 0; }// http://programmingnotes.org/ 1234567891011121314151617181920212223242526 // ============================================================================//    Author: Kenneth Perkins//    Date:   Jan 4, 2012//    Updated: Feb 15, 2021//    Taken From: http://programmingnotes.org///    File:  modulus.cpp//    Description: Demonstrates performing modulus on numbers// ============================================================================#include <iostream>int main(){    int num1 = 0;    int num2 = 0;    int remainder = 0;     std::cout << "Please enter the first number: ";    std::cin >> num1;    std::cout << "\nPlease enter the second number: ";    std::cin >> num2;     // find the remainder of the two numbers here    remainder = num1 % num2;     std::cout << "\nThe remainder of " <<num1<<" and "<<num2<< " is: "<< remainder;    return 0;}// http://programmingnotes.org/ ```

The above code should give the following output:

```Please enter the first number: 24 Please enter the second number: 8 The remainder of 24 and 8 is: 0```