Comparing a String with 2d Array [closed] - c++

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 8 years ago.
Improve this question
actually I am trying to compare a string with a 2d array.If the entered string is already present in the array the program should terminate.If the string is not present then it should be stored in the next row of array.
what this piece of code is doing is that it is not telling if the entered "cnic" has been previously entered or not. I am using Turbo C++ 3.0 compiler so please keep that in mind.
This program actually takes cnic of user and check whether that cnic has been previously entered or not.
Here is my Program
cout<<"\nEnter Your CNIC?\n";
gets(cnic);
**for (i=0;i<=13;i++)
{
if (strcmp(cnic,cnic2)==0)
{
cout<<"This Cnic has already casted the vote";
}
}
cnic2[i][j]=cnic[i];
j++;**

I used Turbo C (even not ++) but it was long long time ago ... More seriously, I assume :
cnic is a char array of size 13 (12 + terminating null)
cnic2 should be a 2D array of 100 char arrays of size 13 (it is not what is written in your code)
you want to see if cnic C-string is already in cnic2, if it is you reject it, if not you add it.
j is the index of next element in cnic2, and should be explicitely set to 0 before main loop.
Declaration :
char cnic2[100][13];
int found; /* should be bool found but unsure if Turbo C++ knows about that */
(you code was declaring a array of 13 C-Ctring of size 100)
Test loop (including code reviewed and tested by OP) :
/* should control size of nic before that processing - I ASSUME IT HAS BEEN DONE */
found = 0; /* should be found = false; and later use false and true instead of 0 and 1 */
for(i=0; i<j; i++) {
if (0 == strcmp(cnic, cnic2[i]) {
found = 1;
break;
}
}
if (found) {
cout<<"This Cnic has already casted the vote";
continue;
}
if (j == 99) {
count << "Too much Cnic already";
break;
}
strcpy(cnic2[j++], cnic);
/* Revised and Working Code
found = 0; /* should be found = false; and later use false and true instead of 0 and 1 */
for(i=0; i<j; i++) {
if (0 == strcmp(cnic, cnic2[i]))
{
found = 1;
break;
}
}
if (found) {
cout<<"This Cnic has already casted the vote";
continue;
}
if (j == 99) {
cout << "Too much Cnic already";
break;
}
strcpy(cnic2[j++], cnic);

Concentrating on the code you marked with **. The mistakes are numbered below:
for (i=0;i<=13;i++) // (1)
{
if (strcmp(cnic,cnic2)==0) // (2)
{
cout<<"This Cnic has already casted the vote";
}
}
cnic2[i][j]=cnic[i]; // (3)
For mistake (1), you are looping too many times. You want to loop from 0 to 12, or use < 13, not <= 13.
For mistake (2), the second argument to strcmp() is wrong. You want to compare the string starting at cnic2[j].
For mistake (3), you are accessing an element out-of-bounds of both arrays, since i will be 13.
I won't fix these for you, since your code does much more. My answer pointed out was is obviously wrong.

Related

Caeser's Cipher not working for lower case characters [closed]

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 last year.
This post was edited and submitted for review last year and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
Please someone run it , It runs fine for all uppercase values but if you include some x y or z the code breaks.
I found this in hackerrack and several test cases were passed but several failed.
#include<iostream>
using namespace std;
string caesarCipher(string, int);
int main() {
string s;
int places, length;
cin>>length;
cin>>s;
cin>>places;
if(places >26) {
places = places % 26 ;
}
s= caesarCipher(s,places);
cout<<s;
}
string caesarCipher(string S, int k){
for(int i=0;i<S.length();i++){
if(S[i]>='a' && S[i] <='z'){
S[i] = S[i]+k;
if(S[i]>'z'){
S[i]=S[i]-'z'+'a'-1;
}
}
else if(S[i]>='A' && S[i] <= 'Z'){
S[i] = S[i]+k;
if(S[i]>'Z'){
S[i]= S[i]-'Z'+'A'-1;
}
}
else
;
}
return S;
}```
To my own surprise, it looks like strings do not like certain values, not even temporarily.
If you use
S[i] = (S[i]-'a'+k)%26+'a'; instead of
S[i] = S[i]+k;, no value outside of a-z is ever written to the string, which as far as I tested avoids your problem.
An input of "Helloxyz" with a shift of 2 gets an output of "Jgnnqzab".
An the reverse, with a shift of 24 gets "Helloxyz" again.
With that, you do not need
if(places >26) {
places = places % 26 ;
}
/* ... */
if(S[i]>'z'){
S[i]=S[i]-'z'+'a'-1;
}
/* ... */
if(S[i]>'Z'){
S[i]= S[i]-'Z'+'A'-1;
}

This is a program to search a number and also display its index position if found in an array [closed]

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;

Unexpected changing of C++ constant integer [closed]

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 8 years ago.
Improve this question
The variable steady_counter is intialized as a constant integer.
cout << steady_counter;
So long as i have the above statement anywhere before the following code, the function runs as expected and checks if an integer input is or is not a runaround number.
The problem is that when the cout line is not present, the constant integer changes within the below if statements. I tested this by printing steady_counter before entering the if-else, and then after the if-else.
Without the cout line, steady_counter changes to a 4 digit number.
for (int i = 0; i < 10; i++)
{
if (CheckArr[i])
{
num_of_unique++;
}
}
if ((steady_counter == num_of_unique) & (final == NumArr[0]) )
{
return true;
}
else
{
return false;
}
}
Any idea what's going on? Why do I require a cout line to maintain the constant integer steady_counter?
One obvious problem:
for (int i = counter; i > 0; i --)
NumArr[i] = -1;
This covers values from 1 to counter inclusive; while valid indexes for NumArr are from 0 to counter-1 inclusive. So you write outside the array, corrupting something else; possibly another local variable.
Either correct the off-by-one error in the index
NumArr[i-1] = -1;
or use a more canonical loop
for (int i = 0; i < counter; ++i)
or, for more of a C++ flavour,
std::fill(NumArr, NumArr+counter, -1);
There are likely to be further errors, which are better found by using your debugger than by asking people to read through all your code.

C++ total beginner needs guidance [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
yesterday,we had to solve problems at the codeforces contest
I couldn't solve this problem since I am a total beginner.
http://codeforces.com/contest/353/problem/A
I used this algorithm, but something is wrong with it. I think it should print s or f, however it prints nothing. it just auto closes. Even when I added an input to stop instant close
#include <cstdlib>
#include <iostream>
using namespace std;
int main(){
int y=0;
int x=0;
int f;
int a;
cin >> a;
int s;
s = 0;
int number [a][a];
for(int i = 0;i<a;i++){
cin >> number[i][0] >> number[i][1];
x += number[i][0];
y += number[i][1];
}
for(int i = 0;i<a;i++){
if(x%2==0 && y%2==0){
return s;
}else if(y%2!=0 && x%2==0){
f = -1;
return f;
}else if(y%2==0 && x%2!=0){
f = -1;
return f;
}else{
y+= number[i][0];
x+= number[i][1];
s++;
}
}
int g;
if(f!=-1){
cout << s;
}else{
cout << f;
}
}
As Angew said, the return statements are incorrect and causing you to exit your main. You want to replace this by a break; to exit the loop but not the function.
I have not spent effort in trying to understand your algorithm, but at first glance it looks more complicated than it should be.
From my understanding of the problem, there are 3 possibilities:
the totals of the upper halves and the lower halves are already even (so nothing needs to be done)
the totals of the upper halves and the lower halves cannot be made even (so no solution exists)
just one Domino needs to be rotated to get the totals of the upper halves and the lower halves to be even (so the time needed is 1 second)
I base this on the fact that adding only even numbers always gives an even result, and adding an even number of odd numbers also always gives an even result.
Based on this, instead of having a 2-dimensional array like in your code, I would maintain 2 distinct arrays - one for the upper half numbers and the other for the lower half numbers. In addition, I would write the following two helper functions:
oddNumCount - takes an array as input; simply returns the number of odd numbers in the array.
oddAndEvenTileExists - takes 2 arrays as input; returns the index of the first tile with an odd+even number combination, -1 if no such tile exists.
Then the meat of my algorithm would be:
if (((oddNumCount(upper_half_array) % 2) == 0) && ((oddNumCount(lower_half_array) % 2) == 0))
{
// nothing needs to be done
result = 0;
}
else if (((oddNumCount(upper_half_array) - oddNumCount(lower_half_array)) % 2) == 0)
{
// The difference between the number of odd numbers in the two halves is even, which means a solution may exist.
// A solution really exists only if there exists a tile in which one number is even and the other is odd.
result = (oddAndEvenTileExists(upper_half_array, lower_half_array) >= 0) ? 1 : -1;
}
else
{
// no solution exists.
result = -1;
}
If you wanted to point out exactly which tile needs to be rotated, then you can save the index that "oddAndEvenTileExists" function returns.
You can write the actual code yourself to test if this works. Even if it doesn't, you would have written some code that hopefully takes you a little above "total beginner".

Professionalise this code [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 11 years ago.
Improve this question
I have been programming for about 3 years now and feel confident in my skills. But recently I began working alongside embedded systems and working on other peoples code and have begun to question how good my code is.
I see all these complex answers on SO and think I would have done that with a vector and if statements and wonder if I am any more than a beginner as I was self taught and don't really know my level.
So I was wondering if more experienced programmers could show me ho to do things better.
This is code I wrote to for an rpg game to pick a target to attack. using it as an example could you show me better/more advanced/professional ways of doing it.
int FindTarget(Player &player);
{
int aimPoint[5] = 0;
for(int i = 0; i <= 5; i++)
{
if(player.team[i].exist == true)
{
// set random starting point between 1 - 3
aimPoint[i] = random /3;
// add a point if you hve an elemental advantage minus if not
if(player.team[i].type == weak)
{
aimPoint += 1;
}
else if(player.team[i].type == strong)
{
aimPoint -= 1;
}
//add for front row minus for back
if(i == 1 || i== 3)
{
aimPoint += 1;
}
else
{
aimPoint -= 1;
}
}
}
return 0;
}
EDIT: If you don't have the time or effort to show me examples I would appreciate a good book that a beginner/intermediate could understand.
Comment #1:
This line starts at 0, and goes exactly once? Why is it a loop?
for(int i = 0; i <= 0; i++)
Comment #2:
Don't compare a boolean against true.
if(player.team[i].exist == true)
Just re-write it to:
if(player.team[i].exist)
Comment #3:
Professionals rarely use hardcoded values.
Why is this value 5?
int aimPoint[5] = 0;
Instead, make it clear:
int aimPoint[TARGET_SIZE] = 0;
Similarly, change
aimPoint[i] = random /3;
to:
aimPoint[i] = random /INITIAL_TARGET_VALUE;
This is pointless; it's not a loop, it's a single pass.
for(int i = 0; i <= 0; i++)
ahem since nobody mentioned it, let me point this one out:
int FindTarget(Player &player);
{
int aimPoint[5] = 0;
...
return 0
}
to roughly
void FindTarget(const Player &player)
{
std::vector<int> aimPoint(5, 0);
...
}
Also, since there is no knowing what the code should do (and how 'aimPoint' is related to teams; guessing doesn't help because none of it is used, aimPoint is discarded?), I don't have anything else than fixing the obvious breakage that was above
---- Edit from a comment
The handling of random seems misguided. Someone suggested that you might have meant random %3 + 1;
I noted that too but decided there is nothing to base the assumption on. Perhaps random is already an int in the range [3, 12).
Also, random % 3 won't yield a uniform distribution, so you'd need to do something else
For many applications, rand() will perform admirably when used correctly, but with the current sad state of affairs, rand() is very rarely used correctly.
The problem is that of distribution
Here is how I would write it.
void FindTarget(Player &player);
{
int aimPoint[5];
for(int i = 0; i <= 5; ++i)
{
if(!player.team[i].exist)
continue;
// set random starting point between 1 - 3
aimPoint[i] = random / 3;
// add a point if you hve an elemental advantage minus if not
switch(player.team[i].type) {
case weak:
++aimPoint[i];
break;
case strong:
--aimPoint[i];
break;
}
//add for front row minus for back
if(i == 1 || i== 3)
++aimPoint[i];
else
--aimPoint[i];
}
}
That piece of code:
// set random starting point between 1 - 3
aimPoint[i] = random /3;
don't get you random number between 1 and 3, try this:
aimPoint[i] = random % 3 + 1