Answer:
Following are the code to the given question:
#include<stdio.h>//include header file
int main() //defining a main method
{
int a[100],k,x,s; //defining integer variable and an array
printf("Input the number of element want to insert array: "); //print message
scanf("%d",&x); //input value
printf("Enter array value: \n"); //print message
for(k = 0; k<x; k++) //defining a loop that inputs values
{
scanf("%d",&a[k]); //use array to input value
}
s = a[0]; //holding first array value in array
for(k=0;k<x;k++) //use for loop
{
if(a[k]<s) //use if block to check the smallest array value
{
s=a[k];//holding smallest array value
}
}
printf("smallest number= %d",s);//print smallest value
}
Output:
Please find the attached file.
Explanation:
In this code an array and another integer variable "a[100], i,n, and s" is is declared, in which the array and n for input the value from the user-end.
In the next step, an "s" variable is declared that inputs the first array element value in s and use a loop to check the smallest array element and prints its value.
3. Most widely used structure for recording database modifications is called
A. Scheduling
B. Buffering
C. Log
D. Blocking
Answer:
C. log
Explanation:
The log is a sequence of log records, recording all the update activities in the database
hope this helps
Answer:
C. Log is the
answer
Explanation:
a sequence of log records recording all update activity in database
Can we update App Store in any apple device. (because my device is kinda old and if want to download the recent apps it aint showing them). So is it possible to update???
Please help
Answer:
For me yes i guess you can update an app store in any deviceI'm not sure×_× mello ×_×Write an expression that evaluates to True if the string associated with s1 is greater than the string associated with s2
Answer:
Explanation:
The following code is written in Python. It is a function that takes two string parameters and compares the lengths of both strings. If the string in variable s1 is greater then the function returns True, otherwise the function returns False. A test case has been provided and the output can be seen in the attached image below.
def compareStrings(s1, s2):
if len(s1) > len(s2):
return True
else:
return False
print(compareStrings("Brainly", "Competition"))
Write a statement that assigns numCoins with numNickels + numDimes. Ex: 5 nickels and 6 dimes results in 11 coins. Note: These activities may test code with different test values. This activity will perform two tests: the first with nickels = 5 and dimes = 6, the second with nickels = 9 and dimes = 0.
1 import java.util.Scanner;
2
3 public class AssigningSum {
4 public static void main(String[] args) {
5 int numCoins;
6 int numNickels;
7 int numDimes;
8
9 numNickels = 5;
10 numDimes - 6;
11
12 /* Your solution goes here
13
14 System.out.print("There are ");
15 System.out.print(numCoins);
16 System.out.println(" coins");
17 }
18 }
Answer:
Explanation:
The statement solution was added to the code and then the code was repeated in order to create the second test case with 9 nickels and 0 dimes. The outputs for both test cases can be seen in the attached image below.
import java.util.Scanner;
class AssigningSum {
public static void main(String[] args) {
int numCoins;
int numNickels;
int numDimes;
numNickels = 5;
numDimes = 6;
/* Your solution goes here */
numCoins = numNickels + numDimes;
System.out.print("There are ");
System.out.print(numCoins);
System.out.println(" coins");
// TEST CASE 2
numNickels = 9;
numDimes = 0;
/* Your solution goes here */
numCoins = numNickels + numDimes;
System.out.print("There are ");
System.out.print(numCoins);
System.out.println(" coins");
}
}
Many companies possess valuable information they want to guard closely (ex. new chip design, competition plans, legal documents). Personal computer hard disks these days are full of important photos, videos, and movies. As more and more information is stored in computer systems, the need to protect it is becoming increasingly important. Which of the following statements is incorrect with respect to Security?
a. security has many facets; three of the more important ones are: the nature of the threats, the nature of intruders, and cryptography
b. data integrity means that unauthorized users should not be able to modify any data without the owner's permission
c. a common category of intruders are driven by determined attempts to make money; for example: bank programmers attempting to steal from the bank they work for
d. in addition to threats caused by malicious users, data can be lost by accident; for example: rats gnawing backup tapes
Answer: D. in addition to threats caused by malicious users, data can be lost by accident; for example: rats gnawing backup tapes
Explanation:
Data security is essential to protecting unwanted people from having access to ones data, malicious attack should also be prevented and unusual behavior should be monitored.
Data security has many facets such as threat nature, the nature of intruders, and cryptography. Furthermore, data integrity means that unauthorized users should not be able to modify any data without the owner's permission. Also, the statement that a common category of intruders are driven by determined attempts to make money; for example: bank programmers attempting to steal from the bank they work for is correct.
It should be no noted that rats gnawing backup tapes cannot prevent data loss. Therefore, the correct option is D
How many ways are there to arrange the letters in the word ALGORITHMS? Note, the letter arrangement does not have to spell a word in the dictionary, but the new word must contain all the letters and each letter can be used only once.
there are ten letters in the word, so for the first position we can choose out of 10 option.
no matter wich specific option we choose, we will have 9 letters left for the 2nd letter.
and 8 for the third place.
...
when we will have used up 9 of 10 letters, there will be only one option for the last place.
the number of possible decision-paths is therefore given by this expression:
10*9*8*7*6*5*4*3*2*1
wich is 3,628,800
there are quite a few ways to rearrange 10 letters
The sorting method which commands entries in a going to head predicated on each character without regard to space as well as punctuation, therefore there are 3628800 ways.
The word 'ALGORITHMS' has 10 letters. There is no repeated letter so, the first Letter can hold 10 places if we start taking one letter at a time. The second can then hold nine positions, the third can hold eight, and so on.So, as [tex]\bold{ 10\times 9 \times 8.... \times 3 \times 2 \times 1 = 362,8800}[/tex] ways, we have such a total number of ways.
Learn more:
brainly.com/question/17276660
Spending plans serve as a tool to analyze program execution, an indicator of potential problems, and a predictor of future program performance. True False
Answer:
True
Explanation:
Spending plans serve as a tool to analyze program execution, an indicator of potential problems, and a predictor of future program performance.
9.17 LAB: Acronyms An acronym is a word formed from the initial letters of words in a set phrase. Write a program whose input is a phrase and whose output is an acronym of the input. If a word begins with a lower case letter, don't include that letter in the acronym. Assume there will be at least one upper case letter in the input.
Answer:
Hence the code is given as follows,
import java.util.Scanner;
public class LabProgram {
public static String createAcronym(String userPhrase){
String result = "";
String splits[] = userPhrase.split(" ");
for(int i = 0;i<splits.length;i++){
if(splits[i].charAt(0)>='A' && splits[i].charAt(0)<='Z')
result += splits[i].charAt(0);
}
return result;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
System.out.println(createAcronym(s));
}
}
How can COUNTIF, COUNTIFS, COUNT, COUNTA, and COUNTBLANK functions aide a company to support its mission or goals
Answer:
Following are the responses to these questions:
Explanation:
It employs keywords to autonomously do work tasks. Users can type numbers directly into the formulas or use the following formulae, so any data the cells referenced provide would be used in the form.
For instance, this leadership involves accounting, and Excel is concerned with organizing and organizing numerical data. In this Equation, I can discover all its information in the data. This idea is simple me count the number many cells containing a number, and also the number of integers. It counts integers in any sorted number as well. As both financial analysts, it is helpful for the analysis of the data if we want to maintain the same number of neurons.
You know different types of networks. If two computing station high speed network link for proper operation which of the following network type should be considered as a first priority?
MAN
WAN
WLAN
LAN
All of these
Answer:
All of these.
PLZ MARK ME BRAINLIEST.
SQLite is a database that comes with Android. Which statements is/are correct?
The content of an SQLite database is stored in XML formatted files because XML is the only file format supported by Android OS.
A SQLite database is just another name for a Content Provider. There is no difference as the SQLite implementation implements the Content Provider interface.
If an app creates an SQLite database and stores data in it, then all of the data in that particular database will be stored in one, single file.
A database query to an SQLite database usually returns a set of answers
To access individual entries, SQLite provides a so-called Cursor to enumerate all entries in the set.
This is yet another example of the Iterator pattern.
Answer:
1. Wrong as per my knowledge, SQLite may be an electronic database software that stores data in relations(tables).
2. Wrong. Content provider interface controls the flow of knowledge from your android application to an external data storage location. Data storage is often in any database or maybe it'll be possible to store the info in an SQLite database also.
3.Right. SQLite uses one file to store data. It also creates a rollback file to backup the stored data/logs the transactions.
4. Wrong. The queries are almost like a traditional electronic database system, the queries are going to be answered as per the conditions given and should return a group of answers or one answer depending upon the info and sort of query used.
5. Right. A cursor helps to point to one entry within the database table. this may be very helpful in manipulating the present row of the query easily.
A process needs 103 KB of memory in order to run. If the system on which it is to run uses paging with 2 KB pages, how many frames in memory are needed
Answer: 52
Explanation:
Following the information given in the question, we are informed that a process needs 103 KB of memory in order to run and that the system on which it is to run uses paging with 2KB pages, then the number of frames in memory that are needed will be:
= 103/2
= 51.5
= 52 approximately
Therefore, 52 frames in memory are needed.
You have recently subscribed to an online data analytics magazine. You really enjoyed an article and want to share it in the discussion forum. Which of the following would be appropriate in a post?
A. Including an advertisement for how to subscribe to the data analytics magazine.
B. Checking your post for typos or grammatical errors.
C. Giving credit to the original author.
D. Including your own thoughts about the article.
Select All that apply
Answer:
These are the things that are would be appropriate in a post.
B. Checking your post for typos or grammatical errors.
C. Giving credit to the original author.
D. Including your own thoughts about the article.
Explanation:
The correct answer options B, C, and D" According to unofficial online or internet usage it is believed that sharing informative articles is a reasonable use of a website forum as much the credit goes back to the actual or original author. Also, it is believed that posts should be suitable for data analytics checked for typos and grammatical errors.
A cashier distributes change using the maximum number of five-dollar bills, followed by one-dollar bills. Write a single statement that assigns num_ones with the number of distributed one-dollar bills given amount_to_change. Hint: Use %.
Sample output with input: 19
Change for $ 19
3 five dollar bill(s) and 4 one dollar bill(s)
1 amount_to_change = int(input())
2
3 num_fives amount_to_change // 5
4
5 Your solution goes here
6 I
7 print('Change for $, amount_to_change)
8 print(num_fives, 'five dollar bill(s) and', num_ones, 'one dollar bill (s)')
Answer:
Explanation:
The code that was provided in the question contained a couple of bugs. These bugs were fixed and the new code can be seen below as well as with the solution for the number of one-dollar bills included. The program was tested and the output can be seen in the attached image below highlighted in red.
amount_to_change = int(input())
num_fives = amount_to_change // 5
#Your solution goes here
num_ones = amount_to_change % 5
print('Change for $' + str(amount_to_change))
print(num_fives, 'five dollar bill(s) and', num_ones, 'one dollar bill (s)')
Write a programmer defined function that compares the ASCII sum of two strings. To compute the ASCII sum, you need to compute the ASCII value of each character of the string and sum them up. You will thus need to calculate two sums, one for each string. Then, return true if the first string has a larger ASCII sum compared to the second string, otherwise return false. In your main function, prompt the user to enter two strings with a suitable message and provide the strings to the function during function call. The user may enter multiple words for either string. Then, use the Boolean data returned by the function to inform which string has the higher ASCII sum.
Answer:
The program in Python is as follows:
def ASCIIsum(str1,str2):
asciisum1 = 0; asciisum2 = 0
for chr in str1:
asciisum1 += (ord(chr) - 96)
for chr in str2:
asciisum2 += (ord(chr) - 96)
if asciisum1 > asciisum2:
return True
else:
return False
str1 = input("Enter first string: ")
str2 = input("Enter second string: ")
if ASCIIsum(str1,str2) == True:
print(str1,"has a higher ASCII value")
else:
print(str2,"has a higher ASCII value")
Explanation:
This defines the function
def ASCIIsum(str1,str2):
This initializes the ascii sum of both strings to 0
asciisum1 = 0; asciisum2 = 0
This iterates through the characters of str1 and add up the ascii values of each character
for chr in str1:
asciisum1 += (ord(chr) - 96)
This iterates through the characters of str2 and add up the ascii values of each character
for chr in str2:
asciisum2 += (ord(chr) - 96)
This returns true if the first string has a greater ascii value
if asciisum1 > asciisum2:
return True
This returns false if the second string has a greater ascii value
else:
return False
The main begins here
This gets input for first string
str1 = input("Enter first string: ")
This gets input for second string
str2 = input("Enter second string: ")
If the returned value is True
if ASCIIsum(str1,str2) == True:
Then str1 has a greater ascii value
print(str1,"has a higher ASCII value")
If otherwise
else:
Then str2 has a greater ascii value
print(str2,"has a higher ASCII value")
write an algorithm for finding the perimeter of a rectangle
What is the default return type of a method in Java language?
A.Void
B.Int
C.None
D.Short
Answer:
The default return data type in function is int
Answer: Option (b)
Explanation:
The default return data type in a function is int. In other words commonly if it is not explicitly mentioned the default return data type of a function by the compiler will be of an integer data type.
If the user does not mention a return data type or parameter type, then C programming language will inevitably make it an int.
mark me brainlist
how to identify mistakes in a html code??
Write a RainFall class that stores the total rainfall for each of 12 months into an array of doubles. The program should have methods that return the following: the total rainfall for the year the average monthly rainfall the month with the most rain the month with the least rain Demonstrate the class in a complete program and use java 8 examples to do so. Input Validation: Do not accept negative numbers for monthly rainfall figures.
Answer:
Explanation:
The following code is written in Java. It creates the Rainfall class with two constructors, one that passes the entire array of rainfall and another that initializes an array with 0.0 for all the months. Then the class contains a method to add rain to a specific month, as well as the three methods requested in the question. The method to add rain validates to make sure that no negative value was added. 8 Test cases were provided, and any methods can be called on any of the 8 objects.
class Brainly {
public static void main(String[] args) {
Rainfall rain1 = new Rainfall();
Rainfall rain2 = new Rainfall();
Rainfall rain3 = new Rainfall();
Rainfall rain4 = new Rainfall();
Rainfall rain5 = new Rainfall();
Rainfall rain6 = new Rainfall();
Rainfall rain7 = new Rainfall();
Rainfall rain8 = new Rainfall();
}
}
class Rainfall {
double[] rainfall = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
public Rainfall(double[] rainfall) {
this.rainfall = rainfall;
}
public Rainfall() {
}
public void addMonthRain(double rain, int month) {
if (rain > 0) {
rainfall[month-1] = rain;
}
}
public double totalRainfall() {
double total = 0;
for (double rain: rainfall) {
total += rain;
}
return total;
}
public double averageRainfall() {
double average = totalRainfall() / 12;
return average;
}
public double rainiestMonth() {
double max = 0;
for (double rain : rainfall) {
if (rain > max) {
max = rain;
}
}
return max;
}
}
A recursive method may call other methods, including calling itself. A recursive method has:
1. a base case -- a case that returns a value or exits from a method without performing a recursive call.
2. a recursive case -- calling the method again with a smaller case..
Study the recursive method given below.
For example, this call recursiveMethod (5); returns 15:
public static int recursiveMethod (int num) (
if (num == 0)
return 1;
else {
if (numX2!=0)
return num * recursiveMethod (num -1);
else
return recursiveMethod (num-1);
}
}
1 What is the base case?
2. What does the following statement check?
3. What does the method do?
Answer:
Hence the answer is given as follows,
Explanation:
Base Case:-
If (num == 0) //This is the base case for the given recursive method
return 1;
If(num % 2!=0) checks whether num is odd.
The above condition is true for all odd numbers and false for even numbers.
if the remainder is not equal to zero when we divide the number with 2 then it is odd.
The method:-
The above recursive method calculates the product of odd numbers up to the given range(that is num)
For num=5 => 15(5*3*1).
For num=7 => 105(7*5*3*1).
For num=10 => 945(9*7*5*3*1).
When rating ads, I should only consider my personal feelings on the ad.
Answer:
yes when rating ads you should only consider your personal feelings on the ad
Una persona decide comprar un número determinado de quintales de azúcar, ayúdele a presentar el precio de venta al público por libra, considerando un 25% de utilidad por cada quintal.
what is a mirror site?
Explain the following terms.
a) Explain Final keyword with example. b) Define Static and Instance variables
Answer:
A.
the final keyword is used to denote constants. It can be used with variables, methods, and classes. Once any entity (variable, method or class) is declared final , it can be assigned only once.
B.
Static variables are declared in the same place as instance variables, but with the keyword 'static' before the data type. While instance variables hold values that are associated with an individual object, static variables' values are associated with the class as a whole.
If the signal is going through a 2 MHz Bandwidth Channel, what will be the maximum bit rate that can be achieved in this channel? What will be the appropriate signal level?
Answer:
caca
Explanation:
Trace the evaluation of the following expressions, and give their resulting values. Make sure to give a value of the appropriate type (such as including a .0 at the end of a double or quotes around a String).
4 + 1 + 9 + "." + (-3 + 10) + 11 / 3
8 + 6 * -2 + 4 + "0" + (2 + 5)
1 + 1 + "8 - 2" + (8 - 2) + 1 + 1
5 + 2 + "(1 + 1)" + 4 + 2 * 3
"1" + 2 + 3 + "4" + 5 * 6 + "7" + (8 + 9)
Answer:
[tex](a)\ 14"."43[/tex]
[tex](b)\ 0"0"7[/tex]
[tex](c)\ 2"8 - 2"611[/tex]
[tex](d)\ 7"(1 + 1)"46[/tex]
[tex](e)\ "1"23"4"30"7"17[/tex]
Explanation:
Required
Evaluate each expression
The simple rules to follow are:
(1) All expressions in bracket will be evaluated based on its data type
(2) Divisions will return only integer values
(3) Integers immediately after string values will be concatenated (not added)
So, the results are as follows:
[tex](a)\ 4 + 1 + 9 + "." + (-3 + 10) + 11 / 3[/tex]
Evaluate till a string is encountered
[tex]4 + 1 + 9 = 14[/tex]
Followed by "."
Then:
[tex](-3 + 10) = 7[/tex]
[tex]11/ 3 = 3[/tex]
[tex]"." + (-3 + 10) + 11/3 = "."73[/tex] -- because expressions after string operations are concatenated.
So, we have:
[tex]4 + 1 + 9 + "." + (-3 + 10) + 11 / 3 = 14"."43[/tex]
[tex](b)\ 8 + 6 * -2 + 4 + "0" + (2 + 5)[/tex]
Evaluate till a string is encountered
[tex]8 + 6 * -2 + 4 =0[/tex]
[tex]"0" + (2 + 5) ="0"7[/tex]
So, we have:
[tex]8 + 6 * -2 + 4 + "0" + (2 + 5) = 0"0"7[/tex]
[tex](c)\ 1 + 1 + "8 - 2" + (8 - 2) + 1 + 1[/tex]
Evaluate till a string is encountered
[tex]1 + 1 = 2[/tex]
[tex]"8 - 2" + (8 - 2) + 1 + 1 = "8 - 2"611[/tex]
So, we have:
[tex]1 + 1 + "8 - 2" + (8 - 2) + 1 + 1 = 2"8 - 2"611[/tex]
[tex](d)\ 5 + 2 + "(1 + 1)" + 4 + 2 * 3[/tex]
Evaluate till a string is encountered
[tex]5 + 2 =7[/tex]
[tex]"(1 + 1)" + 4 + 2 * 3 = "(1 + 1)"46[/tex] --- multiply 2 and 3, then concatenate
So, we have:
[tex]5 + 2 + "(1 + 1)" + 4 + 2 * 3= 7"(1 + 1)"46[/tex]
[tex](e)\ "1" + 2 + 3 + "4" + 5 * 6 + "7" + (8 + 9)[/tex]
Since a string starts the expression, the whole expression will be concatenated except the multiplication and the expressions in bracket.
So, we have:
[tex]"1" + 2 + 3 + "4" + 5 * 6 + "7" + (8 + 9) = "1"23"4"30"7"17[/tex]
Select the correct statement(s) regarding 4B5B encoding.
a. 4B5B is used to map four codeword bits into a five bit data word
b. 4B5B information bit rate is 80% of the total (information plus overhead) bit rate
c. 4B5B information bit rate is 20% of the total (information plus overhead) bit rate
d. all statements are correct
Answer:
b. 4B5B information bit rate is 80% of the total information plus overhead bit rate.
Explanation:
4B5B bit rate encoding means there is 80% of the bit rate which included all the information plus the overheads. There is 20% of lack in bit rate due to encoding code words which converts data into smaller bits.
Factors to consider when buying a computer
Answer:
money
Explanation:
for working for socializing with orher
Write a RainFall class that stores the total rainfall for each of 12 months into an array of doubles. The program should have methods that return the following:
the total rainfall for the year
the average monthly rainfall
the month with the most rain
the month with the least rain
Demonstrate the class in a complete program.
Input Validation: Do not accept negative numbers for monthly rainfall figures.
import java.io.*;
import java.util.*;
public class Rainfall
{
Scanner in = new Scanner(System.in);
private int month = 12;
private double total = 0;
private double average;
private double standard_deviation;
private double largest;
private double smallest;
private double months[];
public Rainfall()
{
months = new double[12];
}
public void setMonths()
{
for(int n=1; n <= month; n++)
{
System.out.println("Enter the rainfall (in inches) for month #" + n + ":" );
months[n-1] = in.nextInt();
}
}
public double getTotal()
{
total = 0;
for(int i = 0; i < 12; i++)
{
total = total + months[i];
}
System.out.println("The total rainfall for the year is" + total);
return total;
}
public double getAverage()
{
average = total/12;
System.out.println("The average monthly rainfall is" + average);
return average;
}
public double getLargest()
{
double largest = 0;
int largeind = 0;
for(int i = 0; i < 12; i++)
{
if (months[i] > largest)
{
largest = months[i];
largeind = i;
}
}
System.out.println("The largest amout of rainfall was" + largest +
"inches in month" + (largeind + 1));
return largest;
}
public double getSmallest()
{
double smallest = Double.MAX_VALUE;
int smallind = 0;
for(int n = 0; n < month; n++)
{
if (months[n] < smallest)
{
smallest = months[n];
smallind = n;
}
}
System.out.println("The smallest amout of rainfall was" + smallest +
"inches in month " + (smallind + 1));
return smallest;
}
public static void main(String[] args)
{
Rainfall r = new Rainfall();
r.setMonths();
System.out.println("Total" + r.getTotal());
System.out.println("Smallest" + r.getSmallest());
System.out.println("Largest" + r.getLargest());
System.out.println("Average" + r.getAverage());
}
}
Answer:
Explanation:
The code provided worked for the most part, it had some gramatical errors in when printing out the information as well as repeated values. I fixed and reorganized the printed information so that it is well formatted. The only thing that was missing from the code was the input validation to make sure that no negative values were passed. I added this within the getMonths() method so that it repeats the question until the user inputs a valid value. The program was tested and the output can be seen in the attached image below.
import java.io.*;
import java.util.*;
class Rainfall
{
Scanner in = new Scanner(System.in);
private int month = 12;
private double total = 0;
private double average;
private double standard_deviation;
private double largest;
private double smallest;
private double months[];
public Rainfall()
{
months = new double[12];
}
public void setMonths()
{
for(int n=1; n <= month; n++)
{
int answer = 0;
while (true) {
System.out.println("Enter the rainfall (in inches) for month #" + n + ":" );
answer = in.nextInt();
if (answer > 0) {
months[n-1] = answer;
break;
}
}
}
}
public void getTotal()
{
total = 0;
for(int i = 0; i < 12; i++)
{
total = total + months[i];
}
System.out.println("The total rainfall for the year is " + total);
}
public void getAverage()
{
average = total/12;
System.out.println("The average monthly rainfall is " + average);
}
public void getLargest()
{
double largest = 0;
int largeind = 0;
for(int i = 0; i < 12; i++)
{
if (months[i] > largest)
{
largest = months[i];
largeind = i;
}
}
System.out.println("The largest amount of rainfall was " + largest +
" inches in month " + (largeind + 1));
}
public void getSmallest()
{
double smallest = Double.MAX_VALUE;
int smallind = 0;
for(int n = 0; n < month; n++)
{
if (months[n] < smallest)
{
smallest = months[n];
smallind = n;
}
}
System.out.println("The smallest amount of rainfall was " + smallest +
" inches in month " + (smallind + 1));
}
public static void main(String[] args)
{
Rainfall r = new Rainfall();
r.setMonths();
r.getTotal();
r.getSmallest();
r.getLargest();
r.getAverage();
}
}
Write a program that launches 1,000 threads. Each thread adds 1 to a variable sum that initially is 0. You need to pass sum by reference to each thread. In order to pass it by reference, define an Integer wrapper object to hold sum. Run the program with and without synchronization to see its effect. Submit the code of the program and your comments on the execution of the program.
Answer:
Following are the code to the given question:
import java.util.concurrent.*; //import package
public class Threads //defining a class Threads
{
private Integer s = new Integer(0);//defining Integer class object
public synchronized static void main(String[] args)//defining main method
{
Threads t = new Threads();//defining threads class object
System.out.println("What is sum ?" + t.s);//print value with message
}
Threads()//defining default constructor
{
ExecutorService exe = Executors.newFixedThreadPool(1000);//defining ExecutorService class object
System.out.println("With SYNCHRONIZATION........");//print message
for(int i = 1; i <= 1000; i++)//defining a for loop
{
exe.execute(new SumTask2());//calling execute method
System.out.println("At Thread " + i +" Sum= " + s + " , ");//print message with value
}
exe.shutdown();//calling shutdown method
while(!exe.isTerminated())//defining while loop that calls isTerminated method
{
}
}
class SumTask2 implements Runnable//calling SumTask2 that inherits Runnable class
{
public synchronized void run()//defining method run
{
int value = s.intValue() + 1;//defining variable value that calls intvalue which is increment by 1
s = new Integer(value);//use s to hold value
}
}
}
Output:
Please find the attached file.
Explanation:
In this code, a Threads class is defined in which an integer class object and the main method is declared that creates the Threads class object and calls its values.
Outside the method, the default constructor is declared that creates the "ExecutorService" and prints its message, and use a for loop that calls execute method which prints its value with the message.
In the class, a while loop is declared that calls "isTerminated" method, and outside the class "SumTask2" that inherits Runnable class and defined the run method and define a variable "value" that calls "intvalue" method which is increment by 1 and define s variable that holds method value.