I've been trying for a while to do a specific problem that our teacher gave us at school if we wanted to earn a good grade but I couldn't do it.
But now, I'm actually very interested in solving this.
{
int i,n,a[100],c;
cout <<"n=";
cin >>n;
for(i=1;i<=n;i++)
{
cout <<"a["<<i<<"]=";
cin>> a[i];
}
for (i=2;i<=n-1;i++)
if (a[i]/10==0)
{
c=a[i];
a[i]=a[i-1]+a[i+1];
a[i-1]+a[i+1]=c;
}
for (i=1;i<=n;i++)
{
cout<<"a["<<i<<"]="<<a[i]<<endl;
}
return 0;
}
ERROR AT: a[i-1]+a[i+1]=c;
lvalue required as left operand of assignment.
The questions I have to solve with this once it's done are, for example: What will be shown for n=5 and the vector a=(22,4,10,5,16)?
Hi, Richard. I actually don't want anything to happen on that line but the reason for why that error occurs. What I'm doing with that part of the code is to apply the interchange algorithm, so that, for example, when the code is finished and I'll have to press F9 in the CodeBlocks Application, there will be a chosen n, which the problem tells me that it's 5, and then I'll have to pick the 5 numbers shown in the a vector which are 22,4,10,5,16
ex: a[1]=22, a[2]=4, a[3]=10, a[4]=5, a[5]=16.. When all of that is done, the application has to change my a[1] with a[2], so a[1] will have the value of a[2] and so on.
You are assigning a value to a constant: a[i-1]+a[i+1]=c;
Because the statement above doesn't return an address of the element but the value in that address which is of course constant. It is like you write:
5 = n;
To solve your problem then:
(a[i-1]+a[i+1])=c; becomes:
c = (a[i-1]+a[i+1]); // because c is not a constant
Related
I find this very stupid to ask, but I've been trying a question on Google Kickstart (Round A, 2021).
Now, firstly, I'd like to clarify that I do NOT need help with the question itself, but I'm encountering a weird issue that seems to be compiler-related. This problem only arises on certain compilers.
I am posting the question link, then the question statement if someone does not wish to use the link, then the problem I'm facing along with the code that works and the code that doesn't work.
Question Title: K-Goodness String, Round A (2021)
Question Link: https://codingcompetitions.withgoogle.com/kickstart/round/0000000000436140/000000000068cca3
Problem
Charles defines the goodness score of a string as the number
of indices i such that Si ≠ SN−i+1 where 1≤i≤N/2 (1-indexed). For
example, the string CABABC has a goodness score of 2 since S2 ≠ S5 and
S3 ≠ S4.
Charles gave Ada a string S of length N, consisting of uppercase
letters and asked her to convert it into a string with a goodness
score of K. In one operation, Ada can change any character in the
string to any uppercase letter. Could you help Ada find the minimum
number of operations required to transform the given string into a
string with goodness score equal to K?
Input
The first line of the input gives the number of test cases, T. T
test cases follow.
The first line of each test case contains two integers N and K. The
second line of each test case contains a string S of length N,
consisting of uppercase letters.
Output
For each test case, output one line containing Case #x: y,
where x is the test case number (starting from 1) and y is the minimum
number of operations required to transform the given string S into a
string with goodness score equal to K.
Sample Input:
2
5 1
ABCAA
4 2
ABAA
Sample Output:
Case #1: 0
Case #2: 1
Explanation:
In Sample Case #1, the given string already has a goodness score of 1. Therefore the minimum number of operations required is 0.
In Sample Case #2, one option is to change the character at index 1 to B in order to have a goodness score of 2. Therefore, the minimum number of operations required is 1.
The issue:
The problem is fairly straightforward, however, I seem to be getting a wrong answer in a very specific condition, and this problem only arises on certain compilers, and some compilers give the correct answer for the exact same code and test cases.
The specific test case:
2
96 10
KVSNDVJFYBNRQPKTHPMMTZBHQPZYQHEEEQFQWOJHPHFBFXGFFGXFBFHPHJOWQFQEEEHQYZPQHBZTMMPHTKPQRNBYFFVDNXIX
95 7
CNMYPKORAUTSYETNXAZQZGBFSJJNMOMINYKNTMHTARUMDXAJAXDMURATHMTNKYNIMOMNJJSFBGZQZAXNTEYSTUAROKPKJCD
Expected Output:
Case #1: 6
Case #2: 3
The problem arises when I do NOT use std::cout.clear() at a very specific place in my code. Just printing the value of any random variable also seems to solve this issue, it doesn't necessarily have to be cout.clear() only. I'm pasting the codes below.
**Original Code (Gives incorrect answer):**
//
// main.cpp
// Google Kickstart - Round A (2021)
//
// Created by Harshit Jindal on 10/07/21.
//
#include <iostream>
#define endl "\n"
using namespace std;
int main() {
int num_test_cases;
cin >> num_test_cases;
for (int test_case = 1; test_case <= num_test_cases; test_case++) {
int answer = 0;
int N, K;
cin >> N >> K;
char s[N];
cin >> s;
int current_goodness = 0;
for (int i = 0; i < N/2; i++) {
if (s[i] != s[N-1-i]) { current_goodness++; }
}
answer = abs(current_goodness - K);
cout << "Case #" << test_case << ": " << answer << endl;
}
return 0;
}
Incorrect Result for original code:
Case #1: 6
Case #2: 6
Modified Code (With cout.clear() which gives correct answer):
//
// main.cpp
// Google Kickstart - Round A (2021)
//
// Created by Harshit Jindal on 10/07/21.
//
#include <iostream>
#define endl "\n"
using namespace std;
int main() {
int num_test_cases;
cin >> num_test_cases;
for (int test_case = 1; test_case <= num_test_cases; test_case++) {
int answer = 0;
int N, K;
cin >> N >> K;
char s[N];
cin >> s;
int current_goodness = 0;
for (int i = 0; i < N/2; i++) {
if (s[i] != s[N-1-i]) {
current_goodness++;
}
cout.clear();
}
answer = abs(current_goodness - K);
cout << "Case #" << test_case << ": " << answer << endl;
}
return 0;
}
Correct Result for modified code:
Case #1: 6
Case #2: 3
A few additional details:
This issue is NOT coming up on my local machine, but on Google Kickstart's Judge with C++17 (G++).
Answer for Case #2 should be 3, and NOT 6.
This issue does NOT come up if only the second test case is executed directly, but only if executed AFTER test case #1.
The issue is ONLY resolved if the cout.clear() is placed within the for loop, and nowhere else.
We don't necessarily have to use cout.clear(), any cout statement seems to fix the issue.
I know it's a long question, but given that a problem is only coming up on certain machines, I believe it would require a deep understanding of c++ to be able to understand why this is happening, and hence posting it here. I'm curious to understand the reasoning behind such a thing.
Any help is appreciated.
As pointed out by Paddy, Sam and Igor in the comments, here is the solution as I understand it:
The problem arises because char s[N] is NOT C++ standard, any variable length arrays, for that matter. That might cause a buffer overrun, and will write over memory outside of the array, causing all sorts of weird behaviour.
The best way to avoid these kinds of bugs is to make it logically impossible for them to happen. – Sam Varshavchik
In this case, using string s solved the issue without having to call cout.clear().
Also, using #define endl "\n" might be faster when redirecting output to files, but since we're importing the entire std namespace, any person who does std::cout will get an error because it'll essentially get translated to std::"\n" which does not make sense.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
This is a C++ program to search a number and also display its index position if found in an array.
Program works fine. I just wanted to ask why we used k=1 in if statement because if we don't use it, then program won't work. Please explain the significance of k=1 in 2nd for loop in if statement.
#include<iostream>
using namespace std;
int main(){
int n;
cout<<"Size of Array: ";
cin>>n;
int arr[n];
cout<<"Type Elements of Array: ";
for(int i=0; i<n; i++)
{
cin>>arr[i];
}
int k;
cout<<"Enter No to be found: ";
cin>>k;
for(int i=0; i<n; i++)
{
if(arr[i]==k)
{
k=1;
cout<<"No is found at index position: "<<i<<endl;;
break;
}
else
{
cout<<"No is not found";
break;
}
}
return 0;
}
Looks like you are trying to do a linear search, there are some points I would like to clarify..
Never use int arr[n] using cin by user, it may work in yours, but not all compilers support it. Always allocate memory to the array statically like arr[10] or arr[20]
You are changing k which is the number that is to be found, I cannot understand why are you changing k . This is the number that is to be searched, you are mistakenly interpreting k as a flag variable, but it is NOT. Never try to change the input variable from the user.
Your program will only work, if the number you are searching is at 0th index, because, after that you are literally breaking from the loop in both if as well as else condition.
Here is a link to a better linear search code in c++, I hope it will clear your concepts C++ Linear Search
The problem is not with the k=1 statement. It lies in your logic of the else block.
Consider this:
n = 5
arr = [12, 2, 3, 14, 5]
k = 3
So initially i in the for loop starts from 0
It checks for equality:
Is arr[i] == k ?
arr[0] == 3 ?
12 == 3?
This is false, so your program goes to the else block, where it prints that the number was not found and breaks from the for loop. So essentially you are not checking all numbers, just the first one.
PS: Try and find a working logic for this on your own, it will be a good exercise and improve your understanding if you are getting started with programming (Hint: There are multiple ways, either through a flag variable or using the loop variable, etc). When your program doesn't work as you wanted it to, perform a dry run like I did on top.
You should go for the dynamic allocation of the array. Secondly, there is a mess with your if-else block. It checks only the first number in the array and then proceeds to the else portion. Your program can work fine but you should make sure that it searches the complete array for the number to be searched. You can do it by just removing the else part:
for(int i=0;i<n;i++)
{
if(arr[i]==k)
{
cout<<"No is found at index position: "<<i<<endl;;
return 0;
}
}
cout<<"No is not found.";
return 0;
#include<iostream.h>
int main()
{
int n[50],p=0;
double g=1;
char c;
cout<<"\n press a for addition";
cout<<"\n press m for multiplication";
cin>>c;
if(c=='a')
{
for(int i=0;n[i]=!'=',i<50;i++)
{
cin>>n[i];
p+=n[i];
}
cout<<p;
}
else if(c=='m')
{
for(int j=0;n[j]=!'=',j<50;j++)
{
cin>>n[j];
g*=n[j];
}
cout<<g;
}
else cout<<"wrong input";
}
I have wrote this code, it works perfectly fine when addition part is used but when multiplication is done it isn't giving the final product. Whenever I click '=' it doesn't give any final product during multiplication but while addition the same logic works fine.
You have multiple problems:
The array n isn't initialized so its contents will be indeterminate, and using indeterminate values lead to undefined behavior.
Fortunately (for you) the loop "condition" expression n[j]=!'=',j<50 doesn't do what you probably think it does... The part n[j]=!'=' is actually equal to n[j] = !'='. That is you assign the result of !'=' to n[j].
And about the loop "condition", the result of n[j]=!'=',j<50 is the result of j<50 only, because that's how the comma operator works.
With cin>>n[j] you can't read arbitrary characters, as n[j] is an int and you only read int values. The only way to get a '=' from the input is if the user inputs the value 61 which happens to be the ASCII encoded value for '='.
Your loop "condition" also have another flaw, because you increase j before you check n[j], so in the condition n[j] will always be an element of the array that you haven't read into.
And building on the previous point, because the value of j will be wrong in the "condition" you will go out of bounds of the array which also leads to undefined behavior.
The code is giving SIGSEGV error. How can I remove it? The code is multiplying elements of an array and modulo 109+7 at each step of multiplication.
int main()
{
int n;
int A[10];
cin >> n;
for(int i = 0; i < n; i++)
cin >> A[i];
int ans = 1;
int m = 1000000007;
for(int i = 0; i < n; i++)
{
ans = (ans * A[i]) % m;
}
cout << ans;
}
In your code the array A is declared as of 10 elements. However, afterwards the amount of elements to handle is asked to user. Also, potentially the first number enterred by the user seems to be either negative or more than 10. In this case you need to test the enterred value.
Besides that, you can use std::vector instead of the array A to be of a dynamic size. Then after the user has given the amount of elements (with the first std::cin) you can set the size of the vector. The rest code then will remain nearly the same with some cosmetical changes.
Arrays in C++ do not magically resize themselves. As a result, if the user enters a value for n of 10 or more, both loops attempt to access elements of the array A past its end. For example, if n is 13, the loops will access 13 elements of a 10 element array named A.
That is undefined behaviour. If your host system is some unix variant (e.g. linux) and the operating system detects your program accessing memory it shouldn't, it will send a SIGSEGV signal to your program, which forceably causes the program to exit. However, that is only one possible symptom of many.
Given that this is a homework exercise, I'll just say you need to work out a way to dynamically allocate an array with n elements - AFTER reading n. Using a standard container (like std::vector<int>) is one way - but, depending on what your homework requires, may not be permitted. In that case, look up operators new and delete. (No, I will not be more specific - this is your homework, not mine)
I am taking my very first C++ class and I am stuck. I would really appreciate some help from you experienced programmers.
The assignment is creating a blackjack-scoring program. Not a very realistic one, but hey. The user inputs how many cards he wants and then the values of each of those cards. The assignment specifies that the inputs should be in type char. So if the user has a 2 card they enter 2, but that 2 is actually char and must be converted to int. Or they would enter "Q" if they have a queen and my program is supposed to convert that Q to ten points for scoring. I cannot figure out what is the right way to do this. The assignment suggests I will use either a switch statement or nested if-else statement, but I am afraid I don't understand switch very well from the book examples.
So here's a tiny bit of my attempts at switch. *points_for_card* is of type char and *number_value* is int.
switch (points_for_card)
{
case '2':
number_value = 2 ;
break;
case '3':
number_value = 3 ;
break;
// ETC
}
So what I am going for here is: if the user enters '3' as a char, it becomes int 3. But maybe this is not how switch works at all.
The thing is, my program compiles and works, but returns weird crazy huge numbers. If I move points_for_card to int instead of char, then the arithmetic works perfectly for whatever numbers I enter, because at that point it's just adding them together.
I hope I explained this ok, will clarify as much as possible if necessary.
it can be something like this code:
if (points_for_card >= '1' && points_for_card <= '9'){
number_value = points_for_card - '0'; // convert to number
}else if (points_for_card == 'Q'){
...
}
A map comes to mind. You can store the scores directly, or you can make one map to look up the card type and other maps to associate other information (like score) to each card. Here's the baby example:
std::map<char, int> scores;
scores['Q'] = 10; scores['A'] = 13; scores['2'] = 2; // etc.
char c;
std::cout << "Please enter a card: ";
std::cin >> c;
std::cout << "Your card has score " << scores[c] << std::endl;
Oftentimes when your heart says "switch", your brain should say "map" :-)
Personnally I'd define an enum ECardType { Card_2, ..., Card_10, Card_Jack, ... }; and have one map be std::map<char, ECardType>, and then other maps from card type to secondary information like scores.
How are you taking inputs into points_for_card ?
Your input should be cin >> points_for_card;
Instead of comparing a character to a character, you can also compare it to the ASCII value of a character.
For example,
char letter = 'A'
if(letter == 65){
cout << "Match";
}
The above code will output "Match!".
Also, your switch statements are perfectly worded. The problem lies elsewhere in your program, so please provide the relevant source.
Another point related to your program but not your problem: How are you dealing with Aces ? You know that they can be counted as either 1 or 11, depending on the player's hand value, right ?