C++ , A2oj.com , Supermarket [duplicate] - c++

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);

Related

Why does my code give me different answers when I initialize a variable compared to when I add a simple value like 0? [duplicate]

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

Write a program that prompts the user to input an integer and then outputs both the individual digits of the number and the sum of the digits

For Example: Input: 982
Outputs: 9 8 2
Your Total sum is: 19
I see people using input_number % 10 in a loop and then input_number / 10 but I still do not get it. If i did 982 % 10 I would get 2 and then they add it to the sum which is 0 + 2 = 2 and how would that get 19???? and then the input number which is 982/10 is equal to 9.82 how does lead me to my solution of 19?? I am just super confused can someone please explain it to me and try to work out the problem and make it into a simple solution. I appreciate it and try to use the basic stuff like including namespace std and then not using arrays just loops and simple math equations thank you.
int n,sum=0;
cin>>n;
while(n!=0)
{
sum=sum+(n%10);
n=n/10;
}
/*
Since your n is an integer it will drop the value after decimal.
Therefore, 982 will run as
Iteration 1 n=982
sum=2
n=982/10=98
Iteration 2
sum=2+(98)%10 = 10
n=98/10= 9
Finaly in iteration 3
n=9/10=0 hence loop will terminate and sum be 19*/
You should input the number as a characters, that you convert into the digits and then individual numbers, that are easy to add or print or whatever. Avoid complicated math when you can totally live without it.
std::string str;
std::cin >> str;
int sum = 0;
for( int i=0; i<str.length(); i++) {
if( isdigit(str[i]) ) {
std::cout << str[i] << " ";
sum += int(str[i] - '0') // convert a char to int
}
}
std::cout << std::endl;
std::cout << "Total sum: " << sum << std::endl;
or something like that. Haven't programmed in C++ for a while, there might be minor mistakes in the code, but you get the general idea.

How do I find 20 odd numbers starting from a number entered by user? [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 3 years ago.
Improve this question
So, i was given an assignment to find 20 odd numbers starting from a number entered by user.. I know how to find odd numbers. but I don't know how to find them starting from a number entered by user.
I tried this:
#include<iostream>
using namespace std;
int main(){
int num,i;
cout<<"Enter num: ";
cin>>num;
for(i=num;i<=20;i++){
if(i%2!=0)
cout<<num <<endl;
}
}
but it outputs the number entered by user 20 times.
As the comment says, you output the num, not newly calculated i, but even if you fix that, you will output only few odd numbers (or none), for example for input 50 there will be no output instead of odd 20 numbers (because 50 <= 20 is always false, so no for body will be executed). Plus you are doing lot of math... while the whole task can collapse to trivial:
#include<iostream>
int main() {
int num;
std::cout << "Enter num: ";
std::cin >> num;
num |= 1; // turn user number into odd one (if it was even)
const int endNum = num + 20*2; // calculate the first odd number after 20 of them (end value)
while (num < endNum) {
std::cout << num << std::endl;
num += 2;
}
}
doing just simple addition +2 in loop.
edit: btw, why num |= 1; guarantees odd number... because integers in computer are stored as binary values, where every digit is different power of two, with the least significant bit corresponding to the zeroth power of two (i.e. value 1). If this bit is set, then the value is odd, because dividing by two does apply from first power of two upward and this bottom bit is remainder. And if it is reset, the value is even, for the same reason, the bottom bit is remainder after you would divide the value by two. The binary or operator |= 1 will set the least significant bit to one, turning any integer value to odd one.
This is the special case, when your task involves calculation based on powers of two. Because all the values in computer are already encoded in the binary way, there are usually shortcuts how to get the result of such calculation. Like for example to get remainder of division by 16 from integer n you can do binary and: n & 15 and you have the remainder. Or to divide by 16 you can shift the unsigned integer value by four bits to the right like n >> 4 to get the result. But this doesn't work with calculations which are not power-of-two based, i.e. remainder after dividing by ten is NOT n & 9, because 9 is 0b1001, so different values will be trimmed down to only values 0, 1, 8 or 9, but remainders after dividing by 10 can be any value from 0 to 9. .. while 15 is in binary 0b1111, so such binary and-mask will produce all values from 0 to 15, and they correspond to the remainder by div 16.
The bug in your code is that you print num instead of i. So just do:
cout<< i <<endl;
^
But you can simplify your code a lot by doing:
#include<iostream>
using namespace std;
int main(){
int num,i;
cout<<"Enter num: ";
cin>>num;
if (num%2 == 0) ++num; // Make sure num is odd
for(i=0; i < 20; ++i){ // Print 20 numbers
cout << (num + 2*i) << endl; // Multiply i by 2 and add it to num
// so that the result is the next odd number
}
}
note
As suggested by Ped7g the line
if (num%2 == 0) ++num; // Make sure num is odd
can be made more simple. Just replace it with
num |= 1; // Set the least significant bit so that num is odd
This loop
for(i=num;i<=20;i++){
if(i%2!=0)
cout<<num <<endl;
}
does not make sense because it checks the variable i instead of the variable num whether it is an odd number. And it is obvious there will be outputted a half of 20 values of i.
The program can look the following way
#include <iostream>
int main()
{
const size_t N = 20;
int n = 0;
std::cout << "Enter a number: ";
std::cin >> n;
n |= 1; // make the first odd number
for ( size_t i = 0; i < N; i++ )
{
std::cout << n << ' ';
n += 2;
}
}
Its output might look the following way
Enter a number: 10
11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49
A more correct professional code can look the following way
#include <iostream>
#include <limits>
int main()
{
const size_t N = 20;
int n = 0;
std::cout << "Enter a number: ";
std::cin >> n;
n |= 1;
for ( size_t i = 0; i < N; i++ )
{
std::cout << n << ' ';
n = std::numeric_limits<int>::max() - 2 < n ? std::numeric_limits<int>::min() | 1 : n + 2;
}
}
In this case if the user will enter the maximum integer value then the output will look like
Enter a number: 2147483647
2147483647 -2147483647 -2147483645 -2147483643 -2147483641 -2147483639 -2147483637 -2147483635 -2147483633 -2147483631 -2147483629 -2147483627 -2147483625 -2147483623 -2147483621 -2147483619 -2147483617 -2147483615 -2147483613 -2147483611

Create an algorithm that asks the user for two positive numbers, call them "first" and "last", and prints the sum of all the numbers between first [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have a program that I need to compile that does the following:
1.One way to do multiplication is by repeated addition. For example, 47 x 25 can be evaluated as 47 + 47 + 47 + . . .+ 47 (25 times). Sketch out an algorithm for multiplying two positive numbers a and b using this technique.
2.Create an algorithm that asks the user for two positive numbers, call them "first" and "last", and prints the sum of all the numbers between first and last inclusive. Thus, for example if the input was 4 and 7 (this works also if input was 7 and 4), the algorithm will print 22 because 4+5+6+7 = 22
So for the first one I really don't have an idea how to start and I understand that it's simple but I'm new to programming.
For the second problem I wrote this program but there's one error of unexpected unqualified-id right after int main()
#include <iostream>
int main();
{
int num1, num2, sum = 0; //Sum starts at 0 and contains the sum of all even numbers
cout << "Enter first integer: ";
cin >> num1;
cout << "Enter second integer: ";
cin >> num2;
{
while (num1 <= num2)
sum += num1;
num1++; };
cout << "Sum is " << sum << "." << endl;
cin.get();
return=0;
}
I would appreciate any advice as soon as possible
This doesn't concern the code itself, but rather efficiency: This can easily be solved in constant time. Thanks to Gauss we know:
sum from 0 to N is: N * (N + 1) / 2
We can simply calculate the sum from first to last using that formula. Simply substract the sum from 0 to first - 1 from the sum from 0 to last:
int sum = last * (last + 1) / 2 - (first - 1) * (first) / 2;
Thanks to #MOehm for pointing out some mistakes in my answer.
Remove the semicolon after main(), prepend cout, cin and endl with std:: (i.e. make it std::cout, std::cin and std::endl), and remove the = in return=0.
The code will then compile.

long integer multiplication in c++

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?