I was playing around with array and when i did this , im expecting IndexOutOfBound
however , the program still ran and gave an output 54
Where does the extra number come from ?
How to avoid these kind of indexing problem?
#include <iostream>
int main(){
int array[] = {1,2,3,4,5,6};
int total;
for(int i = 0 ; i<=7 ; i++){
total += array[i];
}
std::cout << total;
return 0;
}
C++ does not do any checking to make sure that your indices are valid for the length of your array.
Like churill notes above, indexing out of range is undefined behavior. For example, in your question, the value of array[6] is whatever is stored your memory at the location where the 6th element would have existed. In your case, this was a random value for instance from another variable.
Although rare, C++ will also let you use a negative index, with similarly undesirable results.
Related
In the code, if we use an integer n to store strlen(str), the output by for loop becomes different than used here! Why is that happening?
void helper(char str[], int start){
int n=strlen(str)
if(str[start]=='\0'||str[start]=='\0')
return;
helper(str,start+1);
if(str[start]=='p' && str[start+1]=='i'){
for(int i=n;i>=start+2;i--){
str[i+2]=str[i];
}
str[start]='3';
str[start+1]='.';
str[start+2]='1';
str[start+3]='4';
}
}
In order to complete your question, you should include your expected output and the one you got. Or the difference that you observe.
Anyway, it seems that your code contains undefined behaviour / out of bond array access.
for(int i=n;i>=start+2;i--){
str[i+2]=str[i];
}
If n is the size of the string, then at the first loop iteration, i+2 is greater than the string size.
Please complete your question to get more details.
Can someone help me with the code in c++ below?
#include <iostream>
#include <fstream>
using namespace std;
int PARENT(int i)
{
return (i/2);
}
int Heapify_up(int arra[], int i)
{
int j,k;
if (i>1){
j = PARENT(i);
if (arra[i]<arra[j]){
k=arra[i];
arra[i]=arra[j];
arra[j]=k;
Heapify_up(arra, j);
}
}
return j;
}
int main()
{
int array3[15];
int i,p,array_length;
ifstream inputFile1("Heapfile.txt");
if (inputFile1.good()){
int current_number = 0;
i=1;
while (inputFile1>> current_number)
array3[i++] = current_number;
inputFile1.close();
}
array_length = i;
cout<<"Please, enter an integer: ";
cin>>p;
array3[array_length+1]=p;
int pos=Heapify_up(array3, array_length+1);
for (i=1; i<15; i++){
cout<<array3[i]<<" ";
}
cout<<"The position is "<<pos;
}
Let me explain you that have an array in a txt file. After i insert a random integer and with the heapify-up algorith I'm sorting this random number to the array. I want to print the new sorted array(I' have done that) and the new position of the random element that i have entered. Any idea?
thanks in advance!
P.S. I am new here and i find it somehow difficult to post my code correctly... still learning! XD
Okay, there are multiple problems with your code.
You make no effort to ensure you don't blow past the size of your
static array.
You skip a spot in the array when appending your manually-added
value
Your array length is wrong
You aren't initializing your variables
Let's start with the last one. Please do something like this:
int i{0}, p, array_length;
This ensures the i variable is properly initialized to zero.
Next, your code does this:
array3[i++] = current_number;
This means that at any given time, i is the length of the array.
But later you do this:
array_length = i;
array3[array_length+1]=p;
Frankly, I would drop variable i entirely and use array_length instead. There is no need for both.
But even without that, you're setting array_length correctly, but then you're inserting to a point AFTER that, so you might start with:
[ 1, 2, 3, 4, 5 ]
At this point, i == 5. Input a 6 and have:
[ 1, 2, 3, 4, 5, 0, 6 ]
Because you put it at index i+1 not at index i.
At this point, array_length is no longer an accurate length. But you do this:
int pos=Heapify_up(array3, array_length+1);
So it kind of works.
I don't know why Heapify_up is returning j -- it's just the midpoint of the array. That's not a useful value.
Furthermore, I don't really know what your heapify thing is trying to accomplish.. It certainly isn't a heap-sort. If the middle and end numbers are in sorted order, it doesn't actually do a thing.
This URL might help you with some code:
Heap sort at Geeks for Geeks
As for using a fix-length array -- that's problematic, too, but using std::vector is probably a bit much for you. I'd make sure that your input loop doesn't run into issues or start with a much longer beginning array.
I am supposed to make a function that accepts an integer array as an input, and then randomly modify each value within the array by either -38 or 55, specifically. However, I'm not sure how to randomly choose whether a number will get deducted by -38 or added by 55, and how to go about this process.
I tried making an if statement within my function, stating that if a function is even (array[i] % 2), then deduct by -38, and if the number is odd (else statement), add by 55. While this may work, it's not the right way to answer this question, because what if I wanted to add an even number by 55? Or vice versa with an odd number with subtracting 38?
#include <iostream>
using namespace std;
#include <time.h>
#include <cstdlib>
int output(int array[]){
for(int i = 0; i<5; i++){
cout << array[i] << " ";
}
}
int offset(int array[]){
for (int j = 0; j < 5; j++) {
int myrand = rand();
if (myrand % 2 == 0){
array[j] = array[j] - 38;
}
else{
array[j] = array[j] + 55;
}
}
}
int main()
{
srand(time(NULL));
int array[5] = {1, 2, 3, 4, 5};
cout << "Original: ";
output(array);
offset(array);
return 0;
}
If the value within an array is 5, it should have the possibility of being 10 or 0, and so forth with any numbers.
Let's get you started and then you can go from there. When beginning to learn any programming language, (or any language for that matter), you start with a large amount of what makes up the language, what are the words and what are the rules for putting them together. For a programming language that is its "syntax". Every language has its own. You begin learning the syntax with minimal examples that make use of the basic types and progress from there.
With a compiled language, you add to that, how you translate the collection of proper syntax in a file into a machine readable executable. How you compile the source code into an executable.
At this point, the most important thing you can do is make friends with your compiler and listen to what it is telling you. You do this most effectively by enabling compiler warnings so your compiler will point out for you the line (and in many cases the character in the line) that it finds troubling. The rule is
"Always compile with warnings enabled, and do not accept code
until it compiles cleanly without warning."
To enable warnings add -Wall -Wextra -pedantic to your gcc/clang compile string. For VS (cl.exe on windows), use /W3. There are always additional warnings you can add, but this will provide a thorough set that if you follow the rule will save you hours of time debugging.
With that as background, let's look at what you are trying to do. First, you have tagged your Question as C++. I provided you in the comment above a place to start to determine what basic header files were needed in your proposed code. C++ Standard Library headers. Checking you will find that C++ provides an implementation of time.h as the header ctime (all of the standard C headers are generally named c......). So here, based on what you included in your code, you would need, at minimum,
#include <iostream>
#include <cstdlib>
#include <ctime>
While you can use 5 in your code, you want to avoid hard-coding numbers (unless required by the standard library function being used, such as the C scanf field-width modifier, which does not allow a named constant or variable in that case). Hard-coding numbers is called using magic-numbers and is best avoided.
When you declare and initialize an array, you can declared the array with an empty [] (which would normally be an incomplete type), but by virtue of providing a braced-initializer, the compiler uses the number of elements provided to size the array at compile time. You can then determine the number of elements with the array by dividing the sizeof array by the sizeof (an_element). You can simply derefernce the array to obtain the first element, so you will see it written as follows:
int main (void) {
int array[] = {1, 2, 3, 4, 5};
int nelem = sizeof array / sizeof *array; /* number of elements */
...
Now when passing basic-type arrays to a function, you also need to pass the number of elements as well. Why? When an array is passed as a parameter (actually on any access, subject to limited exceptions), an array is converted to a pointer to the first element. If you tried to use the sizeof array / sizeof (an_element) within a function after passing the array as a parameter, you would end up with sizeof (a_pointer) / sizeof (an_element) which is certainly not going to work.
So for example, in your output() function, to pass the number of elements along with the array, you would need:
void output (int array[], int nelem)
{
for (int i = 0; i < nelem; i++) {
cout << array[i] << " ";
}
cout << '\n';
}
The same would apply equally to your offset() function:
void offset (int array[], int nelem)
{
for (int j = 0; j < nelem; j++) {
int myrand = rand();
if (myrand % 2 == 0) {
array[j] = array[j] - 38;
}
else{
array[j] = array[j] + 55;
}
}
}
(note: the return type for each function has been changed to void rather than int. Neither function need provide an indication of success/failure and neither is returning a value that is being used back in the calling function, main() here. In each case you are simply printing the elements of the array, or updating their values in-place.)
The remainder for your first attempt is simply to output the array before applying the offset, and then again afterwards. Your main() could be:
int main (void) {
int array[] = {1, 2, 3, 4, 5};
int nelem = sizeof array / sizeof *array; /* number of elements */
srand (time(NULL)); /* seed random number generator */
cout << "Original: "; /* output original array */
output (array, nelem);
offset (array, nelem); /* apply offset to array */
cout << "Updated : "; /* output original array */
output (array, nelem);
return 0;
}
If you put all the pieces together, and compile with warnings enabled, will find your code compiles without warning and produces a working executable.
Example Use/Output
$ ./bin/randaddtoarray
Original: 1 2 3 4 5
Updated : 56 57 58 -34 -33
If you run it multiple times you will probably see that you don't always have an even number of odd or even random numbers. That is the nature of random numbers.
As mentioned in the comments, there are many many ways to approach developing a random scheme for applying your -38 or +55. Take some time and research the different methods and try implementing them and see how your results change. You will probably want to add more than 5 values to your array to be able to draw any kind of distribution conclusion. Five values is really not enough to provide any type of clear comparison.
Let me know if you have further problem.
as the title explains this is a program to find lcm of numbers between 1 to 20. i found an algorithm to do this, here's the link
http://www.cut-the-knot.org/Curriculum/Arithmetic/LCM.shtml
there is a java applet on the webpage that might explain the algorithm better
Problem: i wrote the code compiler shows no error but when i run the code the program goes berserk, i guess may be some infinite loopig but i can't figure it out for the life of me. i use turbo c++ 4.5 so basically if anyone can look at the code and help me out it would be great . thanks in advance
Algorithm:
say we need to find lcm of 2,6,8
first we find the least of the series and add to it the number above it, i.e the series become
4,6,8
now we find the least value again and add to it the intitial value in the column i.e 2
6,6,8
so the next iteration becomes
8,6,8
8,12,8
10,12,8
10,12,16
12,12,16
14,12,16
14,18,16
16,18,16
18,18,16
18,18,24
20,18,24
20,24,24
22,24,24
24,24,24
as you can see at one point all numbers become equal which is our lcm
#include<iostream.h>
/*function to check if all the elements of an array are equal*/
int equl(int a[20], int n)
{
int i=0;
while(n==1&&i<20)
{
if (a[i]==a[i+1])
n=1;
else
n=0;
i++;
}
return n;
}
/*function to calculate lcm and return that value to main function*/
int lcm()
{
int i,k,j,check=1,a[20],b[20];
/*loading both arrays with numbers from 1 to 20*/
for(i=0;i<20;i++)
{
a[i]=i+1;
b[i]=i+1;
}
check= equl(a,1);
/*actual implementation of the algorith*/
while(check==0)
{
k=a[0]; /*looks for the least value in the array*/
for(i=0;i<20;i++)
{
if(a[i+1]<k)
{
k=a[i+1]; /*find the least value*/
j=i+1; /*mark the position in array */
}
else
continue;
}
a[j]=k+b[j]; /*adding the least value with its corresponding number*/
check= equl(a,1);
}
return (a[0]);
/*at this point all numbers in the array must be same thus any value gives us the lcm*/
}
void main()
{
int l;
l=lcm();
cout<<l;
}
In this line:
a[j]=k+b[j];
You use j but it is unitialized so it's some huge value and you are outside of the array bounds and thus you get a segmentation fault.
You also have some weird things going on in your code. void main() and you use cout without either saying std::cout or using namespace std; or something similar. An odd practice.
Also don't you think you should pass the arrays as arguments if you're going to make lcm() a function? That is int lcm(int a[], int b[]);.
You might look into using a debugger also and improving your coding practices. I found this error within 30 seconds of pasting your code into the compiler with the help of the debugger.
Your loop condition is:
while(n==1&&i<20)
So your equl function will never return 1 because if n happens to be 1 then the loop will just keep going and never return a 1.
However, your program still does not appear to return the correct result. You can split the piece of your code that finds the minimum element and replace it with this for cleanliness:
int least(int a[], int size){
int minPos = 0;
for(int i=0; i<size ;i++){
if (a[i] < a[minPos] ){
minPos = i;
}
}
return minPos;
}
Then you can call it by saying j = least(a, 20);. I will leave further work on your program to you. Consider calling your variables something meaningful instead of i,j,k,a,b.
Your equl function is using array indices from 0-20, but the arrays only have 1-19
j in lcm() is uninitialized if the first element is the smallest. It should be set to 0 at the top of the while loop
In the following code, when i=19, you are accessing a[20], which is out of the bounds of the array. Should be for(i=0;i<19;i++)
for(i=0;i<20;i++) {
if(a[i+1]<k)
You are not actually using the std namespace for the cout. this should be std::cout<<l
Your are including iostream.h. The standard is iostream without the .h, this may not work on such an old compiler tho
instead of hard-coding 20 everywhere, you should use a #define. This is not an error, just a style thing.
The following code does nothing. This is the default behavior
else
continue;
I have written some code, here is a snippet of it is:
int num[8],n=0;
for (n = 0; n<8; n++)
{
char temp = binnum[n];
num[n] = atoi(&temp);
cout << num[n];
}
It doesn't gives any error, but I do get a warning. When I run it on C++, it gives Run Time Check Failure - The variable n is being used without being initialized.
After that, it doesn't run any further and the program closes. Is there any way to ignore this error? Because if I initialize n, it gives the wrong answer. For example, if answer is 101011, it will give 10101100, which is wrong.
Initialize n as #anthares pointed out and increment it at the end of the loop so your loop actually works.
int number[8];
int n = 0;
do
{
char temp = binnum[n];
number[n] = atoi(&temp);
cout << number[n];
n++;
} while (n<8);
Your main problem (after all the edits) is that atoi takes a null-terminated char array (C-style string). The address of a single char variable does not make a C-style string.
To convert a single character in range ['0'...'9'] to a corresponding number use:
number[i] = temp - '0';
possibly having checked that temp contains a digit character.
Give a value to your vairable n before using it int number [8], n=0 for example. Otherwise, it is "not defined behavior" what is the value of n and how many iterations you will do in your cycle.
Also, As it is written your loop will go forever since you never change the value of n ...
You are using n before it is assigned a value. You need to ensure that n is initialized (to 0, maybe) before you begin to reference it in your code. You do not want to ignore this error.
Try something like this:
const int count = 8;
int number[count];
for (int i=0; i < count; i++)
{
char temp = binnum[i];
number[i] = atoi(&temp);
cout << number[i];
}
what? you never assign any value to n.
and even if you will for example do int number[8],n=0; you never change n's value you you will end up with an infinite loop.
You should really initialize n (and also increment it, for that matter).
You are probably running a debug build of your application. In this case, the variable is probably always initialized with the same value. This is why you see the result you expect. It seems to behave correct purely by accident.
As soon as your application is built in release mode, n may have a different value each time the program is run and thus the output will be unpredictable.
This is what happens when you have undefined behavior in your program.