Creating Array with values from console - c++

I am trying to create an array by taking value 'n' from the console and create an array with 'n' inits and then again take a value 'r' to work.
so far I wrote
int main(){
int n = 0;
cin >> n;
int* a = new int[n];
for(int i = 0; i< sizeof(a);i++){
cin >> a[i];
}
for(int y = 0; y < sizeof(a);y++){
cout << a[y] << " ";
}
int r = 0;
cin >> r;
rotate(a,r);
(the "cout" part is for checking the output of the array)
but no matter I try I would get an array which length doesn't equal the input 'n'. Can anyone give me some advice on it?
Here the outputs for every input from console:
(the second row is supposed to be the created array)
INPUT
6
1 2 3 4 5 6
3
OUTPUT
1 2 3 4 5 6 3 0
INPUT
10
-1 -2 3 4 5 -6 7 -8 9 0
5
OUTPUT
-1 -2 3 4 5 -6 7 -8
INPUT
1
1
1
OUTPUT
1 1 0 0 0 0 135137 0
INPUT
5
1 2 3 4 5
5
OUTPUT
1 2 3 4 5 -3 135137 0
Any ideas why those unexplainable numbers at the end?

As Algirdas said, take a close look at what SizeOf does. Also, you don't really need it. You can make it work like this:
for(int i = 0; i< n; i++){
cin >> a[i];
}
As you've got 'n' elements in your array.
Also, I know that most textbooks are really fond of arrays, but please follow Cody Gray's advice!

Related

Spiral matrix, i am getting extra elements while printing spiral matrix order. Don't know why?

// printing in spiral order matrix
#include<iostream>
using namespace std;
int main(){
int n,m;
cin>>n>>m;
int arr[n][m];
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
cin>>arr[i][j];
}
}
// print
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
cout<<arr[i][j]<<" ";
}
cout<<endl;
}
// spiral print
int row_start=0,row_end=n-1,col_start=0,col_end=m-1;
while(row_start<=row_end && col_start<=col_end){
for(int j=col_start; j<=col_end; j++){
cout<<arr[row_start][j]<<" ";
}
row_start++;
for(int i=row_start; i<=row_end; i++){
cout<<arr[i][col_end]<<" ";
}
col_end--;
for(int j=col_end; j>=col_start; j--){
cout<<arr[row_end][j]<<" ";
}
row_end--;
for(int i=row_end; i>=row_start; i--){
cout<<arr[i][col_start]<<" ";
}
col_start++;
}
return 0;
}
My output is:
PS C:\Users\anmol\Desktop\c++projectwork> ./a
3 4
1 2 3 4 5 6 7 8 9 0 1 2
1 2 3 4
5 6 7 8
9 0 1 2
1 2 3 4 8 2 1 0 9 5 6 7 6
I am getting an extra '6' at the end.
which is not required however this type of problem only come when matrix is rectangular.
But code works fine for square matrix.
Please tell me where i went wrong..
Suppose you have a below matrix. Let's dry run your code on below example.
1 2 3 4
5 6 7 8
9 10 11 12
Dry Run
1st for loop: prints 1 2 3 4 row_start=1,row_end=2,col_start=0,col_end=3
2nd for loop: prints 8 12 row_start=1,row_end=2,col_start=0,col_end=2
3rd for loop: prints 11 10 9 row_start=1,row_end=1,col_start=0,col_end=2
4th for loop: prints 5 row_start=1,row_end=1,col_start=1,col_end=2
All condition of while loop are true 2nd Iteration of while loop:
1st for loop: prints 6 7 row_start=2,row_end=1,col_start=1,col_end=2
2nd for loop: won't do anything row_start=2,row_end=1,col_start=1,col_end=1
3rd for loop: prints 6
DO you see the problem?
you should run 3rd for loop only if
"row_start < row_end"
similarly you should check for
"col_start<col_end"
before running the 4th loop

Homework: Testing square with all equal rows

So for my current homework assignment, I have to determine whether the sum of all the rows in a square are equal, if they are all equal then the square is 'Awesome' otherwise 'Not Awesome'. In this program the first input is the number of squares you want to solve and then for each square you enter how many rows it will have, followed by a series of integers to represent each number in the 'square'. Below is my tried and tested code, for me, I cant seem to come up with a test case that breaks it, yet when I upload it for grading, the grading bot fails it. Any help is greatly appreciated.
At first I thought it was an overflow issue, so I changed the sum and temp variables to long long but it had no effect.
input examples:
3
4
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
3
1 2 3
2 3 1
3 2 7
5
1 2 3 4 5
1 1 1 1 11
2 2 2 2 7
3 3 3 3 3
4 4 4 4 -1
output would be:
Awesome
Not Awesome
Awesome
#include <iostream>
using namespace std;
int main()
{
int numTests, numRows, i, col, row, firstRun;
long long sum, prevSum, temp;
cin >> numTests;
for (i = 0; i < numTests; i++)
{
firstRun = 1;
cin >> numRows;
for (row = 0; row < numRows; row++)
{
sum = 0;
for (col = 0; col < numRows; col++)
{
cin >> temp;
sum += temp;
}
if (!firstRun && prevSum != sum)
break;
firstRun = 0;
prevSum = sum;
}
if (row != numRows)
cout << "Not ";
cout << "Awesome" << endl;
}
return 0;
}
You are breaking the loop when you get the answer . But input may not finish .
1
4
1 2 3 4
1 2 3 1
1 2 3 4
1 2 3 4
Here , your loop will break after inputting second row . Thus the subsequent numbers are treating wrongly and causing WA . Consider the case
2
3
1 2 3
1 2 1
3 2 1
3
3 1 1
1 1 3
1 3 1
Your program will print
Not Awesome
Not Awesome

C++ Array (disregarding a repeat number)

I am a beginner programmer and I need some assistance.
I need to write a program that reads an array of 10 numbers from a user, then scans it and figures out the most common number/s in the array itself and prints them. If there is only one number that is common in the array, only print that number. But, if there's more than one number that appears more than once, print them also in the order they appear in in the array.
For example- 1 2 3 3 4 5 6 7 8 9 - output would be 3
For- 1 2 3 4 1 2 3 4 5 6 - output would be 1 2 3 4
for- 1 1 1 1 2 2 2 3 3 4 - output would be 1 2 3
Now, the problem I've been running into, is that whenever I have a number that repeats more than twice (see third example above), the output I'm getting is the number of iterations of the loop for that number and not only that number once.
Any assistance would be welcome.
Code's attached below-
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int array [10], index, checker, common;
main ()
{
for (index=0; index<10; index++)
{
cin >> array [index];
}
for (index=0; index<10; index++)
{
int tempcount=0;
for (checker=(index+1);checker<10;checker++)
{
if (array[index]==array[checker])
tempcount++;
}
if (tempcount>=1)
cout << array[index]<<" ";
}
return 0;
}
Use appropriate data structures for the task.
Create a std::unordered_map that maps value to number_of_occurrences, and make a single pass over the input data.
Then create another map from number_of_occurrences to value. Sort it, in descending order. Report the first value, plus any additional ones that occurred as many times as the first did.
The reason you are having problems is that anytime a number appears two times or more it will print out. A solution is that you create another variable maxCount, then find the maximum times a number appears. Then loop through the array and print out all the numbers that appears the maximum amount of times.
Hope this helps.
Jake
Rather than writing you a solution, I will try to give you some hints that you can hopefully use to correct your code. Try to keep track of the following things:
Remember the position of the first occurrence of each distinct number in the array.
Count the number of times each number appears
and combine the two to get your solution.
EDIT:
int array[] = {1, 2, 3, 4, 1, 2, 3, 4, 5, 6};
int first [11], cnt[11];
for(int i = 0; i < 11; i++){
first[i] = -1;
cnt[i] = 0;
}
int max = 0;
for(int i = 0; i < 10; i++){
cnt[array[i]]++;
if(max < array[i]) max = array[i];
}
for(int i = 0; i <= max; i++){
if(cnt[i] > 1 && first[i] == -1) {
printf(" %d", i);
first[i] = i;
}
}
You could do something like this. At any index in the array look for previous occurences of that element. If you find that that it is the first occurence of that element, you only need to look if there is an occurence of that element ahead in the array.
Lastly display the element whose frequency(here num) would be greater than 1.
for (int i = 0; i < 10; i++)
{
int presentBefore = 0;
for (int j = 0; j < i; j++) //if any previous occurence of element
{
if (array[i] == array[j]) presentBefore++;
}
if (presentBefore == 0)//if first occurence of the element
{
int num = 1;
for (int j = i + 1; j < 8; j++)// if occurences ahead in the array
{
if (array[i] == array[j]) num++;
}
if(num>1)cout<<array[i]<<" ";
}
}
Here is another solution using STL and std::set.
#include <iostream>
#include <algorithm>
#include <set>
#include <iterator>
int main()
{
int array[12] = { 1, 2, 3, 1, 2, 4, 5, 6, 3, 4, 1, 2 };
std::set<int> dupes;
for (auto it = std::begin(array), end = std::end(array); it != end; ++it)
{
if (std::count(it, end, *it) > 1 && dupes.insert(*it).second)
std::cout << *it << " ";
}
return 0;
}
Prints:
1 2 3 4
I will try to explain how this works:
The original array is iterated from start to finish (BTW as you can see it can be any length, not just 10, as it uses iterators of beginning and end)
We are going to store duplicates which we find with std::count in std::set
We count from current iterator until the end of the array for efficiency
When count > 1, this means we have a duplicate so we store it in set for reference.
std::set has unique keys, so trying to store another number that already exists in set will result in insert .second returning false.
Hence, we print only unique insertions, which appear to be in the order of elements appearing in the array.
In your case you can use class std::vector which allows you to Erase elements, resize the array...
Here is an example I provide which produces what you wanted:
1: Push the values into a vector.
2: Use 2 loops and compare the elements array[i] and array[j] and if they are identical push the the element j into a new vector. Index j is always equal to i + 1 in order to avoid comparing the value with itself.
3- Now you get a vector of the repeated values in the temporary vector; You use 2 loops and search for the repeated values and erase them from the vector.
4- Print the output.
NB: I overloaded the insertion operator "<<" to print a vector to avoid each time using a loop to print a vector's elements.
The code could look like :
#include <iostream>
#include <vector>
std::ostream& operator << (std::ostream& out, std::vector<int> vecInt){
for(int i(0); i < vecInt.size(); i++)
out << vecInt[i] << ", ";
return out;
}
int main() {
std::vector< int > vecInt;
//1 1 1 1 2 2 2 3 3 4
vecInt.push_back(1);
vecInt.push_back(1);
vecInt.push_back(1);
vecInt.push_back(1);
vecInt.push_back(2);
vecInt.push_back(2);
vecInt.push_back(2);
vecInt.push_back(3);
vecInt.push_back(3);
vecInt.push_back(4);
std::vector<int> vecUniq;
for(int i(0); i < vecInt.size(); i++)
for(int j(i + 1); j < vecInt.size(); j++)
if(vecInt[i] == vecInt[j])
vecUniq.push_back(vecInt[j]);
std::cout << vecUniq << std::endl;
for(int i = 0; i < vecUniq.size(); i++)
for(int j = vecUniq.size() - 1 ; j >= 0 && j > i; j--)
if(vecUniq[i] == vecUniq[j])
vecUniq.erase(&vecUniq[j]);
std::cout << vecUniq << std::endl;
std::cout << std::endl;
return 0;
}
The input: 1 2 3 3 4 5 6 7 8 9
The output: 3
The input: 1 2 3 4 1 2 3 4 5 6
The output: 1 2 3 4
The input: 1 1 1 1 2 2 2 3 3 4
The output: 1 2 3
For this problem, you can use a marking array that will count the number of times you a digit is visited by you, it's just like counting sort. let's first see the program :
#include <iostream>
using namespace std;
int print(int a[],int b[])
{
cout<<"b :: ";
for (int index=0;index<10;index++)
{
cout<<b[index]<<" ";
}
cout<<endl;
}
int main ()
{
int a[10],b[11], index, checker, common;
for (index=0; index<10; index++)
{
cin >> a [index];
b[index] = 0;
}
b[10] =0;
for (index=0;index<10;index++)
{
b[a[index]]++;
if (b[a[index]] == 2)
cout<<a[index];
//print(a,b);
}
return 0;
}
As you can see that I have used array b as marking array which counts the time a number is visited.
The size of array b depends upon what is the largest number you are going to enter, I have set the size of array b to be of length 10 that b[11] as your largest number is 10. Index 0 is of no use but you need not worry about it as it will be not pointed until your input has 0.
Intially all elements in array in b is set 0.
Now assume your input to be :: 1 2 3 4 1 2 3 4 5 6
Now value of b can be checked after each iteration by uncommenting the print function line::
b :: 0 1 0 0 0 0 0 0 0 0 ....1
b :: 0 1 1 0 0 0 0 0 0 0 ....2
b :: 0 1 1 1 0 0 0 0 0 0 ....3
b :: 0 1 1 1 1 0 0 0 0 0 ....4
b :: 0 2 1 1 1 0 0 0 0 0 ....5
b :: 0 2 2 1 1 0 0 0 0 0 ....6
b :: 0 2 2 2 1 0 0 0 0 0 ....7
b :: 0 2 2 2 2 0 0 0 0 0 ....8
b :: 0 2 2 2 2 1 0 0 0 0 ....9
b :: 0 2 2 2 2 1 1 0 0 0 ....10
In line 5 you can b's at index 1 has value 2 so it will print 1 that is a[index].
And array a's element will be printed only when it is repeated first time due to this line if(b[a[index]] == 2) .
This program uses the idea of counting sort so if you want you can check counting sort.

Number triangle using while loops

I'm having trouble with my C++ programming class homework.
Here is the assignment:
Write a program which reads in the number of rows and prints 'n' rows
of digits.
1
12
123
1234
12345
where the i’th row is 1234 . . . k where k = i mod 10. If a row
has more than 10 digits, the digit after 9 should start again from 0.
For instance, if the number of rows is 15, the output should be: 1
12
123
1234
12345
123456
1234567
12345678
123456789
1234567890
12345678901
123456789012
1234567890123
12345678901234
123456789012345
This is what I have so far:
#include <iostream>
using namespace std;
int main()
{
int rows(0);
int i(0);
int j(0);
cout << "Enter number of rows: ";
cin >> rows;
int k=rows;
i=1;
while (i <= rows)
{
j=1;
while(j <= i)
{
cout << j;
j++;
}
cout << endl ;
i++;
}
return (0);
}
This works perfectly until I get to the 10th row. I'm not sure how to get the counter to reset back to 0 and go 1-9 again. I'm guessing an if statement, but I don't know how to correctly implement it. Any help would be greatly appreciated.
Using cout << j%10 will always print the ones digit of whatever j is equal to. So when j = 10, cout << j%10 will print 0, etc.
To expand on the other answer a bit:
% is referred to as the remainder operator. It is also sometimes called "modulo" or "modulus". It returns the remainder of the first argument divided by the second argument. So for this situation, since you want the number to be between 0 and 9, consider what happens when you have n % 10.
8 / 10 == 0 remainder 8
9 / 10 == 0 remainder 9
10 / 10 == 1 remainder 0
11 / 10 == 1 remainder 1
12 / 10 == 1 remainder 2
Etc.
In C++, as in most programming languages, you typically start counting at 0 and you exclude the final number in your range. So if you had n % 56, your output starting at 0 would go up to 55, and then reset to 0 again. The classical argument for this was written by Dijkstra:
http://www.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/EWD831.html

Insertion sort homework

In the input I have to specify the array as well as it's elements and the output should be in the form given below
input
5
2 4 6 8 3
Sample Output
2 4 6 8 8
2 4 6 6 8
2 4 4 6 8
2 3 4 6 8
And this is my output
2 4 6 8 8
2 4 6 6 8
2 4 4 6 8
2 4 3 6 8
2 3 3 6 8
2 3 3 6 8
int main() {
int* a=0;
int n,x;
std::cout<<"Enter size ";
std:: cin>>n;
std::cout<<"Enter elements ";
a=new int[n];
for(int i=0;i<n;i++){
std::cin>>x;
a[i]=x;
}
int q=a[n-1];
for(int i=n;i>=0;i--){
if(a[i-2]>q)
{ a[i-1]=a[i-2];
}else
a[i]=q;
for(int j=0;j<n;j++ )
{ std::cout<<a[j];cout<<" ";
}
cout<<" \n ";
}
//for(int j=0;j<n;j++ ){std::cout<<a[j];}
getch();
}
What am I doing wrong?
Since i goes all the way down to 0. Then i-2 can go to -2. Thus this line indexes before the beginning of the array, which is undefined behavior:
if(a[i-2]>q)
Here you are assigning over the value in the array without remembering what the old value was.
}else
a[i]=q;
Thus you are loosing information and thus something is going to go wrong as a sort is not supposed to destroy information.