array getting more than it should - c++

char name[4][20];
int count=0;
cout<<"Enter 4 name at most , one name per line:\n";
while(cin.getline(name[count++],20))
;
--count;
(rest of code is for printing if u need to see that too it's at the end)
when i Enter names more than 4 it still prints those names but how can that happen?
because the first dimension is 4 so how can it get more than four
printing part of code:
for(int i=0; i<count; i++)
{
cout<<i<<"="<<name[i]<<endl;
}
system("pause");
}

If I get it correctly, your are asking "why if the array is 4 I can fit 5?".
Unlike Pascal, where arrays boundaries are checked at runtime, C++ doens't do such thing.
Think about it. An array is just some pointer that is added the offset later.
Let's say that you've an array of 5 integers and you do this
int a[5];
a[3] = 3;
a[6] = 4;
Nothing is really wrong, because in the first assignment, the statement equals to a+12 and the second one a+24. You're just incrementing the pointer and unless you don't bother the OS, you could go on and potentially overwrite some other data.
So C++ will very unlikely say something if you cross the arrays boundaries.
This implies that you must always somehow know how big is the array, in your case by simply adding to the loop:
while(count < 4 && cin.getline(name[count++], 20));

You need to tell the while() loop when to stop.
Try this:
char name[4][20];
int count=0;
cout<<"Enter 4 name at most , one name per line:\n";
while(count < 4 && cin.getline(name[count++],20))
;

Related

Error with big number of characters while making a letter pyramid

The task is to make a letter pyramid. I have done it but its behaviour goes very strange after I pass a certain number of characters that were inputed. Looking forward to an answer.
string input{};
string reverseString{};
getline(cin,input);
for(int j = input.length()-1;j>=0;j--){
reverseString += input.at(j);
}
for(int i = 0;i<input.length();i++){
int numberOfSpaces {};
numberOfSpaces = input.length()-i;
string spaces(" ",numberOfSpaces);
cout<< spaces << input.substr(0,i) << input.at(i)<<reverseString.substr(numberOfSpaces,i) <<spaces<<endl;
}
This is an example of the input/output:
string spaces(" ",numberOfSpaces);
This doesn't do what you think it does.
This constructor takes an array and a count.
It copies count (in this case numberOfSpaces) items from the passed in array.
The passed in array has length 1 (technically 2 with the null terminator), and so anything > 2 will cause undefined behaviour as it reads off the end of the array.

Time limit exceeded on test 10 code forces

hello i am a beginner in programming and am in the array lessons ,i just know very basics like if conditions and loops and data types , and when i try to solve this problem.
Problem Description
When Serezha was three years old, he was given a set of cards with letters for his birthday. They were arranged into words in the way which formed the boy's mother favorite number in binary notation. Serezha started playing with them immediately and shuffled them because he wasn't yet able to read. His father decided to rearrange them. Help him restore the original number, on condition that it was the maximum possible one.
Input Specification
The first line contains a single integer n (1⩽n⩽105) — the length of the string. The second line contains a string consisting of English lowercase letters: 'z', 'e', 'r', 'o' and 'n'.
It is guaranteed that it is possible to rearrange the letters in such a way that they form a sequence of words, each being either "zero" which corresponds to the digit 00 or "one" which corresponds to the digit 11.
Output Specification
Print the maximum possible number in binary notation. Print binary digits separated by a space. The leading zeroes are allowed.
Sample input:
4
ezor
Output:
0
Sample Input:
10
nznooeeoer
Output:
1 1 0
i got Time limit exceeded on test 10 code forces and that is my code
#include <iostream>
using namespace std;
int main()
{
int n;
char arr[10000];
cin >> n;
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
for (int i = 0; i < n; i++) {
if (arr[i] == 'n') {
cout << "1"
<< " ";
}
}
for (int i = 0; i < n; i++) {
if (arr[i] == 'z') {
cout << "0"
<< " ";
}
}
}
Your problem is a buffer overrun. You put an awful 10K array on the stack, but the problem description says you can have up to 100K characters.
After your array fills up, you start overwriting the stack, including the variable n. This makes you try to read too many characters. When your program gets to the end of the input, it waits forever for more.
Instead of putting an even more awful 100K array on the stack, just count the number of z's and n's as you're reading the input, and don't bother storing the string at all.
According to the compromise (applicable to homework and challenge questions) described here
How do I ask and answer homework questions?
I will hint, without giving a code solution.
In order to fix TLEs you need to be more efficient.
In this case I'd start by getting rid of one of the three loops and of all of the array accesses.
You only need to count two things during input and one output loop.

Array input after pressing enter becoming 0

#include <iostream>
using namespace std;
int main() {
int start_time[3];
int final_time[3];
int i;
for(i=0;i<3; i++)
cin >> start_time[i];
for(i=0;i<3;i++)
cin >> final_time[i];
int a[10];
for(i=0;i<=10;i++)
a[i]=0;
for(i=0;i<3;i++){
cout << start_time[i] << " " << final_time[i] << endl;
}
}
If I give the following input:
23 53 09
23 53 10
We see that the output is:
23 0
53 53
9 10
Why is it taking the starting input of final_time equal to 0 after I press enter?
How do I solve this?
int a[10];
for(i=0;i<=10;i++)
a[i]=0;
In this part, you are writing a 0 into a[10]. But a[10] does not exist. a[] only has space for 10 integers, indexed 0 to 9. So you are writing a zero to somewhere in memory, and you overwrote your final_time[0] by chance. Could have been something else or could have crashed your program, too.
Fix this by correcting your loop to for(i=0;i<10;i++) like your other loops.
Writing to an array out of it's allocated bounds is undefined behavior in C++. that basically means it's not defined in the standard and each compiler vendor will have to make something up for their product on what should happen if you do this. So it's rather random and therefor bad (tm). You may get a different behavior when you switch compilers, you may even get a different behavior when you restart your program. In your case, your compiler vendor (like many others) decided that they will just not check if the developer was correct. They just write that zero to the space in memory that a[10] would have been at, had it existed. But it did not. And by plain chance there was another variable at that spot in memory. So that one had it's value overwritten by the zero.
You're invoking a undefined behaviour by out of bound indexing for array a
The for loop
for(i=0;i<=10;i++)
~~~
should use i < 10 to index from 0 to 9 for 10 elements

How to store a big number in parts in an array and then add up the digits?

Let suppose a user enters a number below:
54353325421435
i want the variables below to store parts of the number above
Eg.
int part[3]
part[0]=54353
part[1]=32
part[2]=5421435
and then add up the digits and store it the variable like below:
Eg.
int sum[3]
sum[0]=5+4+3+5+3 //sum up part[0]
sum[1]=3+2 //sum up part[1]
sum[2]=5+4+2+1+4+3+5 //sum up part[2]
Sorry guys! I don't know, how to explain this better! I hope you understand my question.
Thanks for reading
Problem
You want to divide your integer to 3 different parts. Basically, you have a number 54353325421435, and you want to divide it up into:
part[0]=54353
part[1]=32
part[2]=5421435
Then add them up.
Solution
A for loop will do best. If you don't know what a for loop is, basically it's a means of iteration with a defined starting and ending point. For example, here is a simple iteration that prints out "hello world" 2 times:
for(int i=0; i<2; i++)
cout << "Hello World" << endl;
You can learn more about for loops here. In your case, what you want to do is iterate through this. So basically, first you store the variable in an integer. (I'm sure you can do that.)
const unsigned long long NUM = 54353325421435; //Make it a constant to not change it
And then you have an array of parts as you mentioned above:
int part[3]
What you can do now is, loop through the NUM. So let me show you how to do the first one:
int access_digits(const unsigned long long int n, int index)
{
int digit_array[64] = {0};
unsigned long long digits = 0, digit, number = n;
while (number) {
digit = number % 10;
number /= 10;
digit_array[digits] = digit;
digits++;
}
return digit_array[digits - index - 1];
}
std::string digits;
for(int i=0; i<=4; i++)
{
digits.append(std::to_string(access_digits(NUM,i)));
}
int digit_int = std::stoi( digits );
You can see above, first that there is an access_digits function. You can use that function to access digits by index. (Credit goes toward Slayther.) Anyway, after that, you can see I am looping from 0 to 4 to get the first 5 digits for part[0]. The first 5 digits bring 54353.
Now finally you want to add them up. Well, again that's pretty easy. Just loop through the digits, and have an accumulator add them up like so:
int accum=0;
for(int i=0; i<4; i++)
{
accum += access_digits(digit_int,i);
}
Exercise
Now edit this to include part[1] and part[2] below on the exercise section.
References
Iterating through digits in integer in C
Teenage Territory chat
for loop
std::string
string::append
Glossary
For Loops:
Executes init-statement once, then executes statement and iteration_expression repeatedly until the value of condition becomes false. The test takes place before each iteration.
Syntax
formal syntax:
attr(optional) for ( init-statement condition(optional) ; iteration_expression(optional) ) statement
informal syntax:
attr(optional) for ( declaration-or-expression(optional) ; declaration-or-expression(optional) ; expression(optional) ) statement
if you want the sum of the digits of no. as you mentioned above then
int number,digit,sum=0;
while(number!=0)
{
digit=number%10;
sum=s+digit;
number=number/10;
}
this code segment will calculate the sum of the digits of the no.
if number=123;
it will calculate sum=3+2+1=6;

forloop lines of arrays

int lineInputs = 0;
cin >> lineInputs;
int whatever = 0;
char* myArray = new char[arrayElements*lineInputs];
int j =0;
for(int i = 0; i < lineInputs; i++)
{
cin >> whatever;
for(j; j<total; j+=39)
{
for(int nom=0; j<arrayElements; nom++)
{
cin >> myArray[j];
}
}
}
In my forloop say i have lineInputs = 4 and total = 156
Meaning 4 times we do this, we want to insert 156 chars into my array. But we want to make it so that every 40 characters we continue entering the array.
Bsically we need to insert this input into the array but i feel like my forloops are messed up. This will be the input
4
1
HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH
2
TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT
3
HHTTTHHTTTHTHHTHHTTHTTTHHHTHTTHTTHTTTHTH
4
HTHTHHHTHHHTHTHHHHTTTHTTTTTHHTTTTHTHHHHT
The first line 4 meaning 4 of these 40 character lines. And the number above the character lines just signifying line 1 2 3 4 ect.
How can i attempt this right?
So the array would basically look like this.
HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTHHTTTHHTTTHTHHTHHTTHTTTHHHTHTTHTTHTTTHTHHTHTHHHTHHHTHTHHHHTTTHTTTTTHHTTTTHTHHHHT
You are making the same fundamental mistake you made in your other question, which is to fail to treat the input array correctly. You are repeatedly reading into the first 40 characters of myArray. What you need to do is read the first line into the first 40 characters, the second line into characters 40 to 79, etc.
Better yet, make it a two dimensional array so that you don't have to muck around with computing the indices.
Even better, make it an array of std::string rather than an array of char.