1) Write a program that asks the user to enter the number of pancakes eaten for breakfast by 10 different people (Person 1, Person 2, ..., Person 10).
Once the data has been entered, the program must analyze the data and output which person ate the most pancakes for breakfast.
My solution uses an array, but the program only displays the person who ate the most sentence if I put a break in the end of the if statement. Without the break the program just asks how much each person ate then exits. I'm just trying to understand exactly why the break needs to be there, or if there is a way to do it without the break.
Here is my code:
//Pancakes!
#include <iostream>
#include <limits>
using namespace std;
int main()
{
//Build array of people and set a value for most eaten
int people[9] = {};
int most = -1;
for (int n=1; n<=10; n++)
{
//Sets the number of pancakes eaten to a person value in the array
cout << "How many pancakes did person " << n << " eat? ";
cin >> people[n-1];
//Checks if the value entered above is the highest value
if(people[n-1] > most)
{
most = people[n-1];
}
}
//Line entered for formatting
cout << endl;
//Lists the person and how many pancakes they ate
for (int x=0; x<10; x++)
{
if(people[x] == most)
{
cout << "Person " << (x+1) << " ate " << most << " pancake(s), the most!" << endl;
break;
}
}
//Pause after program
cout << endl;
std::cout << "Press ENTER to continue...";
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
return 0;
}
Also feel free to review my code and give me tips for making it more concise because im still a newbie =] thanks.
For the above question, I would solve it this way to preview the person who ate the most pancakes:
Code:
// assuming the first one is the highest one
most = 0;
//now checking for the higest one
for (int x = 0; x < 10; x++) {
if (people[x] > =people[most]) {
most = x;
}
}
cout << people[most]; //this shows the highest pancakes.
This doesn't use break at all and gives the required output.
Related
I am trying to solve a execise, which amis to find the Last Digit of a Large Fibonacci Number, and I try to search for others' solution, and I find one here: https://www.geeksforgeeks.org/program-find-last-digit-nth-fibonnaci-number/, then I copy and paste the method 2, and I just changed the ll f[60] = {0}; to ll f[60]; but this doesn't work properly on CLion, my test code
int n; std:cin>>n;
`
for (int i = 0; i < n; i++) {
std::cout << findLastDigit(i) << '\n';
}
return 0;
}` the error: SIGSEGV (Segmentation fault). Could someone give me a hint or reference or something?
Correct me if I'm totally off base here, but if I'm looking at this correctly, you don't need to actually calculate anything ::
the last digit of Fibonacci sequence numbers appears to have a predictable pattern that repeats every 60th time, as such (starting with F.0 ) :
011235831459437077415617853819099875279651673033695493257291
011235831459437077415617853819099875279651673033695493257291
011235831459437077415617853819099875279651673033695493257291
011235831459437077415617853819099875279651673033695493257291
011235831459437077415617853819099875279651673033695493257291 ….etc
So all you have to do is quickly compute the list from F.0 to F.59, then take whatever insanely large input , modulo-% 60, and simply look up this reference array.
———————————————
UPDATE 1 : upon further research, it seems there's more of a pattern to it :
last 1 : every 60
last 2 : every 300 ( 5x)
last 3 : every 1,500 ( 5x)
last 4 % 5,000 : every 7,500 ( 5x)
last 4 : every 15,000 (10x)
last 5 % 50,000 : every 75,000 ( 5x)
last 5 : every 150,000 (10x)
For a large number, you probably want to utilize a cache. Could you do something like this?
// Recursive solution
int fib(int n, int cache[]) {
if (n == 0) {
return 0;
}
if (n == 1) {
return 1;
}
if (cache[n]!= 0) {
return cache[n];
}
cache[n] = fib(n - 1, cache) + fib(n - 2, cache);
return cache[n];
}
// Iterative solution
int fib(int n) {
int cache[n + 1];
cache[0] = 0;
cache[1] = 1;
for (int i = 2; i <= n; i++) {
cache[i] = cache[i - 1] + cache[i - 2];
}
return cache[n];
}
(Re-write)
Segfaults are caused when trying to read or write an illegal memory location.
Running the original code already produces an access violation on my machine.
I modified the original code at two locations. I replaced #include<bits/stdc++.h> with #include <iostream> and added one line of debug output:
// Optimized Program to find last
// digit of nth Fibonacci number
#include<iostream>
using namespace std;
typedef long long int ll;
// Finds nth fibonacci number
ll fib(ll f[], ll n)
{
// 0th and 1st number of
// the series are 0 and 1
f[0] = 0;
f[1] = 1;
// Add the previous 2 numbers
// in the series and store
// last digit of result
for (ll i = 2; i <= n; i++)
f[i] = (f[i - 1] + f[i - 2]) % 10;
cout << "n (valid range 0, ... ,59): " << n << endl;
return f[n];
}
// Returns last digit of n'th Fibonacci Number
int findLastDigit(int n)
{
ll f[60] = {0};
// Precomputing units digit of
// first 60 Fibonacci numbers
fib(f, 60);
return f[n % 60];
}
// Driver code
int main ()
{
ll n = 1;
cout << findLastDigit(n) << endl;
n = 61;
cout << findLastDigit(n) << endl;
n = 7;
cout << findLastDigit(n) << endl;
n = 67;
cout << findLastDigit(n) << endl;
return 0;
}
Compiling and running it on my machine:
$ g++ fib_original.cpp
$ ./a.out
n (valid range 0, ... ,59): 60
zsh: abort ./a.out
ll f[60] has indices ranging from 0 to 59 and index 60 is out of range.
Compiling and running the same code on https://www.onlinegdb.com/
n (valid range 0, ... ,59): 60
1
n (valid range 0, ... ,59): 60
1
n (valid range 0, ... ,59): 60
3
n (valid range 0, ... ,59): 60
3
Although it is an out-of-range access that environment handles it just fine.
In order to find the reason why it is running with array initialization and crashing without on your machine needs some debugging on your machine.
My suspicion is that when the array gets initialized the memory layout changes allowing to use the one additional entry.
Please note that access outside of the array bounds is undefined behavior as explained in Accessing an array out of bounds gives no error, why?.
Question
How can I give spaces between numbers? When I add a <<" " after cout<<j the pattern changed. Is there any other way to give spaces between numbers?
code
#include<iostream>
using namespace std;
int main(){
int i,j=1,space,star,n;
cin>>n;
i=1;
Looping
while(i<=n){
space=n-i;
while(space){
cout<<" ";
space--;
}
star=i;
while(star){
cout<<j<<" ";
j++;
star--;
}
cout<<"\n";
i++;
}
return 0;
}
output
for n=4
1
23
456
78910
I want this output :-
1
2 3
3 4 5
7 8 9 10
For the expected output you only need to add a second space in the while(space) loop:
space = n - i;
while (space) {
std::cout << " "; // note: two spaces
space--;
}
or multiply space by 2 before the loop:
space = 2 * (n - i);
while (space) {
std::cout << ' ';
space--;
}
You could also #include <string> and skip the loop:
space = 2 * (n - i);
std::cout << std::string(space, ' ');
Another way of skipping the loop is to #include <iomanip> and use std::setw.
Note that you can use std::setw and std::left to correct the while (star) loop too to make this pattern hold for up to n = 13.
space = 2 * (n - i) + 1;
std::cout << std::setw(space) << "";
while (star) {
std::cout << std::setw(2) << std::left << j;
j++;
star--;
}
Demo
I'm doing an exercise and I stuck with my code. I hope you guys can help me fix it.
And here is my function fen():
double fen(double x,double y, int n) { // You should complete this function
// Write your statements here
double sum=1,temp;
int j=2,k=1;
double a = (x*y*y) / 18;
sum=1-a;
for(int i=2;i<=n;i++)
{
for(;j<=i;j++)
{
a *= (x*y);
for(;k<=(i+j);k++)
a /= k;
}
temp = a/(k*k);
temp = (i%2 == 0) ? temp : -temp;
sum+=temp;
}
return sum; //This statement must be changed
}
I've checked many times but still don't know why its result's wrong.
I've debugged and when i=3, a actually equal to 0.025 but it displayed0.02499999999.
I wrote a small code to simplify things and here it is:
#include <iostream>
using namespace std;
double fen(double x,double y, int n) {
double tmp = y;
double sum = 1;
for (int i = 1; i < n; i++) {
tmp *= -((x * y * (2*i-1)) / ((2*i) * (2*i+1) * (2*i+1)));
sum += tmp;
}
return sum;
}
int main(void) {
cout << fen(2,3,1) << endl;
cout << fen(2,3,2) << endl;
cout << fen(2,3,3) << endl;
cout << fen(2,3,4) << endl;
cout << fen(2,3,1000) << endl;
return 0;
}
I only checked it till fen(2,3,4) and results were correct till there. it shows 0.162772 for fen(2,3,1000):
1
0
0.18
0.161633
0.162772
UPDATE:
Updated code to use cout for output rather than printf. But I don't think this code really differs between C or C++.
In addition, remember that you reach quickly to limit of numerical precision of double in this code.
OP's formula mis-calculates the terms.
// int j=2,k=1;
int j=2,k=3; // The loop's later calculation expect this to be initially 3
// in the loop
// add
a *= k; // undo the prior terms /k
for(;j<=i;j++) {
// this part OK
}
// temp = a/(k*k);
temp = a/k*; // Only need /k
Other simplifications possible.
/* There are 100 students and 100 lockers. Student 1 opens all, student 2 closes every second one, student 3 changes every third
locker(closes if open, opens if close), Student 4 changes every forth locker and so on for all 100 students.
Which locker will be left open? */
Here is my code thus far:
#include <stdio.h>
int main(void)
{
int locker[100], i, closed = 0, opened = 0;
for(i=0; i<100; i++) locker[i] = 1;//0 means closed locker, 1 means open locker
for(i=1; i<101; i++) if(i % 2 == 0) locker[i-1] = 0; // every second locker is closed by second student...(2,4,6,7)
for(i=3; i<101; i++){ // i means student no. i
if(locker[i-1] == 0) locker[i-1] = 1;
if(locker[i-1] == 1) locker[i-1] = 0;
if I substitute "if(locker[i-1] == 1)" with "else" why the program doesn't work? Correct result is opened 1 closed 99. If I use 'else' result becomes opened 50 and closed 50
}
for(i=0; i<100; i++){
if(locker[i] == 0) closed = closed + 1;
else opened = opened + 1;
}
printf("opened locker %d\nclosed locker %d", opened, closed);
return 0;
}
This is my first post in stack overflow. Correct me if I've done anything wrong.
I'll give you a few hints to help you out.
The answer is that 10 lockers remain open, 90 are closed.
For this particular problem, it's easier to write the code if you avoid zero-based indexing. So
declare the array as int locker[101]; and then use indexes 1 thru
100 to represent the 100 lockers.
The Nth student is supposed to change every Nth locker. So you need
two nested for loops. The outer loop keeps track of n, and the
inner loop flips lockers.
The inner loop that only affects every Nth locker should look like
this
for ( i = n; i <= 100; i += n ) // every Nth locker
locker[i] = 1 - locker[i]; // flip the locker
Note that instead of the normal i=0 and i++, we have i=n
and i+=n. So, for example, if n is 3, then the values of i
are 3,6,9,...
Though I have not checked entire code and the logic of your question is not very clear to me, these lines seem to be problematic in your code:
if(locker[i-1] == 0) locker[i-1] = 1;
if(locker[i-1] == 1) locker[i-1] = 0;
What you're doing here is if a value is 0, then you are setting it to 1, then you are checking again, if it is 1, you are setting it to 0. So, so in this case all values will be set to 0 after running through both these statements.
Instead you should be doing
if(locker[i-1] == 0) locker[i-1] = 1;
else locker[i-1] = 0;
Note that your loop is wrong because you are looping over every locker for the third student and not looping over the remainder. You should for each student (n) change every nth locker to the reverse.
Also when you have the two ifs in a row. If the first if opens a locker, the second if sees it open and closes it (which is wrong). The else is required to actually change it.
Another point is that you can use exclusive or instead of the if locker[i] ^= 1
#include <stdio.h>
int main(void)
{
int locker[100], i, k, closed = 0, opened = 0;
for(i=0; i<100; i++) {
if (i%2 == 0) locker[i] = 1; // odd lockers (base 1) stay open
else locker[i] = 0; // even lockers (base 1) are closed
//0 means closed locker, 1 means open locker
for(i=3; i<101; i++){ // i means student no. i
for (k=i; k<101); k+=i) { // change every ith locker
// if (locker[k-1] == 0) locker[k-1]=1
// else locker[i-1] = 0;
// use exclusive or instead of if
locker[i-1] ^= 1;
}
}
}
// Now check the number open or closed
for(i=0; i<100; i++){
if(locker[i] == 0) closed = closed + 1;
else opened = opened + 1;
}
printf("opened locker %d\nclosed locker %d", opened, closed);
return 0;
}
solution without using an array.
#include <iostream>
using namespace std;
int main()
{
int studentTotal , lockerTotal, visit, totalOpened = 0, totalClosed = 0;
cout << "Enter number of students" << endl;
cin >> studentTotal;
lockerTotal = studentTotal;
for (int locker = 1; locker <= lockerTotal; locker++ ){ // locker loop
cout << "\n\n\nLocker no." << locker << endl;
cout << " is visited by student(s) ";
visit = 0;
for (int student = 1 ; student <= studentTotal; student++) { // student loop
if( locker % student == 0) {
cout << student << ", ";
visit++;}
}//end of locker loop
cout << "\nTotal number of visits: " << visit;
if (visit % 2 == 0){
cout << " the locker will stay closed.";
totalClosed++;}
else { cout << " the locker will be opened.";
totalOpened++;}
} //end of student loop
if (lockerTotal == totalOpened + totalClosed) {
cout << "\n\n\nOf total lockers (" << lockerTotal << "), " << totalOpened << " will be left open." << "(" << totalClosed << ") " << "will be closed." << endl;
}else cout << "Error!!";
return 0;
}
LOCKERS is the new FIZZBUZZ.
Here's a version which uses Booleans.
/* locker problem.c
*/
#include <stdio.h>
#include <stdbool.h>
int main (void)
{
bool locker[101]; // locker open = true, closed = false
// student 1 opens all lockers
for (int i = 1; i <= 100; ++i) {
locker[i] = true;
}
// subsequent students toggle (flip) subsequent lockers
for (int i = 2; i <= 100; ++i) {
for (int j = i; j <= 100; j += i) {
locker[j] = ! locker[j];
}
}
// display results
printf("\nopen lockers:");
for (int i = 1; i <= 100; ++i) {
if (locker[i]) {
printf(" %d", i);
}
}
putchar('\n');
return 0;
}
At the conclusion of the process the open lockers are the ones with a number which is a perfect square -- a perfect square has an odd number of divisors.
I want to get the loop bounds by using LLVM API. Here is the part of the code as follows. I don't know whether it is right to get the bounds. So, is there any other situation that I haven't thought about?
typedef std::vector<Loop*> LoopNest;
typedef std::vector<const Value*> LoopNestBounds;
...
void getLoopNestBounds(const LoopNest &Nest, LoopNestBounds &LBounds) {
ScalarEvolution &SE = getAnalysis<ScalarEvolution>();
for (unsigned d = 0, n = Nestsize(); d != n; ++d) {
if (SE.hasLoopInvariantBackedgeTakenCount(Nest[d])) {
const SCEV *C = SE.getBackedgeTakenCount(Nest[d]);
const SCEVConstant *CC = dyn_cast<const SCEVConstant>(C);
LBounds.push_back(CC->getValue());
errs() << CC->getValue()->getValue() << " iterations\n";
}
else {
LBounds.push_back(0);
errs() << "---- 0 iterations for the nest ----" << "\n";
}
}
}
Note: the version of LLVM is 3.0.