C++ programming interest using for loops.
I'm fairly new to C++ programming. I really don't get for loops, and wanted help with this question. How do I go about it?
1a.
Write a program to ask the user for the starting balance of their savings account, what interest rate they are earning, and how many years they are planning to keep the account open. To calculate the new balance, including compounded interest: use a for loop to loop through the number of years the user specifies (1, 2, 3, 4, … years) and each time through the loop update the account balance using the following formula:
balance = balance * (1 + interest rate / 100.0) //
this adds one year’s interest to the account
balance = initialBalance * (1 + interest rate / 100.0) // this will
only calculate one year’s interest no matter how
many times you repeat it.
1b.
Now write the code to show the user how much money they would have after ONE year, depending on the different interest rates. Ask the user for a minimum and maximum interest rate (e.g. 3.0 and 8.5 … note you may need to swap the values if the user enters them out of order). Use a for loop to loop through the possible interest rates at 0.5 increments (3.0, 3.5, 4.0, 4.5, … 8.5) and each time through the loop calculate the user’s account balance after one year at the specified interest rate:
balance = initialBalance * (1 + interest rate / 100.0) // this time you want the initial balance
In: Computer Science
Write a class encapsulating the concept of a student, assuming a student has the following attributes: a name, a Social Security number, and a GPA (for instance, 3.5). Include a constructor, the accessors and mutators, and methods toString and equals. Write a client class (test driver with main method) to test all the methods in your class (create 2 student objects, print the name, social security number and GPA of the 2 students, check if the two student’s GPA is the same or equal, change the name of the first student).
In: Computer Science
FOR JAVA (ZYBOOK) Write a method swapArrayEnds() that swaps the first and last elements of its array parameter. Ex: sortArray = {10, 20, 30, 40} becomes {40, 20, 30, 10}.
I can't modify/change any of the code. I can only add code to implement this where it says /* Your solution goes here */.
This is the code:
import java.util.Scanner;
public class ModifyArray {
/* Your solution goes here */
public static void main (String [] args) {
Scanner scnr = new Scanner(System.in);
int numElem = 4;
int[] sortArray = new int[numElem];
int i;
int userNum;
for (i = 0; i < sortArray.length; ++i) {
sortArray[i] = scnr.nextInt();
}
swapArrayEnds(sortArray);
for (i = 0; i < sortArray.length; ++i) {
System.out.print(sortArray[i]);
System.out.print(" ");
}
System.out.println("");
}
}
In: Computer Science
You are the IT director at Big Ten University. As part of a training program, you decide to draw a DFD that includes some obvious mistakes to see whether your newly hired junior analysts can find them. You came up with the diagram 0 DFD shown in Figure 5-19. Based on the rules explained in this chapter, how many problems should the analysts find?
In: Computer Science
A cubic polynomial is of the form: f(x) = Ax^3 + Bx^2 + Cx + D
A root of the polynomial is a value, x, such that f(x)=0.
Write a program that takes in the coefficients of a cubic polynomial: A, B, C, and D. The program finds and reports all three roots of the polynomial.
Hint: First use bisection method to determine a single root of the polynomial. Then divide the polynomial by its factor to come up with a quadratic equation. You may use the procedure described here: https://www.purplemath.com/modules/synthdiv.htm. Subsequently, solve the quadratic equation.
The code should be written in python.
In: Computer Science
In Java
The Problem
In his book Irreligion, the mathematician John Allen Paulos tells an amusing story about the Dutch astronomer Cornelis de Jager, "who concocted the following algorithm for personalized physical constants, [and] used it to advance a charming theory about the metaphysical properties of Dutch bicycles." First select any positive real-valued universal physical or mathematical constant that seems interesting to you, e.g., π, e, Planck's constant, the atomic weight of molybdenum, the boiling point of water in Kelvin, whatever you like. Call this constant μ. Then select any four positive real numbers not equal to 1 that have personal meaning to you, e.g., your favorite number, day or month or year of birth, age in fortnights or seconds, weight in stones or grams, height in furlongs or millimeters, number of children, house number, apartment number, zip code, last four digits of SSN, whatever you like. Call these four personal numbers w, x, y, and z.
Now consider the de Jager formula waxbyczd, where each of a, b, c, and d is one of the 17 numbers {-5, -4, -3, -2, -1, -1/2, -1/3, -1/4, 0, 1/4, 1/3, 1/2, 1, 2, 3, 4, 5}. The "charming theory" asserts that the de Jager formula with your four personal numbers can be used to approximate μ within a fraction of 1% relative error. For example, suppose you choose to approximate the mean distance from the earth to the moon in miles: μ = 238,900. And suppose you are an OSU sports fan, so your personal numbers are the number of wins in OSU's last national championship season (14), the seating capacity of Ohio Stadium (102,329), the year of Jesse Owens' four gold medals in Berlin (1936), and your jersey number when you played high school field hockey (13). Then the value of 14-5102329119361/2134 is about 239,103, which is within about 0.08% of μ.
Your job is to create a Java program that asks the user what constant μ should be approximated, and then asks in turn for each of the four personal numbers w, x, y, and z. The program should then calculate and report the values of the exponents a, b, c, and d that bring the de Jager formula as close as possible to μ, as well as the value of the formula waxbyczd and the relative error of the approximation to the nearest hundredth of one percent (see SimpleWriter print(double, int, boolean) for a method you may find useful for this). Note that your program must find the combination of exponents that minimizes the error of the approximation of μ and then print the exponents, best approximation, and corresponding relative error. (Essentially this program could be used to disprove the "charming theory" by finding μ, w, x, y, and z such that the best approximation of μ results in a relative error that is greater than 1%.)
Method
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
/** * Repeatedly asks the user for a positive real number until the user enters * one. Returns the positive real number. * * @param in * the input stream * @param out * the output stream * @return a positive real number entered by the user */ private static double getPositiveDouble(SimpleReader in, SimpleWriter out) {...}
/** * Repeatedly asks the user for a positive real number not equal to 1.0 * until the user enters one. Returns the positive real number. * * @param in * the input stream * @param out * the output stream * @return a positive real number not equal to 1.0 entered by the user */ private static double getPositiveDoubleNotOne(SimpleReader in, SimpleWriter out) {...} |
In: Computer Science
Decision Structures Calorie Calculator Assignment Overview This assignment will give you practice with numerical calculations, simple input/output, and if-else statements. Program Objective: In this exercise, you will write a program the calculates the Daily Caloric needs for weight lose diet. According to everydayhealth.com they recommend this daily caloric formula for a weight loss diet: BMR + Activity Level - 500 calories. Calories Calculator The Harris-Benedict equation estimates the number of calories your body needs to maintain your weight if you do no exercise. This is called your basal metabolic rate or BMR. The Calories needed for a woman to maintain her weight is: BMR = 655 + (4.3 * weight in pounds) + (4.7 * height in inches) - (4.7 * age in years) The Calories needed for a man to maintain his weight is: BMR = 66 + (6.3 * weight in pounds) + (12.9 * height in inches) - (6.8 * age in years) Next, the total daily caloric requirement is calculated by multiplying your BMR by your level of activity: • If the person is inactive (rarely exercise), then increase the calculated BMR 20%. • If the person is somewhat active, then increase the calculated BMR by 30% • If the person is active, then increase the calculated BMR by 40% • If the person is highly active then increase the calculated BMR by 50% Program Specification: Write a program that allows the user to input their weight in pounds, height in inches, and age in years. Ask the user to input the string “M” if the user is a man and “W” if the user is a woman. Use only the male formula to calculate calories if “M” is entered and use only the women formula to calculate calories if “W” is entered. Ask the user if he or she is: A. Inactive B. Somewhat active (exercise occasionally) C. Active (exercise 3-4 days per week) D. Highly active (exercise every day) • If the user answers “Inactive” then increase the calculated BMR by 20 percent. • If the user answers “Somewhat active” then increase the calculated BMR by 30 percent. • If the user answers “Active” then increase the calculated BMR by 40 percent. • Finally, if the user answers “Highly active” then increase the calculated BMR by 50 percent. • The program should then output the calculated daily Calories intake for this person in order to lose one pound per week by subtracting 500 calories from the calculated BMR. Input Errors • If the user enters an age either < 1 or > 100, instantly end the program with an error message. • If the user enters a height < 10 or > 100, instantly end the program with an error message. • If the user enters a weight < 10 or > 500, instantly end the program with an error message. • You can assume that the user does not type some non-numeric value. You don't have to test for this kind of non-numeric error. • If the user does not enter ‘M' for male calculation or 'W' for female calculation, instantly end the program with an error message. • If the user does not enter A, B, C, or D when prompted, instantly end the program with an error message. These limits must be defined as symbolic constants, which should be used throughout the program. Rules: • For this assignment you are limited to the Java features in Chapters 1 through 3; you are not allowed to use more advanced features to solve the problem. Please do not use Java features that are not covered in lecture or the textbook. • Use class constants as appropriate to represent important fixed data values in your program. • Follow programming guidelines and Java’s naming standards about the format of ClassNames, variableNames, and CONSTANT NAMES. • Notice that all real numbers output by the program are printed with no more than 2 digits after the decimal point. To achieve this, you may use the System.out.printf method. • Add the header to the class file and copy/paste the output that is produced by your program into the bottom of the source code file, making it into a block comment. • Class Name: Your program class should be called CalorieCalculator.
In: Computer Science
Hello I need a small fix in my program. I need to display the youngest student and the average age of all of the students. It is not working Thanks.
#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
struct Student {
string firstName;
char middleName;
string lastName;
char collegeCode;
int locCode;
int seqCode;
int age;
};
struct sort_by_age {
inline bool operator() (const Student& s1, const Student& s2)
{
return (s1.age < s2.age); // sort according to age of student
}
};
// main function to run program
int main() {
//CHANGE: vector students; TO vector students;
vector<Student> students; // create vector object to hold students data
ifstream Myfile; // create input file stream object
Myfile.open("a2data.txt"); // open file
// check if file is open
if (!Myfile.is_open()) {
// display error message if file could not be opened
cout << "Could not open the file!";
return 0; //terminate
}
//CHANGE: vector words; TO vector words;
vector<string> words; // create vector object to store words from input file
//read input from file line by line
string line;
while (!Myfile.eof()) {
getline(Myfile, line); // readline from input file stream
line.c_str(); // convert string in to char array
// file given in eample does not contain one record each line
// but it hase some patern for reading
// each word is seprated by space
//read the liine till space is encountered and get the word
int i = 0; // iterator to iterate over line
string word = "";
while (line[i] != '\0') {
// loop till end of line
if (line[i] != ' ') {
word = word + line[i]; // build word with char
i++;
}
else {
if(word!="")
words.push_back(word); // add word to vector
word = ""; //reset word to empty string
i++; //ignore white space
}
}//end of line
words.push_back(word); // add word to vector
}//end of file
//when done reading input from file close the file stream
Myfile.close();
int count = 0; // counts the words proceesed from vector object words
string fname = words.at(count); // variable to store first name of student
count++; //move to next element in the vector
//CHANGE: count < words.size() TO count < words.size() - 2
// at least two words are read in an iteration, so at least two should remain to be read - last name + student id
while (count < words.size() - 2) {
// loop till end of vector words
// create student object
Student s;
//assign first name to student
s.firstName = fname;
//next element in words is middle name
//assign first char to middle name
string mname = words.at(count);
s.middleName = mname[0];
count++;
//next element is last name of student
//assign next word to student
s.lastName = words.at(count);
//CHANGE: start
//If there was no middle name, this is the student id + first name of next student
if(words.at(count).size() >= 12) // college code + locCode + seq + age
{
if(words.at(count)[1] >= '0' && words.at(count)[1] <= '9') // if second character is a digit
{
// this is the student id field, and there is no middle name
count --; // move one step back for next iteration
s.middleName = ' '; //blank middle name
s.lastName = words.at(count);
}
}
//CHANGE: end
count++;
//next element is student id + first name of next student
//id contains college code at first latter
string id = words.at(count);
count++;
//assign college code to the student
s.collegeCode = id[0];
//next 2 char in id contain location
string loc = "";
loc = loc + id[1];
loc = loc + id[2];
// assign location to student
s.locCode = stoi(loc); // convert string to integer
//next 6 char in id contain seqcode
string seq = "";
for (int j = 3; j < 9; j++) {
seq = seq + id[j];
}
// assign seqcode to student
s.seqCode = stoi(seq); //convert string to int
//next 3 char in id contains age
string age = "";
age = age + id[9];
age = age + id[10];
age = age + id[11];
//assign age to student
s.age = stoi(age); // convert string to int
//remainig latters in id contains next student's first name
// delete id of previous student to get name of next student
fname = id.erase(0, 12); // delete first 12 char from id and assign remaining to fname
// add student to student
students.push_back(s);
}
// clear the vector as done working with words
words.clear();
//sort vector according to age of students
sort(students.begin(), students.end(), sort_by_age());
// formating output
cout << setw(15) << left << "Last Name";
cout << setw(15) << left << "Midlle Name";
cout << setw(15) << left << "First Name";
cout << setw(15) << left << "College Code";
cout << setw(12) << left << "Location";
cout << setw(12) << left << "Sequence";
cout << setw(12) << left << "Age" << endl;
cout << "=======================================================================================" << endl;
// print all students
for (int i = 0; i < students.size(); i++) {
cout << setw(15) << left << students.at(i).lastName;
cout << setw(15) << left << students.at(i).middleName;
cout << setw(20) << left << students.at(i).firstName;
cout << setw(13) << left << students.at(i).collegeCode;
cout << setw(10) << left << students.at(i).locCode;
cout << setw(12) << left << students.at(i).seqCode;
cout << students.at(i).age << endl;
}
//print average age
cout << endl;
int avg_age = ageCalc(arry, youngest);
cout<<"Average age is: "<<avg_age<<endl;
cout<<"Youngest student is "<<youngest->firstName<<" "<<youngest->MiddleN<<" "<<youngest->LastN<<endl;
for(int i=0; i<index; i++){
delete arry[i];
}
return 0;
}
int ageCalc(Student *studs[], Student *&youngest){
youngest = studs[0];
int i = 0;
int avg_age = 0;
while(studs[i]!=NULL){
avg_age += studs[i]->age;
if(youngest->age>studs[i]->age)
youngest = studs[i];
i++;
}
return avg_age/i;
}
File needed:
https://drive.google.com/file/d/15_CxuGnFdnyIj6zhSC11oSgKEYrosHck/view?usp=sharing
In: Computer Science
Iterative Merge Sort is not working
#include
#include
#include
int* b;
void merge(int a[], int left, int mid, int right)
{
int i = left, j = mid + 1, k = left;
while (i <= mid && j <= right)
{
if (a[i] < a[j])
b[k++] =
a[i++];
else
b[k++] =
a[j++];
}
for (; i <= mid; i++)
{
b[k++] = a[i];
}
for (; j <= right; j++)
{
b[k++] = a[j];
}
for (int i = left; i <= right; i++)
{
a[i] = b[i];
}
}
void mergesort(int a[], int n)
{
int p, left, right, mid, i;
for (p = 2; p <= n; p = p * 2)
{
for (i = 0; i + p - 1 < n; i = i
+ p)
{
left = i;
right = i + p -
1;
mid = (left +
right) / 2;
merge(a, left,
mid, right);
}
}
if (p / 2 < n)
{
merge(a, 0, (p / 2) - 1, n -
1);
}
}
void main()
{
int max, * a;
scanf("%d", &max);
a = (int*)malloc(sizeof(int) * max);
b = (int*)malloc(sizeof(int) * max);
for (int i = 0; i < max; i++)
{
scanf("%d", &a[i]);
}
mergesort(a, max);
for (int i = 0; i < max; i++)
{
printf(" %d", a[i]);
}
}
input 50
50 49 48 47 46 45 ~ 5 4 3 2 1
output
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 1 2 19 20 21 22 23 24 ~ 50
why 1,2 are between in 18 and 19?
please answer and correct code
In: Computer Science
1 Please answer the following:
a) Rank the following storage systems from slowest to fastest: a. Hard-disk drives b. Registers c. Optical disk d. Main memory e. Nonvolatile memory f. Magnetic tapes g. Cache
b) How are iOS and Android similar? How are they different?
In: Computer Science
Write a Python program that reads in an amount in cents and prints the dollar amount in that and the remaining value in cents. For example, if the amount reads in is 360 (cents), the program would print 3 dollars and 60 cents. if the amount read in is 75 (cents), the program would print 0 dollars and 75 cents.
In: Computer Science
C++
How would I sort my output to evaluate it by sorting the column by it's size? I didn't include my full program but here is the main.cpp where i'm supposed to sort the output by column size.
//User Libraries
#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;
//User Libraries
#include "Table.h"
#include "Triangle.h"
//Global Constants
//Function Prototype
void prntRow(RowAray *,int);
void prntTab(Table *);
void prntTri(Triangle *);
//Execution Begins Here!
int main(int argc, char** argv) {
//Initialize the random seed
srand(static_cast<unsigned int>(time(0)));
//Declare Variables
// creates a random number of rows from 1 to 10
int rows=(rand()%10)+ 1;
//creates a random number of columns from 1 to 10
int cols=(rand()%10 )+1;
int perLine=cols/2;
//Test out the RowAray
RowAray row(cols);
//Print the RowAray
cout<<"The Row Array size = "<<row.getSize()
<<" printed "<<perLine<<" per Line";
prntRow(&row,perLine);
//Test out the Table
Table tab(rows,cols);
//Print the Table
cout<<"The table size is [row,col] =
["<<rows<<","<<cols<<"]";
prntTab(&tab);
//Test out the Triangular Table
Triangle tri(rows);
//Print the Triangular Table
cout<<"The triangular table size is [row,row] =
["<<rows<<","<<rows<<"]";
prntTri(&tri);
//Exit Stage Right
return 0;
}
//Fill a triangular matrix
int **fillAry(int *col,int n){
int **array=new int*[n];
for(int i=0;i<n;i++){
array[i]=new int[col[i]];
}
for(int i=0;i<n;i++){
for(int j=0;j<col[i];j++){
array[i][j]=rand()%9+1;//1 Digit numbers [1-9]
}
}
return array;
}
void prntRow(RowAray *a,int perLine){
cout<<endl;
for(int i=0;i<a->getSize();i++){
cout<<a->getData(i)<<" ";
if(i%perLine==(perLine-1))cout<<endl;
}
cout<<endl;
}
void prntTab(Table *a){
cout<<endl;
for(int row=0;row<a->getSzRow();row++){
for(int col=0;col<a->getSzCol();col++){
cout<<a->getData(row,col)<<" ";
}
cout<<endl;
}
cout<<endl;
}
void prntTri(Triangle *a){
cout<<endl;
for(int row=0;row<a->getSzRow();row++){
for(int col=0;col<=row;col++){
cout<<a->getData(row,col)<<" ";
}
cout<<endl;
}
cout<<endl;
}
In: Computer Science
Explain the similarities and differences between spiders, crawlers and bots in relation to search engines. Additionally with the Search Engine Optimization elements (SEO); explaining the terms positioning and placement as they relate to SEO, with examples.
In: Computer Science
Cpp challenge
Description
The purpose of this challenge is to use the WHILE loop to control program flow. This challenge will use the WHILE loop in various ways.
Requirements
Write all your code for the following steps in one file.
Do Not Use
You must use the WHILE statement. You may not use any other looping mechanism.
Sample Interaction / Output
Enter a string to be repeated: coffee How many times to show? 5 coffee coffee coffee coffee coffee 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 100 90 80 70 60 50 40 30 20 10 Enter a number: 3 3 x 2 = 6 Enter a number: 7 7 x 2 = 14 Enter a number: -2 Enter a string: yo Enter a string: hi Enter a string: hola Enter a string: sup Enter a string: bye
In: Computer Science
In: Computer Science