As a student, how can I improve poor code? [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
How do I improve this spaghetti code? I am a student and this is me being slow in my first programming course.
What I think I want to achieve
Find an alternating sum up to a number.
Problem overview
https://www.hackerrank.com/contests/cs102-s18-march31/challenges/treasure-road
This is a problem from the archive at provided by the teacher. I have deduced that an alternating sum has to be calculated, where the sum of the first odd integers has to be subtracted from the sum of the first even integers (of course up to #ofsteps/2).
What I did
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int arrodds[100]={0},arrevens[100]={0},sumevens=0,sumodds=0;
int steps;
cin >> steps;
int i=0;
while(i<steps/2)
{
if(i%2==0)
arrevens[i]=i;
else arrodds[i]=i;
i++;
}
for(int d=0;d<100;d++)
sumevens+=arrevens[d];
for(int h=0;h<100;h++)
sumodds+=arrodds[h];
cout << sumodds-sumevens;
return 0;
}
My logic/reasoning
Zingo can only move Steps/2, if he moves an odd step he moves forward, and Ringo moves a step closer to to Zingo, else if Zingo moves an even step Ringo moves away from Zingo.
Let's say there are 10 steps... 10/5=5... 5 steps= 1+2+3+4+5, odd steps=1,3,5; even steps=2,4; so displacement is 1+3-(2+4)=-2.
The code
I try to store the even and odd numbers in different arrays, then take the sum of each one and subtract the sums.
What's wrong?
My code works for small numbers it seems, as some test cases go beyond what I think My code could handle.
What I tried
I tried playing around with the sizes of my arrays but didn't get what I want.
Should I abandon this code and try something else? If not, how can I fix this abomination and guide me through it?

You can use a running sum instead of using arrays:
sum_evens = 0;
sum_odds = 0;
for (int i = 0; i < steps; ++i)
{
if (i & 1)
{
sum_odds += i;
}
else
{
sum_evens += i;
}
}
Edit 1:
The sum of the first N odd numbers is N*N.
You could change the calculation to:
sum_odds = steps * steps;
I'll leave the calculation of the first N even numbers up to the reader / OP.

Related

How to handle this odd and even bubble sorting error? [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 last month.
Improve this question
I wanna ask why the even side of the odd&even bubble sort will raise a zsh:abort error in VScode? Is it because it is out of range? If so, does that mean that I have to precisely modify the range? Thank you!
#include <iostream>
using namespace std;
int main()
{
int a[10];
for (int i=0;i<10;i++)
{
cin>>a[i];
}
//First, sort odd and even numbers
int l=0,r=9;//point to the two ends of the array
while (l<=r)
{
bool leftIsOdd=a[l]%2==1;
bool rightIsEven=a[r]%2==0;
//move the two pointers from ends to middle
if (leftIsOdd)
{
l++;
}
else if (rightIsEven)
{
r--;
}
//since it's a symmetric array, with 5 odd and 5 even, we can swap when both sides get stuck
//Q:If we have 4 odd numbers and 6 even numbers, is the approach OK?
else if (!leftIsOdd && !rightIsEven)
{
int temp=a[l];
a[l]=a[r];
a[r]=temp;
}
}
//perform bubble sort for left odd part
int start=0,end=l;
for (int i=start; i<end-1;i++)
{
for (int j=start+1;j<end-i;j++)
{
if (a[j-1]>a[j])
{
int temp=a[j];
a[j]=a[j-1];
a[j-1]=temp;
}
}
}
//now bubble the right even side
start=l,end=10;
for (int i=start; i<end-1;i++)
{
for (int j=start+1;j<start+end-i;j++)
# # # //Why j<start+end-1 would produce error?
{
if (a[j-1]>a[j])
{
int temp=a[j];
a[j]=a[j-1];
a[j-1]=temp;
}
}
}
for (int i=0;i<10;i++)
{
cout<<a[i]<<' ';
}
return 0;
}
I tried putting index j out of the expected range, and received zsh:abort error.
If you initialize the input array a with 10,9,8,7,6,5,4,3,2,1 as you mentioned then when you reach the "// now bubble the right even side" loop you will initialize start to 5 and end to 10. If you write j<start+end-1 then this will allow j to be as large as 13. (i.e. j must be less than 14). You will then try to access a[13], but a has only 10 elements. Therefore, if you are lucky, you will get some kind of memory access error when you run the program and it will crash.
I don't know why you want to replace the expression j<start+end-i (which seems to work, with the expression j<start+end-1 which causes a crash.
You could probably make the crash happen a lot easier just by including the line a[13]=0; after you declare and initialize a.
When you are using arrays it is your responsibility to ensure that all array accesses are valid. When you ask "does that mean that I have to precisely modify the range" the answer is "yes, definitely!"

Not Displaying Spaces [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 months ago.
Improve this question
I'm very new to c++ and everything in general. I dont understand why my code doesn't work:
#include <cstdio>
int main(){
int a;
scanf("%d", &a);
for(int i = 1; i < a; i++){
printf(" ");
}
printf("*");
}
what I'm trying to do is make the number of spaces as the value inputted by the user minus and add a * at the end so if a = 10 :
*
but when I try it the spaces don't show.
Ideally what I'm trying to do is get an output something like:
*
**
***
****
The length depends on user input if it was 10 then the spaces would be 9 and the * at the end would be the tenth.
You will have to use 3 for-loops (two of them nested inside one). The parent for loop for each row. And the nested two are for spaces and stars.
#include <cstdio>
int main()
{
int a;
scanf("%d", &a);
for(int i=1; i<a; i++)
{
for(int j=i; j<a; j++)
printf(" ");
for(int k=0; k<i; k++)
printf("*");
printf("\n");
}
return 0;
}
You will get your desired output if you put the value 5 for a, i.e., a=5.
To learn more in detail, you can follow this link star patterns in c
Your code may contain many errors. That's understandable, cause you are new to C/C++. Try problem-solving in beecrowd to improve your problem-solving capabilities and learn C/C++ in a better way. These errors will automatically go away day by day as you progress. But the secret is to practice and never give up. Good luck!

How to calculate the average score in struct function of C++? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
This is the question that I was aasigned.
https://i.stack.imgur.com/efRFk.png
And this is my coding. This is my first time asking question here so I dont really know how to paste my coding here.
https://i.stack.imgur.com/QCOBG.png
I really hope someone can help me out. Thank you.
You have to initialize the variable sum
When you run the code, sum is created in the memory.
but it has no value if you don't initialize with value such as 0, 1, 2 ... anything you want.
then, sum will take any value which exists in the assigned memory.
that's why the sum of sum has a junk value.
Thus, you have to initialize sum as below.
double sum =0.0;
You can use the below shown program as a starting point(reference). In your program you were creating an ordinary(nonmember) double named average while according to the assignment average should be a data member as shown below. Second, there is no need to create a separate variable called sum because you can use variable average to sum all the test scores and then divide average by 3 which is also shown below.
#include <iostream>
struct Result
{
public:
//this takes input from user
void takeTestInput()
{
for(int i = 0; i < sizeof(test)/sizeof(int); ++i)
{
std::cout<<"Input#"<<i+1<<": ";
std::cin >> test[i];//take the input and put into test[i]
}
}
void calculateAverage()
{
for(int i = 0; i < sizeof(test)/sizeof(int); ++i)
{
average+=test[i];
}
average = average/3;
}
void printAverage()
{
std::cout<<average;
}
private:
int test[3];
double average; //data member called average
};
int main()
{
Result student1;
//take input for student1
student1.takeTestInput();
//calculate average for student1
student1.calculateAverage();
//check if the average calculated above is correct by printing out the average for student1
student1.printAverage();
return 0;
}
The output of the above program can be seen here.

intersection code that prints the intersection of two arrays ( posting lists ) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I wrote this code to print the intersection of two arrays ( posting lists) using dev c++
the problem that when I run the program nothing is printed
can you help ?
I need to know where is the problem
and what if I wanted to use cout instead of printf?
#include <iostream>
#include <stdio.h>
using namespace std;
// Intersecting two postings lists (a “merge” algorithm)
// and I will assume that the two posting listst are sorted Ascendingly
// I will suppose that the first posting list is an array wich
// have n elements I wil name it fistPost
// I will suppose that the second posting list is an array wich have
// m elements I will name it secondPost
int main()
{
int firstPost[] ={3,5,7,8,13,15,30,34};
int secondPost[]={1,5,7,9,11,15,20,34,35};
int i,j=0;
int n = sizeof(firstPost)/sizeof(firstPost[0]);
int m = sizeof(secondPost)/sizeof(secondPost[0]);
while(i<n && j<m)
{
if (firstPost[i]<secondPost[j])
i++;
else if (firstPost[i]>secondPost[j])
j++;
else if (firstPost[i]=secondPost[j])
{
printf ("%i", secondPost[j++]);
i++;
}
}
system("PAUSE");
return 0;
}
You haven't initialized 'i' to 0, hence its taking some garbage value and not executing the while loop.
change int i, j = 0;
to int i = 0, j = 0;
change this printf ("%i", secondPost[j++]);
to
printf ("%d", secondPost[j++]);

C++ total beginner needs guidance [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
yesterday,we had to solve problems at the codeforces contest
I couldn't solve this problem since I am a total beginner.
http://codeforces.com/contest/353/problem/A
I used this algorithm, but something is wrong with it. I think it should print s or f, however it prints nothing. it just auto closes. Even when I added an input to stop instant close
#include <cstdlib>
#include <iostream>
using namespace std;
int main(){
int y=0;
int x=0;
int f;
int a;
cin >> a;
int s;
s = 0;
int number [a][a];
for(int i = 0;i<a;i++){
cin >> number[i][0] >> number[i][1];
x += number[i][0];
y += number[i][1];
}
for(int i = 0;i<a;i++){
if(x%2==0 && y%2==0){
return s;
}else if(y%2!=0 && x%2==0){
f = -1;
return f;
}else if(y%2==0 && x%2!=0){
f = -1;
return f;
}else{
y+= number[i][0];
x+= number[i][1];
s++;
}
}
int g;
if(f!=-1){
cout << s;
}else{
cout << f;
}
}
As Angew said, the return statements are incorrect and causing you to exit your main. You want to replace this by a break; to exit the loop but not the function.
I have not spent effort in trying to understand your algorithm, but at first glance it looks more complicated than it should be.
From my understanding of the problem, there are 3 possibilities:
the totals of the upper halves and the lower halves are already even (so nothing needs to be done)
the totals of the upper halves and the lower halves cannot be made even (so no solution exists)
just one Domino needs to be rotated to get the totals of the upper halves and the lower halves to be even (so the time needed is 1 second)
I base this on the fact that adding only even numbers always gives an even result, and adding an even number of odd numbers also always gives an even result.
Based on this, instead of having a 2-dimensional array like in your code, I would maintain 2 distinct arrays - one for the upper half numbers and the other for the lower half numbers. In addition, I would write the following two helper functions:
oddNumCount - takes an array as input; simply returns the number of odd numbers in the array.
oddAndEvenTileExists - takes 2 arrays as input; returns the index of the first tile with an odd+even number combination, -1 if no such tile exists.
Then the meat of my algorithm would be:
if (((oddNumCount(upper_half_array) % 2) == 0) && ((oddNumCount(lower_half_array) % 2) == 0))
{
// nothing needs to be done
result = 0;
}
else if (((oddNumCount(upper_half_array) - oddNumCount(lower_half_array)) % 2) == 0)
{
// The difference between the number of odd numbers in the two halves is even, which means a solution may exist.
// A solution really exists only if there exists a tile in which one number is even and the other is odd.
result = (oddAndEvenTileExists(upper_half_array, lower_half_array) >= 0) ? 1 : -1;
}
else
{
// no solution exists.
result = -1;
}
If you wanted to point out exactly which tile needs to be rotated, then you can save the index that "oddAndEvenTileExists" function returns.
You can write the actual code yourself to test if this works. Even if it doesn't, you would have written some code that hopefully takes you a little above "total beginner".