## Tag Archives: int

## 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.

```
```
123456789101112131415161718192021222324
# This is the main functiondef 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 6-8, 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 16 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 resulting 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 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 16, replace the addition symbol with a subtraction sign, and you should have something like this

```
```
1234567891011121314151617181920212223
# This is the main functiondef 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 16, and replacing the designated math operator with the star symbol “*.”

```
```
1234567891011121314151617181920212223
# This is the main functiondef 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 ==== **

This one is a little different from the other three. Before we would use int variables to store our data. 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 we use the float data type.

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.

```
```
1234567891011121314151617181920212223
# This is the main functiondef 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 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 16, from division, to modulus.

```
```
1234567891011121314151617181920212223
# This is the main functiondef 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 the following output

`Please enter the first number: 1`

Please enter the second number: 25

1 mod 25 is: 1

## 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.

```
```
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.

```
```
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 987These 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++ || Snippet – How To Find The Minimum & Maximum Of 3 Numbers, Print In Ascending Order

This page will demonstrate how to find the minimum and maximum of 3 numbers. After the maximum and minimum numbers are obtained, the 3 numbers are displayed to the screen in ascending order.

This program uses multiple if-statements to determine equality, and uses 3 seperate int varables to store its data. This program is very basic, so it does not utilize an integer array, or any sorting methods.

**NOTE:** If you want to find the Minimum & Maximum of numbers contained in an integer array, click here.

```
```
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
// ============================================================================// Author: K Perkins// Date: Apr 29, 2012// Taken From: http://programmingnotes.org/// File: min_mid_max.cpp// Description: Demonstrates how to find the minimum & maximum of 3 numbers// ============================================================================#include <iostream>using namespace std; int main(){ // declare variables int a=0; int b=0; int c=0; int max=0; int min=0; int middle=0; // get data from user cout<<"Please enter 3 numbers: "; cin >> a >> b >> c; // display information back to the user cout <<"The numbers you just entered are: "<<a<<" "<<b<<" "<<c<<endl; // check for the highest number if(a > b && a > c) { max = a; } else if(b > a && b > c) { max = b; } else { max = c; } // check for the lowest number if(a < b && a < c) { min = a; } else if(b < a && b < c) { min = b; } else { min = c; } // use the 'min' and 'max' variables from above ^ to find // the 'middle' value if((max == a && min == b) || (max == b && min == a)) { middle = c; } else if((max == b && min == c) || (max == c && min == b)) { middle = a; } else { middle = b; } // display data to the screen cout<<"nThe maximum number is: "<<max; cout<<"nThe minimum number is: "<<min; cout<<"nThe numbers in order are: "<<min<<" "<<middle<< " "<<max<<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.

Once compiled, you should get this as your output

`Please enter 3 numbers: 89 56 1987`

The numbers you just entered are: 89 56 1987

`The maximum number is: 1987`

The minimum number is: 56

The numbers in order are: 56 89 1987

## C++ || Snippet – How To Reverse An Integer Using Modulus & While Loop

This page will consist of a simple program which demonstrates how to reverse an integer (not an int array) using modulus and a while loop.

**REQUIRED KNOWLEDGE FOR THIS SNIPPET**

```
```
1234567891011121314151617181920212223242526272829303132333435363738
#include <iostream>using namespace std; // function prototypeint ReverseNumber(int number); int main(){ // declare variables int number = 0; int numReversed = 0; // get data from user cout << "Enter a number: "; cin >> number; // function call which will return the reversed number numReversed = ReverseNumber(number); // display new data to user cout <<endl<< number << " reversed is: "<< numReversed <<endl; return 0;}// end of main int ReverseNumber(int number){ // declare function variable int rev=0; while(number > 0) { rev = rev * 10 + (number % 10); number = number/10; } return rev;}// 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 three separate times to display different output)

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

Enter a number: 2012

2012 reversed is: 2102==== RUN #2 ====

Enter a number: 1987

1987 reversed is: 7891==== RUN #3 ====

`Enter a number: 241`

241 reversed is: 142

## C++ || Simple Math Using Int & Float

This page will display the use of int and float data types. Note: you can (obviously) add as many int’s together as you wish, not just two.

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

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

```
```
12345678910111213141516171819
#include <iostream>using namespace std;int main(){ int num1 = 0; int num2 = 0; int sum = 0; cout << "Please enter the first number: "; cin >> num1; cout << endl << "Please enter the second number: "; cin >> num2; // calculate the sum of the two numbers here sum = num1 + num2; cout << endl << "The sum of " <<num1<<" and "<<num2<< " is: "<< sum << endl; return 0;}// http://programmingnotes.freeweq.com

Notice in lines 5-7, 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 15 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 resulting 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 15, replace the addition symbol with a subtraction sign, and you should have something like this

```
```
12345678910111213141516171819
#include <iostream>using namespace std;int main(){ int num1 = 0; int num2 = 0; int sum = 0; cout << "Please enter the first number: "; cin >> num1; cout << endl << "Please enter the second number: "; cin >> num2; // calculate the difference of the two numbers here sum = num1 - num2; cout << endl << "The difference between " <<num1<<" and "<<num2<< " is: "<< sum << endl; return 0;}// http://programmingnotes.freeweq.com

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 15, and replacing the designated math operator with the star symbol “*.”

```
```
12345678910111213141516171819
#include <iostream>using namespace std;int main(){ int num1 = 0; int num2 = 0; int sum = 0; cout << "Please enter the first number: "; cin >> num1; cout << endl << "Please enter the second number: "; cin >> num2; // calculate the product of the two numbers here sum = num1 * num2; cout << endl << "The product of " <<num1<<" and "<<num2<< " is: "<< sum << endl; return 0;}// http://programmingnotes.freeweq.com

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 int variables to store our data. 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 we use the float data type (you can also use the “double” data type here aswell).

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 float.

```
```
12345678910111213141516171819
#include <iostream>using namespace std;int main(){ int num1 = 0; int num2 = 0; float sum = 0; cout << "Please enter the first number: "; cin >> num1; cout << endl << "Please enter the second number: "; cin >> num2; // calculate the quotient of the two numbers here sum = num1 / num2; cout << endl << "The quotient of " <<num1<<" and "<<num2<< " is: "<< sum << endl; return 0;}// http://programmingnotes.freeweq.com

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 15, from division, to modulus.

```
```
12345678910111213141516171819
#include <iostream>using namespace std;int main(){ int num1 = 0; int num2 = 0; float remainder = 0; cout << "Please enter the first number: "; cin >> num1; cout << endl << "Please enter the second number: "; cin >> num2; // find the remainder of the two numbers here remainder = num1 % num2; cout << endl << "The remainder of " <<num1<<" and "<<num2<< " is: "<< remainder << endl; return 0;}// http://programmingnotes.freeweq.com

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