Working with files & FOR loop [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
My task is: in every language is n most used words. A boy after d days is leaving for Sweden. Wanting to understand Swedish, the first day he learns z words and the each following day k words more than a day before. Write a program, which would check if a boy will successfully will learn n words during d days.
Let's say that he needs to learn 100 words. He has 20 days. The first day he learned 5 words. Each following day he learned 1 words more than a day before.
In this case answer should be: yes (he will successfully will learn it during 20 days), and 11 (during 11 days he will learn 100 words).
I have a code written.
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main()
{
int n, d=0, k, z;
ofstream fr("Rezults.txt");
ifstream fd("Data.txt");
fd>>n>>d>>z>>k;
int learned_words = 0;
for(int i=0; i<d; i++){
learned_words += z;
z = z+k;
}
if(n<=learned_words) {
fr<<"Yes"<<endl;
}
else
{
fr<<"No"<<endl;
}
z=z-d; d=0;
for(int m=0; m<=n; m+=z, z+=k, d++) {}
cout << "You need " << d << " days to learn " << n << " words";
fd.close();
fr<<d;
fr.close();
return 0;
}

You can simply count the loop by using the for loop in this way:
for (i=z; i<=n; i++)
{
}
cout<< i << endl;
You can simply see the variable "i"'s value right after the loop

This simple function solves the problem in the beginning of your question:
// z : the number of words learned during the first day
// k : this much more we learn after every day
// (i.e first day we learn z words, then z+k, then z+k+k etc.)
// d : this many days we have time to learn
// n: this many words we should learn
bool solve(int z, int d, int k, int n) {
int learned_words = 0;
for(int i=0; i<d; i++){
learned_words += z;
z = z+k;
}
if(n<=learned_words) {
return true;
}
return false;
}
To answer your question about loops, I think the following very simple loop would work:
int n = 100;
int z = 5;
int k = 1;
int d = 0;
for(int m=0; m<n; m+=z, z+=k, d++) {}
cout << "You need " << d << " days to learn " << n << " words";
Here the loop will get executed the minimal number of times needed to learn those n words. The variable d counts the days needed and must be declared before the loop. m counts how many words we have learned.

Despite having for loop in the title, there's no requirement for the loop in the task and no reason to actually use it here (unless you're limited to integer arithmetic).
It would be much easier to simply compute days needed to learn n words (it's simple quadratic equation) and compare it with d.
Number of words (y) learnt during first x days is:
y = z * x + k * x * (x-1)/2. So just solve this equation for y = n.
I'd do something like: (variables a and b are coefficients of the quadratic equation).
const double a = k/2.0;
const double b = z-k/2.0;
const double days_needed = -b + ::sqrt(b*b + 4 * a * n)/(2.0 * a);
std::cout << (days_needed <= d ?"yes":"no") << ", you need " << ::ceil(days_needed) << "days\n";

Related

Incorrect mathematical results calculating power series [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
#include <iostream>
#include <cmath>
using namespace std ;
int main ()
{
int n, sum=0 ;
cout<< "Input number of terms: " ;
cin>> n ;
for (int i=1; i<=n; i++)
{
int k = pow(10, i) - 1 ;
cout << k ;
if(i < n)
{
cout<< " + " ;
}
sum += k ;
}
cout << "\nThe sum of the series = " << sum ;
{int m;cin>>m;}
return 0 ;
}
every time I run this code it gives me weird output like
9 + 98 + 999 + 9998 + ...
it subtracts some Ks from 2 !!
The rule is mathematically right and there is no syntax errors.
Is it the way of declaring k inside the loop or it's an compiler error ?
So, what's wrong here?
Here is the for loop without using the pow function:
int power = 10;
for (int i = 1; i < n-1; ++i)
{
const int k = power - 1 ;
cout << k;
if(i < n)
{
cout<< " + " ;
}
sum += k;
power *= 10; // This is important.
}
This should be more accurate than using pow because there is no conversions between integer and floating point.
Also, you may want to try using the series from 0 .. (n-1).
I think the best thing to do is to create your own power function because pow() is not working that way before when I used it. Kinda like this one
int pow_num(int base_num, int exp_num)
{
int result = 1;
for(int i = 0; exp_num > i; ++i)
{
result = result * base_num;
}
return (result);
}

c++: general q about for-statements and arguments [duplicate]

This question already has answers here:
What is the correct way of using C++11's range-based for?
(4 answers)
Closed 4 years ago.
I'm in the process of learning c++. I've come across an assignment about temperatures I don't understand. Could you guys clarify some things for me?
Here's the code
// compute mean and median temperatures
int main()
{
vector<double> temps; // temperatures
for (double temp; cin>>temp; ) // read into temp
temps.push_back(temp); // put temp into vector
**// compute mean temperature:
double sum = 0;
for (int x : temps) sum += x;
cout << "Average temperature: " << sum/temps.size() << '\n';**
// compute median temperature:
sort(temps); // sort temperatures
cout << "Median temperature: " << temps[temps.size()/2] << '\n';
}
Now the second block (//compute mean temperature) is the stuff I cannot follow.
First off, a for-statement is used with a single argument. Won't this mean that there is just an initial expression and no condition?
I also don't think I have a firm understanding of int X : temps int X isn't defined anywhere else in this bit of code. Won't it cause an error as it has no value assigned to it? Let's say it has a value of 1; what does it do/what does it check? Does it check how many times X fits in vector temps? Why not do this then:
int sum_of_measurements = 0; //value of all measurements
for (int y = 0; y <= temps.size(); ++y){
sum_of_measurements = sum_of_measurements + temps[y]; // add value of measurement to the total for each measurement
}
double mean = sum_of_measurements/temps.size();
cout << mean <<'\n';
//rest of code
What's this identifier called so I can learn more about it (the : in int X : temps)
Thanks :)
That's the range-based for loop, introduced in C++11.
A statement like:
for (int someVal: someCollection)
will iterate over someCollection with someVal being set to each item within the collection (one per iteration).
In your specific case (after changing the type of x to one more suitable), the snippet:
double sum = 0;
for (double x : temps)
sum += x;
is functionally equivalent to:
double sum = 0;
for (int i = 0; i < temps.size(); ++i)
sum += temps[i];

Display powers in C++ loop [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have to solve following exercise
Write a program to display 1,5,25,125 upto n terms.
I am in 11th grade and I have tried of many ways of writing this program.
Value of control variable is one, and it's less than n.
But by how much should it differ so that it obeys the above question?
Please answer if you could in simple language.
Also should I use a special variable for power?
Thanks in advance, Abhijith
Print out the old value times five, starting with 1
Basic mockup:
auto PrintExercise(std::size_t terms) -> void {
std::size_t lastResult = 1;
for (std::size_t i = 0; i < terms; ++i) {
std::cout << std::to_string(lastResult) << std::endl;
lastResult *= 5;
}
}
Edit: Turns out I overthought this. It would be easier to just print the power of the control variable.
auto PrintExercise(std::size_t terms) -> void {
for (std::size_t i = 0; i < terms; ++i) {
std::cout << std::to_string(pow(5,n)) << std::endl;
}
}
Since the correct answers have already been provided, here's the same approach using recursion instead of iteration (loops) with (hopefully) enough comments to explain the process. Just for completeness. Give it a try, it's fun!
#include <iostream>
//value = the value that will be printed
//end = after how many iterations you want to stop
void PowerOfFive( const int value, const int end )
{
//Print the current value to the console. This is more or
//less everything the function does...
std::cout << value << ", ";
//... but a function can also call itself, with slightly different
//values in this case. We decrement "end" by 1 and let the whole
//process stop after "end" reaches 0. As long as we're doing that,
//we're multiplying "value" by five each time.
if ( end != 0 )
{
PowerOfFive( value * 5, end - 1 );
}
}
int main()
{
//Example for the above
//Start:
// 1st PowerOfFive(1, 3)
// --> prints 1
// --> calls 2nd PowerOfFive(1 * 5, 3 - 1)
// --> prints 5
// --> calls 3rd PowerOfFive(5 * 5, 2 - 1)
// --> prints 25
// --> calls 4th PowerOfFive(25 * 5, 1 - 1)
// --> prints 125
// --> function 4 ends because "end" has reached 0
// --> function 3 ends
// --> function 2 ends
// --> function 1 ends
PowerOfFive( 1, 3 );
getchar( );
return 0;
}
It seems you want to print powers of 5 upto n, not sure what you mean by control variable. So this should work
for (int i=0;i<=n;++i) cout << pow(5,i) << ", " ;
Iteration value is by 5, it can be done with pow() function & also by using simple for loop like this.
power=0;
cout<<power;
for(i=0;i<n;i++)
{
power=power*5; // OR power*=5
}
cout<<power;
Im adding code see if it helps
#include<iostream>
#include <cmath>
using namespace std;
int main()
{
int exp;
float base;
cout << "Enter base and exponent respectively: ";
cin >> base >> exp;
for(int i=0;i<exp;i++)
{
cout << "Result = " << pow(base, i);
}
return 0;
}
You have to pass the base and exponent value and for your question it should be base=5 and exp=3 and your output will be till 1 , 5 ,25

How to make this algorithm faster? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am trying to come up with the following algorithm:
The input is unsigned integer number.
The output is the size of the array of unordered pairs of unsigned integers, which, when multiplied, give a number less then or equal to the input.
I have one naive implementation working, but it is way too slow for my purpose (compl. O(n^2), please correct me if I am wrong). My question is: how to make it faster?
#include <iostream>
using namespace std;
bool notInYet(int t[][1], int mi, int ma, int m) {
bool val = true;
for(int i = 0; i < m; i++)
if(t[i][0] == mi && t[i][1] == ma)
val = false;
return val;
}
int main() {
int n, m;
int t[100000][1];
cin >> n;
m = 0;
for(int i = 1; i <= n; i++) {
for(int j = 1; j*i <= n && j <= i; j++) {
if(notInYet(t, j, i, m)) {
t[m][0] = j;
t[m][1] = i;
//cout << "t[" << m << "] = (" << t[m][0] << ", " << t[m][1] << ")" << endl;
m++;
}
}
}
cout << m << endl;
return 0;
}
I think it should be something like that - pseudocode:
int counter = 0;
for int i = 1 to sqrt(input), i++ {
if (input % i == 0) counter++;
}
counter is an answer if you need unique pairs, otherwise you need to multiply it by 2 (and sub 1 if input % sqrt(input) == 0)
If I'm reading correctly #jauser's algorithm doesn't get what you want.
If the target is 5, then the pairs are (1,1)(1,2)(1,3)(1,4)(1,5)(2,2). So the answer is 6. His algorithm will produce 1 because 5 mod 1 == 0, but not mod 2.
In general, if the target is n, then you know (1,k) is a counted pair for all k from 1 to n. There are n - 1 + 1 = n of these. Now you have (2,k) for k from 2 to floor(n/2) (skip 1 because your pairs are unordered). There are n/2-2+1 of these. Continue this through (j,k) for j= floor(sqrt(n)). Putting this is pseudocode
count = 0;
for j in 1 .. floor(sqrt(n))
count += floor(n / j) - j + 1;
Maybe there is even some clever series solution that gets this to a constant time calculation.
Am I missing something in the problem?
Well, you are spending a lot of time effectively calculating the following per i:
j= n/i;
So if you just do that you reduce the complexity to O(n). You can halve it also since the list will contain both (i, j) and (j, i) when i!=j, but that won't reduce the overall complexity.

confused with c++ program? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I have compiled the following program and i know what it does, it takes ten numbers multiplies it my itself and then at the end add their total together.
#include <iostream>
using namespace std;
main()
{
int a[10];//1
int sumOfSquares = 0 ;//2
int i =0; //3`enter code here`
cout << "Please enter the ten numbers one by one " << endl;//4
for (i = 0 ; i < 10 ; i++)//5 dont get what this does,
// obviously its a for loop,
// but why does it increment i by one
{
cin >> a [i];//6 this means store the 10 numbers
// in array a and refer to it by the variable i
}
for (i = 0 ; i < 10 ; i++) //7 again i dont get why this is here
{
sumOfSquares = sumOfSquares + a[i]*a[i];//8
}
cout << "The sum of squares is "<< sumOfSquares << endl; //9
}
why does it increment i by one
Array indexes run from 0 to N-1, where N is the number of elements in the array.
i++ increments the value of i by 1 (equivalent to i = i + 1;). Incrementing i in the for loop is a construct for accessing each element of the array a (in order):
for (int i = 0; i < 10; i++)
{
a[i] = 2; /* just example */
}
is equivalent to:
a[0] = 2;
a[1] = 2;
...
a[9] = 2;
As others have commented, get a C++ book (see this SO question for a list of C++ books).
#include <iostream>
using namespace std;
main()
{
//declare space in memory for 10 numbers to be stored sequentially
//this is like having ten variables, a1, a2, a3, a4 but rather than having
//hardcoded names, you can say a[4] or rather i=4, a[i], to get variable a4.
int a[10];
int sumOfSquares = 0 ; //space for a number to be stored called sumOfSquares
int i =0; //space for a number to be stored called i
cout << "Please enter the ten numbers one by one " << endl; //print msg to screen
for (i = 0 ; i < 10 ; i++) //make i = 0; while i < 10 run this code! increase i by 1 each time
{
//a stores 10 numbers. put the number the user entered in space
//a[0] the first time, a[1] the second time, a[2] the third time etc etc.
cin >> a [i];
}
//run this code 10 times, with i=0 the first time, i=1 the second time,
// i=3 the third time etc etc.
for (i = 0 ; i < 10 ; i++)
{
//get the number at a[0] multiple it by the number at a[0]
//add it to value already in sumOfSquares so this number goes up and up and up.
//the second time through the loop get a[1] and multiply it by a[1].
sumOfSquares = sumOfSquares + a[i]*a[i];
}
//print answer to screen
cout << "The sum of squares is "<< sumOfSquares << endl; //9
}