I coded palindrome program.
I think this code is right especially is_palindrome procedure.
But I don't know why this answers wrong.
Because when I input 2 1 1, return must be This is palindrome.
But it answers the other.
#include <iostream>
using namespace std;
bool is_palindrome(int input[], int numOfSlots);
int main(void) {
int n;
cin >> n;
int *input = new int[n]; // A dynamic array with n slots
for (int i = 0; i < n; i++) {
cin >> input[i];
}
if (is_palindrome(input, n) == true) {
cout << "This is a palindrome.";
}
else {
cout << "This is NOT a palindrome.";
}
return 0;
}
bool is_palindrome(int input[], int numOfSlots) {
int i = 0;
while (i < numOfSlots/2)
{
if (input[i] != input[numOfSlots-i])
return false;
i++;
}
return true;
}
You are going one past then end of the array in if (input[i] != input[numOfSlots-i]). When i == 0 then input[numOfSlots-i] becomes input[numOfSlots] which in this case is input[2]. Since the last valid index of input is 1 you are comparing against garbage. You should have
if (input[i] != input[numOfSlots-i - 1])
Arrays in C++ are zero indexed, as i is initialised to 0, on the first iteration of the loop input[numOfSlots-i] is out of bounds.
Related
I am trying to implement the algorithm RLE with simple input like:
ddddddddddhhhhhhhhhhhhhhhttttttttttttt
code:
#include<iostream>
#include<fstream>
#include<vector>
using namespace std;
int main() {
vector<char> read;
ifstream file;
file.open("file.txt");
if (!file) {
cout << "Unable to open";
}
char v;
while(file>>v) {
read.push_back(v);
}
char x;
int count=0;
for(int i=0; i<read.size(); i++) {
x = read[i];
if(x != read[++i]) {
cout << x << "1";
}
while(x == read[++i]) {
count++;
}
cout << x << count;
count = 0;
}
return 0;
}
The output I am getting is:
d9d1h12h1t10t1
Please help me with the code.
Update: I have updated the question as I have realized few things.
Plus: This code produced no output, is there anything wrong which I am doing wrong?
char o;
char n;
int count=0;
for(int i=0; i<read.size(); i++) {
o = read[i];
n = read[++i];
while(o == n) {
count++;
}
cout << o << count;
if(o != n) {
cout << o << "1";
} count = 0;
}
return 0;
This loop:
char x;
int count=0;
for(int i=0; i<read.size(); i++) {
int j=i;
x = read[i];
if(x != read[++j]) {
cout << x << "1";
}
while(x == read[++j]) {
count++;
}
cout << x << count;
}
Has several errors. First, you should use two indices, i and j. i is going through each element of read, but then j is iterating through a subsequence too. What you want is to go through each element only once, and in each case either print or increase the count. However having a for loop and moving the index inside too is not a very good practice, is rather error-prone. Also you have to cout statements that are do not run at the right time (you don't wan to print something on every iteration, only when the character changes). You could do it with a while loop, or using a simpler structure like:
// If there are no characters finish
if (read.empty()) {
return 0;
}
// Get the first character
char lastChar = read[0];
int count = 1; // We have counted one character for now
// Go through each character (note start from 1 instead of 0)
for(int i = 1; i < read.size(); i++) {
// Get the next char
char newChar = read[i];
// If it is different, print the current count and reset the counter
if (lastChar != newChar) {
cout << lastChar << count;
count = 1;
lastChar = newChar;
} else { // Else increase the counter
count++;
}
}
// Print the last one
cout << lastChar << count;
return 0;
So I am trying to create this program to check the sort of a list of words to see whether they are in ascending, or descending order. I am copying the words from a file to an array of strings. I am told the regular comparison operators function the same with strings as they do with ints. However, when I run the program, it always outputs that the list is unordered (even when it is). I would greatly appreciate any help one could offer me. Thank you!
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int checkArraySort(int array_max, string arr[]);
int main(void)
{
const int array_max = 20;
string arr[array_max];
int d;
ifstream myfile_in;
myfile_in.open ("words_in.txt");
string line;
for(int i = 0; i < array_max; i++)
{
getline(myfile_in, line);
}
d = checkArraySort(array_max, arr);
if(d == -1)
{
cout << "The array is sorted in descending order!" << endl;
}
if(d == 0)
{
cout << "The array is not sorted!" << endl;
}
if(d == 1)
{
cout << "The array is sorted in ascending order!" << endl;
}
myfile_in.close();
return 0;
}
int checkArraySort(int array_max, string arr[])
{
bool y = false;
int j = 0;
for(int i = 0; i < array_max; i++)
{
if(arr[i] < arr[i-1])
{
j++;
}
if(j == (array_max))
{
y = true;
return -1;
}
}
j = 0;
for(int i = 0; i < array_max; i++)
{
if(arr[i] > arr[i-1])
{
j++;
}
if(j == (array_max))
{
y = true;
return 1;
}
}
if(y = false)
{
return 0;
}
}
if(y = false)
should be
if(y == false)
I'm trying to solve an algorithm for extracting a subsequence from an array. It should display the longest subsequence of prime numbers. I have written the whole algorithm but I still get an infinite cycle and I can't figure out where and why. I'm incrementing both indices and modifying the first index at the end, but it is still not working. Thanks a lot !!!
P.S: citire reads the array, prim detects if a number is prime or composed, afisare displays the subsequence and detSecv determines the longest subsequence.
#include <iostream>
#include <math.h>
using namespace std;
void citireSecv(int &n,int x[50])
{
cout<<"Da n: ";
cin>>n;
for(int i=1;i<=n;i++)
{
cout<<"Da un nr: ";
cin>>x[i];
}
}
int prim(int n)
{
int d=2;
while(d<=sqrt(n) && n%d!=0)
{
if(d==2)
d=3;
else
d=d+2;
}
if(d>sqrt(n)) return 1;
else return 0;
}
void afisare(int n,int x[50],int st,int f)
{
for(int i=st;i<=f;i++)
cout<<x[i]<<" ";
}
void detSecv(int n,int x[100],int &st,int &f)
{
st=1; f=0;
int i=1,j;
while(i<=n-1)
{
while(i<=n-1)
{
if(prim(x[i])==0 && prim(x[i+1])==0) i++;
}
j=i+1;
while(j<=n-1)
if(prim(x[j])==0 && prim(x[j+1])==0) j++;
if((j-i) > (f-st))
{
st=i;
f=j;
}
i=j+1;
}
}
int main()
{
int n,x[100],st,f;
citireSecv(n,x);
detSecv(n,x,st,f);
afisare(n,x,st,f);
return 0;
}
Input data:
n=2
First number is: 5
Second number is: 7
Probably just one of many issues with that code:
while(i<=n-1)
{
if(prim(x[i])==0 && prim(x[i+1])==0) i++;
}
j=i+1;
while(j<=n-1)
if(prim(x[j])==0 && prim(x[j+1])==0) j++;
There are two potential infinite loops here. If the conditions in the while don't return true on the first iteration, i (or j) will never get incremented, and you will have your infinite loop. You should almost always increment such variables outside of any conditions.
With a slight change in your code, you make it work, and one thing, you don't need to start array with index 1. you can always start with index zero.
for(int i=1;i<=n;i++)
{
cout<<"Da un nr: ";
cin>>x[i];
}
try to check for a case when no prime subsequence is found, while printing.
void detSecv(int n, int *x, int &start, int &end)
{
start = -1;
end = -1;
int i=0,j;
while(i < n) {
if(prim(x[i])) {
j = i + 1;
while(j < n)
if(prim(x[j])) j++;
else break;
} else {
i++;
continue;
}
if((j-i) > (end - start)) {
start = i;
end = j-1;
}
i=j+1;
}
}
This is a better way to verify if a number is prime or not
bool IsPrime(int number) {
int primeStep = 2;
double stepLimit = sqrt(number);
while(primeStep <= stepLimit)
{
if(number % primeStep == 0)
return false;
primeStep += 1;
}
return true;
}
And nou you can apply that function for each number in your array, and if it's prime , you add it in a new array like this:
void detSecv(int numberOfItems,int *arrayOfNumbers)
{
int arrayOfPrimeNumbers[50] = {};
int index = 0;
for(int i = 0; i < numberOfItems; i++)
{
if(IsPrime(arrayOfNumbers[i])){
arrayOfPrimeNumbers[index] = arrayOfNumbers[i];
index += 1;
}
}
int secondIndex = 0;
while(arrayOfPrimeNumbers[secondIndex] != 0)
{
cout << arrayOfPrimeNumbers[secondIndex] << " ";
secondIndex += 1;
}
}
Sorry, I'm a brand new newbie to C++ and programming and I'm getting a heap corruption error. I think Im writing in unallocated memory but I can't seem to find where the error is... the program is soppuse to take user input values and rearrange them so that they would ascend. I'm also learning templates too.
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
template <typename T>
void sort(T arrayz[], int size, char ch)
{
T temporary;
int k, j;
if (ch = 'a')
{
for (k = 0; k < size; k++)
{
for (j = 0; j < size; j++)
{
temporary = arrayz[j];
arrayz[j] = arrayz[j + 1];
arrayz[j + 1] = temporary;
}
}
}
}
int main()
{
int choices, range, i;
int x;
char ch;
cout << ("Enter the amount of numbers you want =>");
cin >> x;
int *numbers = new int[x];
if (!numbers)
{
cout << "Memory Allocation error!";
cin.get();
exit(1);
}
for (int i = 0; i<x; i++)
{
cout << "Option number" << i + 1 << " =>";
cin >> numbers[i];
}
cout << "Do you want ascending or descending values (a/d) =>" ;
cin >> ch;
if (ch = 'a')
{
sort(numbers, x, ch);
}
else if (ch = 'd')
{
sort(numbers, x, ch);
}
delete[] numbers;
fflush(stdin);
cin.get();
return 0;
}
In your sort function, you are accessing elements at index j + 1. However, this is out of bounds. The valid indexes for your arrayz array are 0 through size-1. When j is size-1, j+1 is size, which accesses past the end of the array.
I'm doing an online challenge and came across one problem! I have worked out the logic on paper, but it seems my problem doesn't work. All it does is return 0 as output.
My code so far:
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int nums[50];
string res[50];
int o = 0;
for(int i=0;i<n;i++)
{
cin >> nums[i];
}
for(int i=0;i<n;i++)
{
int deliteli=1;
for(int j=1;j<=nums[i];j++)
{
if(nums[i]%j==0)
{
deliteli++;
}
}
if(deliteli == 2){
res[0] = "YES";
o++;
}
else if(deliteli != 2){
res[0] = "NO";
o++;
}
}
for(int i=0;i<o;i++)
{
cout << res[i] << endl;
}
return 0;
}
What I am doing is firstly input N number, which means how long the array is going to be and then check for each number in the array whether it's prime or not. Any ideas what am I doing wrong?
deliteli should start at 0.
deliteli should be reset at the beginning of the loop.
You use res[i] instead of res[0], otherwise you keep overwriting the first element.
j%nums[i] should be nums[i]%j, because a%b returns the remainder from dividing a by b.
' is for single characters only (C++ is perfectly happy allowing things that shouldn't be allowed to compile and run). " is for strings.
Final code:
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int nums[50];
string res[50];
int o = 0;
for(int i=0;i<n;i++)
{
cin >> nums[i];
}
for(int i=0;i<n;i++)
{
int deliteli=0;
for(int j=1;j<=nums[i];j++)
{
if(nums[i]%j==0)
{
deliteli++;
}
}
if(deliteli == 2){
res[i] = "YES";
o++;
}
else if(deliteli != 2){
res[i] = "NO";
o++;
}
}
for(int i=0;i<o;i++)
{
cout << res[i] << endl;
}
return 0;
}
Test.
for(int j=1;j>=nums[i];j++)
{
...
}
It seems like you have the loop condition wrong. It should be:
for(int j=1;j<=nums[i];j++) //Change here
{
...
}
To check if nums[i] can be divided by j you are doing j%nums[i]==0, but that needs to be nums[i]%j==0.
Your deliteli counter also has a problem.
You need to reinitialize it for each number, otherwise it will just add to it.
Also you are always setting res[0], but you would want to set res[i].
first: to check if nums[i] can be divided by j you are doing j%nums[i]==0, but that needs to be nums[i]%j==0.
second:
change for(int j=1;j>=nums[i];j++)
to for(int j=1;j<=nums[i];j++)
and last: you don't have to test number nums[i] up to nums[i] but just to square root of this so change it to sqrt(nums[i])+1. It might be slight improvement to the speed of your algorithm.