It seems like I always come here to ask silly questions, but here it goes. As of right now I am in my first compsci course and we are learning c++. I've had an extremely basic introduction to c before, so I had thought I'd go above and beyond my current assignment. Now I was doing this just to showboat, I felt like if I didn't practice my previous concepts they would eventually fade. Anyways, on to the problem! I was supposed to write some code that allowed the user to input their initials, and a series of exams. Now this was supposed to accomplish three things: average the exams, print out the entered exams, and print out their initials. Well, what was a simple assignment, got turned into a huge mess by yours truly.
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
string uInitials;
float avgExam = 0, tExam = 0;
int aExams[10] = {'0'};
int i, nExam = 0, cExam;
cout << "Enter your three initials!";
cin >> uInitials;
do
{
cout << "Enter your exam(s) to be averaged. Enter 0 when complete!\n";
cin >> cExam;
aExams[nExam] = cExam; //I used this before nExam was incremented, in order to get nExam while it was '0' That way the first exam score would be properly saved in the first space
nExam++;
tExam += cExam; //This is just to add all the exams up to later calculate the average
}
while(cExam != 0);
avgExam = tExam/(nExam - 1); //subtracted '1' from nExams to remove the sentinel value from calculations.
cout << "The average for initials: " << uInitials << " is: " << avgExam << endl;
cout << "This average was obtained using the following scores that were entered: \n";
for(i = 0; i < (nExam+1); i++)
{
cout << aExams[i] << endl; //Used a for loop to prevent redundancy
}
return 0;
}
The previous is my code, and the problem is that I'm getting output errors where it adds two '0's when I print out the list of entered exams. Also I feel like I made the whole do{}while() loop one huge clunky mess, so I'd like to refine that as well. If anyone could assist this poor, ignorant, beginner I would greatly appreciate it. Thank you for your time!
Some advice that i can give is for example in the 5th line there is no need
to put the 0 between ' ' and not even need to use the assign = operator.
You can initialize the array like this:
int aExams[10]{0};
Which will initialize all elements to 0,but can't be used for other value.
For example you won't have all the elements with value 1 if you write
int aExams[10]{1};
If your intention to initialize all elements in an array is with value other than 0 you can use fill_n(); function.
fill_n(aExams, 10, 1);
The first argument is the name of the array, the second is up-to which element you want to be initialized with the third argument, and the third is the value you want all elements to have.
Do not leave uninitialized variables like in line 6 with cExam and i variables. Initialize it like cExam=0; (copy-assign initialization) or cExam(0); (direct initialization). The latter calls the constructor for int built-in type.
A negative i see in your do-while loop is that you do not make sure that the user will enter under 10 exams,bad things will happen if the user tries to input 15 exams in an array that can hold only 10.
Just change the while to something more like this:
while( cExam != 0 && (nExam<10) );
You can also write the first two lines of the do-while loop outside the loop.
It is needed only once to tell the user that to stop the loop he/she needs to enter 0. There is no need to tell them this on every iteration plus that you will have a good performance benefit if you put those two lines outside the loop.
Look here how i would write the code and ask if you have any questions.
http://pastebin.com/3BFzrk5C
The problem where it prints out two 0's at the end of your code is a result of the way you wrote your for loop.
Instead of:
for(i = 0; i < (nExam+1); i++)
{
cout << aExams[i] << endl; //Used a for loop to prevent redundancy
}
Use:
for (i = 1; i < (nExam); i++)
{
cout << aExams[i - 1] << endl; //Used a for loop to prevent redundancy
}
Related
I picked up a challenge on r/dailyprogrammer on reddit which wants me to match a necklace and put the last letter at the beginning of a string. I've considered using nested for loops for this but this has made me really confused.
Instead I chose the way of replacing the last with the first character in an if-statement. But I am not getting my desired output with it, though I've tried everything what comes into my mind.
I used even std::swap() which didn't lead me to success either.
Here's the code:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string same_necklace(string& sInput, string& sOutput)
{
for (string::size_type i = 0; i < sInput.size(); i++)
{
if (sInput[i] == sInput.size())
{
sInput[0] = sInput[sInput.size()];
}
}
for (string::size_type j = 0; j < sOutput.size(); j++)
{
if (sOutput[j] == sOutput.size() - 1)
{
sOutput[0] = sOutput[sOutput.size()];
}
}
return sInput, sOutput;
}
int main()
{
system("color 2");
string sName{ "" };
string sExpectedOutput{ "" };
cout << "Enter a name: ";
cin >> sName;
cout << "Enter expected output: ";
cin >> sExpectedOutput;
cout << "Result: " << same_necklace(sName , sExpectedOutput) << endl;
return 0;
}
And of course the link to my challenge (don't worry, it's just Reddit!):
https://www.reddit.com/r/dailyprogrammer/comments/ffxabb/20200309_challenge_383_easy_necklace_matching/
While I am waiting (hopefully) for a nice response, I will keep on trying to solve my problem.
In your if you compare the value of the current index (inside the loop) with the size of the string. Those are two unrelated things.
Also, you use a loop though you only want to do something on a single, previously known index.
for (string::size_type i = 0; i < sInput.size(); i++)
{
if (sInput[i] == sInput.size())
{
sInput[0] = sInput[sInput.size()];
}
}
You could change the if condition like this to achieve your goal:
if (i == sInput.size()-1) /* size as the index is one too high to be legal */
But what is sufficient and more elegant is to drop the if and the loop. completely
/* no loop for (string::size_type i = 0; i < sInput.size(); i++)
{ */
/* no if (sInput[i] == sInput.size())
{*/
sInput[0] = sInput[sInput.size()-1]; /* fix the index*/
/* }
} */
I.e.
sInput[0] = sInput[sInput.size()-1]; /* fix the index*/
Same for he output, though you got the correct index already correct there.
This is not intended to solve the challenge which you linked externally,
if you want that you need to describe the challenge completely and directly here.
I.e. this only fixes your code, according to the desription you provide here in the body of your question,
"put the last letter at the beginning of a string".
It does not "switch" or swap first and last. If you want that please find the code you recently wrote (surely, during your quest for learning programming) which swaps the value of two variables. Adapt that code to the two indexes (first and last, 0 and size-1) and it will do the swapping.
So much for the loops and ifs, but there is more wrong in your code.
This
return sInput, sOutput;
does not do what you expect. Read up on the , operator, the comma-operator.
Its result is the second of the two expressions, while the first one is only valuated for side effects.
This means that this
cout << "Result: " << same_necklace(sName , sExpectedOutput) << endl;
will only output the modified sExpectedOutput.
If you want to output both, the modified input and the modified output, then you can simply
cout << "Result: " << sName << " " << sExpectedOutput << endl;
because both have been given as reference to the function and hence both contain the changes the function made.
This also might not answer the challenge, but it explains your misunderstandings and you will be able to adapt to the challenge now.
You have not understand the problem i guess.
Here you need to compare two strings that can be made from neckless characters.
Lets say you have neckless four latters word is nose.
Combination is possible
1)nose
2)osen
3)seno
4)enos
your function (same_necklace) should be able to tell that these strings are belongs to same necklace
if you give any two strings as inputs to your function same_necklace
your function should return true.
if you give one input string from above group and second input string from other random word thats not belongs to above group, your function should return false.
In that sense, you just take your first string as neckless string and compare other string with all possible combination of first string.
just move move you first latter of first input string to end and then compare each resulting string to second input string.
below is the function which you can use
void swap_character(string &test)
{
int length = test.length();
test.insert(length, 1, test[0]);
test.erase(0, 1);
}
I'm just practicing using arrays. So my program consist of inputting numbers of data type double into the array and have them print out. Simple.
I only limited the numbers down to 4. So the array, num_List[3] is in the code. I've made sure to use the for loops properly for reading and printing out the result.
The first few times I tested the code. I realized that the 4th number in the array was in scientific notation, telling me that I forgot to initialize the array to 0, in this case 0.0, since I'm using double. So I put in this code.
for (index = 0; index <= 3; index++)
num_List[index] = 0.0;
This code should have initialized the arrays of num_List to 0.0. However, when I tested this, nothing came up, after I inputted the 4 numbers. So I made a logical error here or it's something else with the for loop that's causing it to be trapped and not continue the execution.
I've read in the books about this particular way to initialize.
#include <iostream>
using namespace std;
int main() {
double num_List[3]; // These are my variables
int index;
//double num; // Ignore these two for now, for they are to be modified later on.
//double result;
cout << "This program will summarize the numbers you've inputted print out the result. \n";
cout << "And also print out the address of the 1st and 4th address in the array." << endl;
cout << "Please enter the four numbers to be summarized.";
for (index = 0; index <= 3; index++) { // I put this in after I realized my mistake of not initializing my arrays to 0.0.
num_List[index] = 0.0;} // This is where the problem is, I think.
for (index = 0; index <= 3; index++) // This reads in the user the input
cin >> num_List[index];
cout << "The numbers you have inputted is:\n";
for (index = 0; index <= 3; index++) // This prints out the array.
cout << num_List[index] << ", " << endl;
return 0;
}
If you focus on the aforementioned code, and try to compile it, you'll see that my code unfortunately doesn't continue on from there after you input 4 numbers, regardless of whether or type a number and space it up to 4 numbers, or input a number, press the enter key for those numbers. Most likely I've made a obvious mistake, but I'm having some trouble seeing it.
I use Code Blocks, so things are a little different compared to the Bloodshed C++ compiler I used to use to practice codes on.
double num_List[3];
This declares an array with 3 elements, indexed 0 through 2.
for (index = 0; index <= 3; index++)
This loops through 4 indices, 0 through 3. When you do something with num_List[3], you get undefined behavior. In your trial, the undefined behavior fortunately resulted in just some garbage output.
i am trying to make a program to check and list the genders of a number of student, m being fem and l being male.
I'm not sure what's wrong with my code but when i print out the m and l variable they have either really huge.
Have been trying to solve this for hours, your help is greatly appreciated, cheers.
P.S sorry for my bad english.
#include<iostream>
#include<string>
using namespace std;
main()
{
char gender[20];
int jlh,i,j,m,l;
cin>>jlh;
system("cls");
for(i=0;i<jlh;i++)
{ cout<<"Data "<<i+1<<endl;
cout<<"Enter your gender - "<<endl;
cin>>gender[i];
}
m,l=0;
for(i=0;i<jlh;i++){
if(gender[i]=='p'){
m=m+1;
}
else if(gender[i]=='l'){
l=l+1;
}
}
cout<<endl<<l<<endl;
cout<<m;
}
The line
m,l=0;
does not work as you expect. Look up the comma operator, it evaluates the first operand (just m in this case), discards the result, and evaluates and returns the second operand. So only l is set to zero. I would recommend moving the declaration to this line and initializing the variables in one go, like so
int m=0, l=0;
for (int i=0; i<jlh; i++)
...
I would also move the declaration of variables like i to where they are needed, as shown above; there is no need to put all declaration at the beginning of the function.
Then the output
cout<<endl<<l<<endl;
cout<<m;
places the endl before and after the first variable, but not after the second. You should have an endl after the last line of your output, otherwise your console prompt is right after your value. It would improve readability to have something like this:
std::cout << "Number of females: " << m << std::endl;
std::cout << "Number of males: " << l << std::endl;
You should also make sure that not more than 20 values are entered, as your array has this size. But there is not even a need for this (maybe there is in your real code, but not in the MCVE): You can just increment the variables when reading the input, no need to store it in the array. This gets rid off this arbitrary limit. If you really need the values, you should use a std::vector instead of a fixed size array.
I'm working on a project where I need to have the computer print the 12 days of Christmas lyrics. I thought of an idea where I make a FOR loop and have it repeat 12 times. Every time the day changes with the unary operator "++" Here's what I mean:
int main()
{
string Print = first = 1; //Here I want first to become a number so that I can call it up in FOR loop.
cout << "On the first day of Christmas, \nmy true love sent to me\nA partridge in a pear tree.\n" << endl;
for(int loop = 0; loop <= 12; loop++)//This part is a simple for loop, it starts at 0 and goes to 12 until it stops.
{
cout << "On the " << (1,2,3,4,5,6,7,8,9...12) << " day of Christmas,\nmy true love sent to me\n" << endl; HERE!!!!
Here is where I'm having issue. I want the numbers to call in strings to say the day. As in x = 1 will call in "First" and then I can move the number up by using "x++" which will result in x = 2 and then it will say "Second".. all the way to 12. Anyone know how I can resolve this issue?
}
This involves a simple but important part of programming called an array. I don't want to give you the answer directly - you need to use these (or similar structures) all the time, and it is very important to practice their use and understand them. Let's make a simple program using arrays that prints "Hello World":
#include <iostream>
#include <string>
int main() {
std::string words[2]; //make an array to hold our words
words[0] = "Hello"; //set the first word (at index 0)
words[1] = "World"; //set the second word (at index 1)
int numWords = 2; //make sure we know the number of words!
//print each word on a new line using a loop
for(int i = 0; i < numWords; ++i)
{
std::cout << words[i] << '\n';
}
return 0;
}
You should be able to figure out how to use a similar tactic to get the functionality you asked for above. Working Ideone here.
I'm not sure how to title my question, but here goes. I am testing some features, and I have hit a snag.
What I want to know is how can I set up a "for" or "if" statement to only put values in an array that meet a criteria? For example, find every divisor for a number, but only put factors in an array.
Any help would be loved, source code can be provided if needed :). Yes, I am new, so be gentle!
#include <iostream>
using namespace std;
int main(){
int n;
int counter = 1;
cout << "What number would you like to use? ";
cin >> n;
int DiviArray[n];
for (int k=0,j=1;k<n;k++,j++)
{
DiviArray[k] = n-k;
}
int k = 3;
int factn[n];
cout << "Factors of " << n << ": " << endl;
for (int i=0, j=1;i<n;i++,j++)
{
factn[i] = n/DiviArray[i];
if(factn[i]*DiviArray[i]==n)
{
cout << counter << ". " << factn[i] << " x " << DiviArray[i] << endl;
counter++;
}
}
return 0;
}
EDIT: Decided to go with vectors, not sure if I can get it to work, but thanks for the feedback guys :)
Since you don't know in advance how many values will meet the condition, you should use a std::vector.
As a benefit, it keeps track of how many elements you've already added, so push_back will always use the next available index.
This also fixes
cin >> n;
int DiviArray[n];
which isn't legal C++.
If you only want to put the values into the array that match the condition, then you should only put a number into the array when the condition is matched. To do that, the statement that puts a number into the array has to be inside the if-block for the condition. I hope I don't need to explain why :)
This is the only time in your program where you actually do want two indices: one that is incremented every time through the loop (to count how many times to run the process), and one that is incremented only when you put a number in the array (to figure out where the next number goes). Everywhere else, you've created a completely useless j variable (the uselessness should be apparent from the fact that there is no code that actually uses the value, only code to set it).