how print an array row with pointers - c++

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
ifstream fin("C:\\Users\\rati\\Desktop\\iris_flower.txt");
float s=0;
int x,n=5,m=150,i,j;float d[5]={0};
float **iris;
float ss=n;
iris=new float *[n];
for(i=0;i<n;i++)
iris[i]=new float [m];
for(i=0;i<n;i++)
for(j=0;j<m;j++)
fin>> iris[i][j];
for(i=0;i<n;i++){
for(j=0;j<m;j++)
cout<<iris[i][j]<<" ";
cout<<endl;
}
for(j=0;j<m;j++){
for(i=0;i<n;i++)
s+=iris[i][j];
d[j]+=s/ss;
cout<<s<<endl;
}
system ("pause");
}
this is my full code. I want to print a row from 2d array with pointer(no loops).I hope you can write a fragment to add that it did what I want

You can modify the array with pointers but if you want to print the array, you have to use loops.
Check out this example:-
int main() {
int n = 3, m = 4, a[n][m], i, j, (* p)[m] = a;
for (i = 0; i < n; i++)
for (j = 0; j < m; j++)
a[i][j] = 1;
p++;
(*p)[2] = 9;
return 0;}
Here
p is a pointer to a 4-element int arrays (i.e. a pointer to pointer to int, where the first dimension is 4 and the second is unknown). When you increment p, it points to the next 4-element int array, i.e. the fifth int altogether. Then p is dereferenced with offset 2, which means that the seventh int changes, so you get
1 1 1 1
1 1 9 1
1 1 1 1
For converting integer array pointed by p to string, try this :-
string int_array_to_string(int *p, int size_of_array){
string returnstring = "";
for (int temp = 0; temp < size_of_array; temp++)
returnstring += itoa((* p)[temp]);
return returnstring;
}
You get the row array from here.

With array of ints it wont be so easy like array of chars.
int n=10, m=10;
int width, height;
char **tab = new char*[n];
for (int x = 0; x < n; x++) {
tab[x] = new char[m];
}
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
tab[i][j] = rand()%10 + '0';
for (int i=0; i<n; i++) { for(int j=0; j<n; j++) cout << tab[i][j]; cout << endl; }
cout << endl;
cout << tab[5];
ideone
/// edit ///
if u cant use loop and recursion u can do this
const int n=3;
float *k =new float [n];
k[0]=6.123;
k[1]=9.5345;
k[2]=1.32423;
int i=0;
label:
if(i<n){
cout << *(k+i) << " ";
i++;
goto label;
}

Related

C++ replacing values in a dynamic 2D Array

I'm trying to replace the '.' in my array with 'O'but it inserts it in between rather than taking its place. Please help I don't know what I'm doing wrong.
#include <iostream>
using namespace std;
char** createField(int w, int l)
{
int obstacles;
char ** arr = new char * [w];
for(int i=0; i<w; i++)
{
arr[i] = new char[l];
}
//Initializing the values
for(int i = 0; i < w; ++i)
{
for(int j = 0; j < l; ++j)
{
arr[i][j] = 0;
}
}
cout<<"Enter number of obstacles: ";
cin>>obstacles;
int x=0;
int y=0;
for (int j = 0; j < obstacles; ++j) {
cout<<"Enter location of obstacles: ";
cin>>x>>y;
arr[x][y] ='O';
}
for(int i = 0; i < w; ++i)
{
for(int j = 0; j < l; ++j)
{
if(i==0 || i == w-1){
cout<< arr[i][j]<< 'W';
}else if(j==0 || j==l-1){
cout<< arr[i][j]<< 'W';
} else
cout<< arr[i][j]<< '.';
}
cout<<"\n";
}
return arr;
}
int main() {
int w;
int l;
cout << "Enter the Width: ";
cin >> w;
cout << "Enter the length: ";
cin >> l;
//Pointer returned is stores in p
char **p = createField(w, l);
//Do not Forget to delete the memory allocated.It can cause a memory leak.
for (int del = 0; del < w; del++) {
delete[] p[del];
}
delete[]p;
}
Here is an example of my output, I want the 'O' to replace the '.' rather than be in between the two. Also if someone could explain why this is happening that would be really helpful Thanks.
Example of output: w.O.w
Desired output: w.Ow
When you set arr[i][j] = 0, it will cast 0 into char before assigning it to arr[i][j]. 0 casts to the literal '\0' which means a null character. Later when you print the contents of arr, the null characters cannot be seen in output which is part of the underlying cause of your confusion. Hope that explains what's going on a little bit better.

How to correctly use pointers in code

For the following code, how can I find [A^-1] using pointers(equation for [A^-1]= 1/ det (A)? I am not sure whether pointers are used in the arithmetic or if they are used to call a value. Explaining what a pointer would be nice as I'm not exactly sure what they even do. I have most of the code written, except for this one part, so any help is much appreciated. Thanks in advance.
#include <iostream>
#include <cmath>
#include <string>
#include <fstream>
#include <ctime>
#include <cstdlib>
#include <bits/stdc++.h>
#define N 3
using namespace std;
template<class T>
void display(T A[N][N])
{
for (int i=0; i<N; i++)
{
for (int j=0; j<N; j++)
cout << A[i][j] << "\t\t";
cout << endl;
}
}
template<class T>
void display(T A[N])
{
for (int i=0; i<N; i++)
{
cout << A[i]<< "\n";
}
}
void getCofactor(int A[N][N], int temp[N][N], int p, int q, int n)
{
int i = 0, j = 0;
for (int row = 0; row < n; row++)
{
for (int col = 0; col < n; col++)
{
if (row != p && col != q)
{
temp[i][j++] = A[row][col];
if (j == n - 1)
{
j = 0;
i++;
}
}
}
}
}
int determinant(int A[N][N], int n)
{
int D = 0;
if (n == 1)
return A[0][0];
int temp[N][N];
int sign = 1;
for (int f = 0; f < n; f++)
{
getCofactor(A, temp, 0, f, n);
D += sign * A[0][f] * determinant(temp, n - 1);
sign = -sign;
}
return D;
}
void adjoint(int A[N][N],int adj[N][N])
{
if (N == 1)
{
adj[0][0] = 1;
return;
}
int sign = 1, temp[N][N];
for (int i=0; i<N; i++)
{
for (int j=0; j<N; j++)
{
getCofactor(A, temp, i, j, N);
sign = ((i+j)%2==0)? 1: -1;
adj[j][i] = (sign)*(determinant(temp, N-1));
}
}
}
bool inverse(int A[N][N]){
int det = determinant(A, N);
if (det == 0){
cout << "Singular matrix, can't find its inverse";
return false;
}
return true;
}
void computeInverse(int A[N][N], float inverse[N][N]){
int det = determinant(A, N);
int adj[N][N];
adjoint(A, adj);
for (int i=0; i<N; i++)
for (int j=0; j<N; j++)
inverse[i][j] = adj[i][j]/float(det);
cout<<"\nThe Inverse of the Matrix A is:"<<endl;
display(inverse);
}
int main()
{
system("cls");
int A[N][N] = {{-1, 4, -2}, {-3, -2, +1}, {+2, -5, +3}};
char X[N];
int B[N];
float inv[N][N];
cout<<"\nEnter a 3*3 Matrix A"<<endl;
for(int i=0;i<N;i++){
for(int j=0;j<N;j++){
cin>>A[i][j];
}
}
cout<<"\nEnter variables x, y, z for Matrix X"<<endl;
for(int i=0;i<N;i++){
cin>>X[i];
}
if (X[0] == 'x' && X[1] == 'y' && X[2] == 'z')
cout<<"\nMatrix X is Valid"<<endl;
else{
cout<<"\nMatrix X is Invalid"<<endl;
return -1;
}
cout<<"\nEnter values for Matrix B"<<endl;
for(int i=0; i<N; i++)
cin>>B[i];
cout<<"\nMatrix A is:------->\n";
display(A);
cout<<"\nMatrix X is:------->\n";
display(X);
cout<<"\nMatrix B is:------->\n";
display(B);
bool isInverseExist = inverse(A);
if (isInverseExist)
computeInverse(A, inv);
return 0;
}
Okay, Here is a simple pointer example using a char array. This can work with other data types as well. Don't remember where I read it; Think of a pointer as an empty bottle.
lets break this down in English first then I'll share a simple example that can be compiled. Imagine that you have 10 m&m's sitting in front of you on a table.
These m&m's represent a character array that we will call char mm[10]; Assume that this array is filled with chars that represent the color of all 10 of the m&m's
Now, we don't want to leave our candy's on the table all day so we will store all ten of the m&m's in a special jar specifically made for the m&m's. this jar will be called char* mm_ptr;
So now we are left with a table of m&m's and a jar sitting next to the pile. The next step is to fill the jar with the m&m's and you do it like this: mm_ptr = mm;
You now have a "jar full of m&m's". This allows you to access the m&m's directly from the jar!
Here is a Working example of of putting m&m's into a jar:
#include <iostream>
//using namespace std;
int main(){//The main function is our table
char mm[10]; //Our pile of m&m's
for(int i=0; i<10; i++){
if(i < 5){
mm[i] = 'b'; //Lets say that half of the m&m's are blue
}else{
mm[i] = 'r'; //and that the other half is red
}
}
char* mm_ptr; //This is our bottle that we will
//use to store our m&m's
mm_ptr = mm; //this is us storing the m&m's in the jar!
for(int i=0; i<10; i++){//Lets dump those candies back onto the table!
std::cout<<mm_ptr[i]<<std::endl;
}
return 0;
}
A correctly initialized pointer will work almost exactly like a normal array

C++ Bubble Sort Using Swap Function and Pointers

I'm having problems figuring out where my bubble sort code went wrong. I'm almost positive it's in the sorting algorithm. Here is what I need my code to accomplish:
-Initialize an array a fill it with random numbers (I use getNumbers() to accomplish this)
-Compare the first element with all later elements. If the first element is larger, swap them.
-Compare the second element with all later elements one by one. If the second element is larger, swap them.
-Continue comparing and swap operations until the second to last element.
-Print out the sorted array
And here's my code:
#include <iostream>
#include <cstdlib>
using namespace std;
void swap(int *, int *);
int *getNumbers(int);
int main()
{
//Get the size of the array from keyboard
int arraySize;
cout << "How many integers would you like to declare: ";
cin >> arraySize;
//Initialize array
int *array;
array = getNumbers(arraySize); //getNumbers should return a pointer
//Print out original array
cout << "Original array" << endl;
for(int count = 0; count < arraySize; count++)
{
cout << *(array + count) << " ";
}
//Sort array using the swap function
//Have a for loop to swap numbers one by one from min to max
//Compare values using a second for loop
//Swap values if former value is larger
//swap(&array[i],&array[j]);
for(int i = 0; i < arraySize; i++)
{
for(int j = 0; j < (arraySize - 1); j++)
{
if(array[j] > array[j + 1])
{
swap(&array[i], &array[j]);
}
}
}
//Print out sorted array
cout << "\nSorted Array" << endl;
for(int count = 0; count < arraySize; count++)
{
cout << *(array + count) << " ";
}
return 0;
}
void swap(int *num1, int *num2)
{
//Keep record of original value of num1
int tempNum;
tempNum = *num1;
*num1 = *num2; //num1 value has been changed
*num2 = tempNum; //Fetch the original value of num1 and assign it to num2
}
int *getNumbers(int size)
{
int *array;
array = new int[size];
srand(time(0));
for(int i = 0; i < size; i++)
{
array[i] = rand() % 100;
}
return array;
}
Here is the correct code.
#include <iostream>
#include <cstdlib>
using namespace std;
void swap(int *, int *);
int *getNumbers(int);
int main() {
//Get the size of the array from keyboard
int arraySize;
cout << "How many integers would you like to declare: ";
cin >> arraySize;
//Initialize array
int *array;
array = getNumbers(arraySize); //getNumbers should return a pointer
//Print out original array
cout << "Original array" << endl;
for (int count = 0; count < arraySize; count++) {
cout << *(array + count) << " ";
}
//Sort array using the swap function
//Have a for loop to swap numbers one by one from min to max
//Compare values using a second for loop
//Swap values if former value is larger
//swap(&array[i],&array[j]);
for (int i = 0; i < arraySize; i++) {
for (int j = 0; j < (arraySize - 1); j++) {
if (array[j] > array[j + 1]) {
/*********** This line was changed ***********/
swap(&array[j+1], &array[j]); // You were earlier swapping ith and jth entries.
/*********************************************/
}
}
}
//Print out sorted array
cout << "\nSorted Array" << endl;
for (int count = 0; count < arraySize; count++) {
cout << *(array + count) << " ";
}
return 0;
}
void swap(int *num1, int *num2) {
//Keep record of original value of num1
int tempNum;
tempNum = *num1;
*num1 = *num2; //num1 value has been changed
*num2 = tempNum; //Fetch the original value of num1 and assign it to num2
}
int *getNumbers(int size) {
int *array;
array = new int[size];
srand(time(0));
for (int i = 0; i < size; i++) {
array[i] = rand() % 100;
}
return array;
}
You were swapping array[i] with array[j] in line 32. array[j] and array[j+1] should be swapped. Also, as pointed out by dd2, your loop bounds are not strict. The code would work correctly nonetheless but would take more steps. You can change the bound to j < (arraySize - i - 1)
Your loop bounds are not correct and swapping was wrong as well.
for(int i = 0; i < arraySize; i++)
{
for(int j = 0; j < (arraySize - i - 1); j++)
{
if(array[j] > array[j + 1])
{
swap(&array[j], &array[j+1]);
}
}
}

how to get the difference of two points in a 2D array

#include <iostream>
using namespace std;
int main (int argc, char ** argv)
{
int c;
int distance=0;
int largestdistance=0;
int sum=0;
cin >> c;
int point[c][2];
for (int i=0; i<c; i++){
for (int j=0; j<2; j++){
cin >> point[i][j];
}
}
cout << point[2][0] << " ";
for (int i=0; i<c; i++){
for (int j=0; j<2; j++){
sum += abs(point[0][0]-point[1][0])+abs(point[0][1]-point[1][1]);
}
if (sum > largestdistance){
largestdistance=sum;
}
cout << '\n';
return 0;
}
}
This program prints out the value of the absolute value of the first row first number minus the second row first number added to the absolute value of the first row second number minus the second row second number. I was wondering that how do I make the program so that it automatically does the sum += abs(point[0][0]-point[1][0])+abs(point[0][1]-point[1][1]) for all point[][] all the way up to sum += abs(point[c-1][0]-point[c][0])+abs(point[c-1][1]-point[c][1]).
This would be a lot clearer if you introduced a point type:
struct Point {
int x, y;
};
int manhattan_dist(const Point& p, const Point& q) {
return abs(p.x - q.x) + abs(p.y - q.y);
}
Armed with that, it's a lot easier to loop:
int sum = 0;
for (int i = 0; i < c - 1; ++i) { // stop before c-1, so i and i+1 are valid
sum += manhattan_dist(points[i], points[i+1]);
}
Btw int point[c][2]; is non-standard code because c is not a compile-time constant. You need to dynamically allocate the array:
Point* points = new Point[c];
or, preferably:
std::vector<Point> points(c);

For loops and addition

So I'm trying to use a for loop to fill the array with the numbers 1-8. Then add:
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + numb = x
And then save it to an variable called x. I've done filling the array, but I don't know how to calculate the summary of the array + the number you enter. Would appreciate some help a lot.
#include <iostream>
using namespace std;
int main()
{
int array[8];
int numb;
int x; // x = summary of array + numb;
cin >> numb; // insert an number
for (int i = 0; i <= 8; i++)
{
array[i]=i+1;
}
for (int i = 0; i < 8; i++)
{
cout << array[i] << " + ";
}
}
Change the last part to:
x = numb;
for (int i = 0; i < 8; i++)
{
x = x + array[i];
}
cout<<x<<endl;
Realistically though, if you wanted to add the first n whole numbers, there's a formula:
(n*(n+1))/2;
so your whole program would be:
#include <iostream>
using namespace std;
int main()
{
int n = 8;
int numb;
cin >> numb; // insert an number
int x = n*(n+1)/2+numb;
cout<<x<<endl;
}
For the initial loop, remove the =:
for (int i=0; i<8; i++) { array[i]=i+1; }
For adding all the elements of an array, then adding numb:
var x=0;
for (int i=0; i<8; i++) { x += array[i]; }
x+=numb;
Then you can cout you x variable.
Unless you're required to use for loops and arrays (e.g., this is homework), you might want to consider code more like:
std::vector<int> array(8);
// fill array:
std::iota(begin(array), end(array), 1);
int numb;
std::cin >> numb;
int total = std::accumulate(begin(array), end(array), numb);
std::cout << "Result: " << total;