I am a beginner in C++. I am trying this long integer multiplication. I am not understanding that how the value ofsum[3][0] is changing in the subsequent loop cycle.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string num1, num2;
int i,j,l1, l2,temp,k;
cout << "Enter first number: ";
cin >> num1;
cout << "Enter second number: ";
cin >> num2;
l1= num1.size();
l2= num2.size();
cout << l1 << " " << l2 << endl;
int sum[l2-1][l2]; // 5 6 7 8 ---> num1
// 1 2 3 4 ---> num2
for(i=0; i<l1; i++) // ---------
num1[i]-='0'; // 2 2 7 1 2 sum[3][4]---->sum[3][0]
// 1 7 0 3 4 i.e sum[3][0] should be 2
for(i=0; i<l2; i++) // 1 1 3 5 6
num2[i]-='0'; // 5 6 7 8
// -------------
for(i=l2-1; i>=0; i--) // 7 0 0 6 6 5 2
{
k=0;
temp=0;
for(j=l1-1; j>=0; j--)
{
temp+=(num2[i]*num1[j]);
sum[i][k]= temp%10;
temp=temp/10;
k++;
}
sum[i][k]=temp;
cout << sum[3][0] << endl;
}
for(i=l2-1; i>=0; i--) // output is 2 2 7 1 1 Here value of sum[3][0] is 1 but the desired output is 2.
{ // 1 7 0 3 1
for(k=l2; k>=0; k--) // 1 1 3 5 0
cout << sum[i][k]; // 0 5 6 7 8
cout << endl;
}
return 0;
}
I tried this code for the case num1=5678 and num2=1234. So sum[3][0] should be 2 in that case.
You did not make sum large enough. You use sum[0..l2-1][0..l1] so the size would need to be sum[l2][l1+1].
When you exceed the second dim of sum that typically makes part of one row of sum share storage with part of another, so the place where you stored sum[2][0] is the same place you later stored sum[1][4]
When you exceed the first dim of sum (or the second dim in the last row) that makes sum share storage with other things, such as(but not necessarily) the other variables local to that function.
Also, your loop for displaying sum is incorrect. You use rows of sum from l2-1 down to 0 and columns from 0 up to L1. But you display columns l2 down to 0. The columns are computed based on l1, so should be displayed based on l1. That error would have symptoms if you tried an example with l1 not equal l2.
The sum array should be create like this:
int sum[l2][max(l1,l2)+1];
It is too small to store results of you calculations now.
Why program doesn't crash while you write out of bounds of the array? Because C++ has not any array bounds checking.
To be honest, you should declare the array by new and remove it by delete when it is not needed anymore. C++ standard doesn't provide to create non-constant size array without new. Only some compilers supports it as an extension and many of them prints warnings when you do that. More informations here: How do I declare a 2d array in C++ using new?
Related
I'm testing a simple program via Clion 2022.2.4.
#include<iostream>
int main() {
int n, num[10] = {0};
std::cin >> n;
for (int i = 1; i <= n; i++)
std::cin >> num[i];
for (int i = 1; i <= n; i++)
std::cout << num[i] << " ";
return 0;
}
When I paste the following into the Run window via the clipboard and hit Enter, it turns out as expected.
Input:
4
1 2 2 2
Output:
1 2 2 2
When I pasted the following into the Run window via the clipboard, hit the backspace key, typed 2, and then hit enter, the result changed.
Input:
4
1 2 2 2
Output:
1 2 2 24
We can see that the last number changes from 2 to 24. But in fact the input for both operations before and after is 4 1 2 2 2 2(At least that's what it looks like).
Meanwhile, I tried some other inputs
By typing 4 1 2 2 1 through the clipboard, then change the last 1 to 8, the output is as follows:
Input:
4
1 2 2 8
Output:
1 2 2 14
By typing 3 1 2 3 through the clipboard, then change the last 3 to 7, the output is as follows:
Input:
3
1 2 3
Output:
1 2 33
I noticed that it seems that the last anomalous number is a combination of the last number on the clipboard and n.
Also, if n is entered on the same line as another n numbers, the result is correct even if the last number is modified.
Input:
4 1 2 2 2
Output:
1 2 2 2
So I want to know what's going on here, or is this just a bug?
I am not sure what is the issue you are having with the processing of terminal input.
Nevertheless there are several issues in your code:
Array indices are 0..n-1 (not 1..n) - where n is the number of elements.
In c++ is is better to use std::vector instead of c style arrays
(or std::array for fixed size and usually small arrays).
Using std::vector will make your code support an arbitrary array size (not bound by e.g. 10 like in your code).
As mentioned in the comments above, it is recomended to end the output with a newline to avoid having the terminal prompt on the same line.
Better version:
#include <iostream>
#include <vector>
int main() {
int n;
std::vector<int> num;
std::cin >> n;
num.resize(n);
for (int i = 0; i < n; ++i)
std::cin >> num[i];
for (int i = 0; i < n; ++i)
std::cout << num[i] << " ";
std::cout << std::endl;
return 0;
}
This question already has answers here:
What happens when I print an uninitialized variable in C++? [duplicate]
(4 answers)
Closed 2 years ago.
Below you have two different codes. The difference between the two is simply for the variable sum, sum was initialized compared to giving sum the value 0 sum =0;
#include <iostream>
using namespace std;
int main(){
//This code will display first ten numbers and get the sum of it
cout << "The natural numbers are: " << endl;
for(int i=1; i<=10; i++)
{
cout << i << " ";
}
cout << endl;
// variable was initialized
int sum;
cout << "The sum of first 10 natural numbers: ";
for(int i=1; i<=10; i++)
{
sum = sum +i;
}
cout << sum;
cout << endl;
}
This Code outputs:
The natural numbers are:
1 2 3 4 5 6 7 8 9 10
The sum of first 10 natural numbers: 32821
Program ended with exit code: 0
#include <iostream>
using namespace std;
int main(){
//This code will display first ten numbers and get the sum of it
cout << "The natural numbers are: " << endl;
for(int i=1; i<=10; i++)
{
cout << i << " ";
}
cout << endl;
// here I gave the value 1... this time it worked
int sum =0;
cout << "The sum of first 10 natural numbers: ";
for(int i=1; i<=10; i++)
{
sum = sum +i;
}
cout << sum;
cout << endl;
}
This Code outputs:
The natural numbers are:
1 2 3 4 5 6 7 8 9 10
The sum of first 10 natural numbers: 55
Program ended with exit code: 0
Why does the code do this? Can someone please explain to me why they gave me two different sums?
If you do not initialize sum it has an indeterminate value and there's no way you can tell what operations on it will do. Reading an uninitialized variable is undefined behaviour and doing so renders your entire program invalid.
Btw; you seem to be confused about what initialization is. int sum; does not initialize sum, it just declares it - it does not give it an initial value and you may not read it or use it in computations until you have assigned it a known value. int sum = 0; does initialize sum - that is, it gives it an initial value and you can now validly read it and use it in computations.
Actually in the first set of code the compiler took a random value of variable sum. In your case I think the compiler took value of of sum as 32766. This value 32766 is "garbage value".
So see in second case you gave sum a initial value hence compiler knows that user has given a value. So accordingly it will perform your given operation. Inside the loop sum will start from 0 and keep performing the given operation until it exit the loop.
The operation for this Case2 codes is given below :
sum = sum + i; //(here value of "i" increase by 1 with iteration of the given loop)
/* 1 = 0 + 1
3 = 1 + 2
6 = 3 + 3
10 = 6 + 4
15 = 10 + 5
21 = 15 + 6
28 = 21 + 7
36 = 28 + 8
45 = 36 + 9
55 = 45 + 10
As you can see the value of "sum" after the loop is 55
*/
But in first case you didn't give sum initial value, so compiler don't know whether the value of sum is 0, 6, 15, 7 or 10. So, compiler took a random value for it, in your case it is 32766. Inside the loop it start from 32766 and continue its given operation.
The operation for the Case1 codes see below :-
sum = sum + i; //(like previous case here too value of "i" increase by 1 with iteration of the given loop)
/* 32767 = 32766 + 1
32769 = 32767 + 2
32772 = 32769 + 3
32776 = 32772 + 4
32781 = 32776 + 5
32787 = 32781 + 6
32794 = 32787 + 7
32802 = 32794 + 8
32811 = 32802 + 9
32821 = 32811 + 10
Here you can see the value of "sum" after the operation is 32821
*/
Okay! summing up everything, your logic and code looks fine to me but in first case the value of sum was allotted by compiler randomly, so here everything went wrong for the first case.
Activate the compiler flag -Wuninitialized.
In the first program, the sum is kept uninitialized and contained garbage value. Thus, you get the error. OTOH, in the second program, the value of sum is initialized to 0, which is exactly a zero and thus, the count did successful.
When you write int sum; in c++, a space in the memory is reserved for this variable, because it's not only a declaration, but also a definition. As sum is not set to any value yet, then, in this case, it gets any crazy value stored in it's space of memory that was already stored there before. Hope it helped :) Here are some useful links about this:
link1;
link2
#include <iostream>
using namespace std;
int main(){
int n;
int a[n];
cin>>n;
for(int i=0;i<n;i++){
cin>>a[i];
}
for(int i=n;i>=0;i--){
cout<<a[i]<<" ";
}
}
Input:- 4
1 2 3 4
Output 4199008 4 3 2 1
For starters the program has undefined behavior because the variable n is not initialized
int n;
So this declaration
int a[n];
is invalid. Moreover variable length arrays is not a standard C++ feature. Instead use the standard class template std::vector.
Also within this loop
for(int i=n;i>=0;i--) {
cout<<a[i]<<" ";
}
you are trying to access of non-existent element with the index n.
Also you are not reversing an array. You are trying to output an array in the reverse order.
Pay attention to that there are standard algorithms std::reverse and std::reverse_copy declared in the header <algorithm>.
Here is an example how your program with using your approach could look
#include <iostream>
#include <vector>
int main()
{
size_t n = 0;
std::cout << "Enter the size of an array ";
std::cin >> n;
std::vector<int> v( n );
std::cout << "Enter " << n << " elements: ";
for ( auto &item : v ) std::cin >> item;
std::cout << "The array in the reverse order\n";
for ( size_t i = v.size(); i != 0; )
{
std::cout << v[--i] << ' ';
}
std::cout << '\n';
return 0;
}
The program output might look like
Enter the size of an array 10
Enter 10 elements: 0 1 2 3 4 5 6 7 8 9
The array in the reverse order
9 8 7 6 5 4 3 2 1 0
If to use standard algorithms then your program can look the following way
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
int main()
{
size_t n = 0;
std::cout << "Enter the size of an array ";
std::cin >> n;
std::vector<int> v( n );
std::cout << "Enter " << n << " elements: ";
std::copy_n( std::istream_iterator<int>( std::cin ), n, std::begin( v ) );
std::cout << "The array in the reverse order\n";
std::reverse_copy( std::begin( v ), std::end( v ),
std::ostream_iterator<int>( std::cout, " ") );
std::cout << '\n';
return 0;
}
The program output might look the same way as shown above
Enter the size of an array 10
Enter 10 elements: 0 1 2 3 4 5 6 7 8 9
The array in the reverse order
9 8 7 6 5 4 3 2 1 0
a[n] will return the element after the last one. When you iterate in reverse order, start with i=n-1.
At the beginig of your program there is a mistake:
int n; // You declare n with no value
int a[n]; // You use is
cin>>n; // After you used it you get your value-
Now i can suppose that that was just an error while copying it because you give inputs and outputs
Input:- 4 1 2 3 4 Output 4199008 4 3 2 1
So forgeting about that, you declare an array of size n. Remember that the elemnts of the array will go from 0 to n-1. Now look at your second for loop
// the first element you acces is n and you stop at 1
// but the array goes from n-1 to 0
for(int i=n;i>=0;i--){
cout<<a[i]<<" ";
}
So you still get n values as an output but the first element that you access is outside of the array. Thats why you get a garbage value, that is a value that was left there.
A solution will be to change the for loop
for(int i=n-1;i>=-1;i--){
cout<<a[i]<<" ";
}
While reversing the array start the loop from n-1 that is i=n-1 (n is the no of elements in array). And run the loop till i>=0. If you will start loop from n it will read illegal index which is out of range and will give you garbage value.
for(int i=n-1; i>=0; i++){
cout<<arr[i]<<" ";}
How could you move array characters?????????
Here is some basic code with high-level comments. It is not exactly as you desire. But since you have provided some code it is nearly there.
After reading the comments and understanding what is happening, it should be relatively straightforward to modify the below code to your requirements:
#include <iostream>
void printArray(int gameboard[5][5]){
std::cout << "This is what the gameboard looks like now:" << std::endl;
for ( int i = 0; i < 5; i++ ) {
for ( int j = 0; j < 5; j++ ) {
std::cout << gameboard[i][j] << ' ';
}
std::cout << std::endl;
}
}
int main() {
// Declare array and print what it looks like
int gameboard[5][5] = { {1,2,3,4,5}, {1,2,3,4,5}, {1,2,3,4,5}, {1,2,3,4,5}, {1,2,3,4,5}};
printArray(gameboard);
// Get input for which coordinates the user wants to swap
int row1, column1, row2, column2;
std::cout << "Please enter the coordinates of the first piece:" << std::endl;
std::cout << "Row:";
std::cin >> row1;
std::cout << "Column:";
std::cin >> column1;
std::cout << "Please enter the coordinates of the second piece:" << std::endl;
std::cout << "Row:";
std::cin >> row2;
std::cout << "Column:";
std::cin >> column2;
// Swap values at provided coordinates by using a temp variable
int temp = gameboard[row1][column1];
gameboard[row1][column1] = gameboard[row2][column2];
gameboard[row2][column2] = temp;
printArray(gameboard);
return 0;
}
Example Usage:
This is what the gameboard looks like now:
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
Please enter the coordinates of the first piece:
Row: 0
Column: 0
Please enter the coordinates of the second piece:
Row: 4
Column: 4
This is what the gameboard looks like now:
5 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 1
Tasks TO-DO for you:
Change printArray to allow arrays of varying sizes not just 5 x 5.
Ensure user input for row, column and value are numbers.
Ensure user input row, and column values are within the bounds of the array.
This question already has answers here:
Array size at run time without dynamic allocation is allowed? [duplicate]
(8 answers)
Closed 7 years ago.
This is Problem
Supermarket
Problem Statement:
You're in a supermarket and want to buy N items but you have only S dollars.
Input Format:
first two numbers N (the number of items) and S (The amount of dollars you have) followed by N integers indicate the price of each item
N is a positive integers less than or equal to 1,000,000
0 < S < 1,000,000,001
All prices are less than 1,000,001
Output Format:
Print "Yes" if the total price of items less than or equal to S and print "No" otherwise.
Sample Input:
6 100 8 31 4 12 19 2
Sample Output:
Yes
Notes:
8 + 31 + 4 + 12 + 19 + 2 = 76
76 < 100
Then "Yes" you can buy them
This is My Code:
#include <iostream>
using namespace std;
int main()
{
int N,S;
cin >> N >> S;
int sum=0;
int numslist[N];
for (int i=0; i<N; i++)
{
cin>>numslist[i];
sum=sum+numslist[i];
}
if(sum<=S)
cout << "No" << endl;
else if(sum>S)
cout << "Yes" << endl;
return 0;
}
I submit This Code and The Online Judge and it say Wrong answer Website
Please any one Help me and say What's the wrong?
You may not declare an array with a size that is only known at run-time, it must be known at compile time (ignoring compiler extensions). So you cannot do this
int N;
cin >> N;
int numslist[N];
Instead you could do
int N;
cin >> N;
vector<int> numslist(N);