Code inside loops wont print - c++

void Graph::sortW ()
{
int length = vertices*vertices;
int array[length];
for (int i = 0; i < length; i++)
{
array[i] = 0;
cout << array[i]; // nothing prints
}
cout << "i";
// convert to 1D array
for (int i = 0; i < vertices; i++) {
for (int j = 0; j < vertices; j++) {
array[i*vertices+j] = matrix[i][j];
cout << array[i*vertices+j] << " "; // nothing prints
}
}
cout << "j";
qsort(array, length, sizeof(int), compare);
// for (int i=0 ; i<25; i++)
// cout << array[i] << endl; // only loop that prints?!
}
I have no idea why the output is ij only. Sort is called in the constructor like so:
// Sort weights using qsort
sortW();
Anyone have any ideas?

I'd suggest you put a
cout << vertices;
at the beginning of your function. My guess ist that vertices is zero?

Related

Why is my insertion sort algorithm altering numbers in the given array? (C++)

I have a C++n insertion sort function template, and it works fine when I give the function an array of integers, but when I give the function an array of doubles, although the array is indeed sorted afterwards, for some reason it alters the numbers in the sorted array.
The code:
#include <iostream>
#include <stdlib.h>
using namespace std;
template <typename T>
void insertionSort(T ary[10], int size)
{
// Printing unsorted array
cout << "Array before sorting: [";
for (int i = 0; i < size; i++)
{
cout << ary[i] << ", ";
}
cout << "]" << endl;
// Beginning of sorting
int j, t;
for(int i = 1; i < size; i++)
{
for (int i = 0; i < size; i++)
{
j = i;
while(j > 0 && ary[j] < ary[j-1])
{
t = ary[j];
ary[j] = ary[j-1];
ary[j-1] = t;
j--;
}
}
}
// Printing sorted array
cout << "Array after sorting: [" ;
for (int i = 0; i < size; i++)
{
cout << ary[i] << ", ";
}
cout << "]\n" << endl;
}
int main()
{
cout << "*** INTEGER ARRAY INSERTION SORT ***" << endl;
int intAry[10] = {0};
for (int i = 0; i<= 9; i++)
{
intAry[i] = rand() % 100;
}
insertionSort(intAry, 10);
cout << "*** DOUBLE ARRAY INSERTION SORT ***" << endl;
double dAry[10] = {0};
for(int i = 0; i<=9; i++)
{
dAry[i] = (double)rand() / RAND_MAX * 100;
}
insertionSort(dAry, 10);
return 0;
}
The output:
You can see here that it changes the number in the array of doubles, like 14.1603 to 14.
Thank you for any help!
The problem is, you want to compare the double numbers, but when you're going through the loop, you use the int i and int j variables. Result is incorrect due to incompatible data type.
if you covert "double" the "int" data types, your problem will be solved.
Also you must change your array type to double.

Is there a way I can store address of a string to a 2D character array

I am trying to make a program where it asks the user the number of shelves and number of positions on those shelves from the user then it asks the user where he wants to enter a product.
Now I got rows and columns figured out but I can't get the full product name printed it just shows a single character of said product. Is there a way I can store an address of a string variable and store it in that column of my row to print the complete word?
This is what I have done so far.
#include<iostream>
#include<string>
using namespace std;
int main()
{
int M = 4;
int N = 4;
char *item;
char ie[20];
// dynamically create an array of pointers of size `M`
char** A = new char*[M];
// dynamically allocate memory of size `N` for each row
for (int i = 0; i < M; i++) {
A[i] = new char[N];
}
cout << "Row num" << endl;
int row = 0;
cin >> row;
cout << "Row col" << endl;
int col = 0;
cin >> col;
//string temp;
cout << "Item" << endl;
cin >> ie;
for (int j = 0; j < strlen(ie); j++)
{
A[row][col] = ie[j];
}
for (int i = 0; i < M; i++)
{
for (int j = 0; j < N; j++) {
cout << A[i][j] << " ";
}
cout << endl;
}
}
sorry If the question is not clear or easy to understand.
First recommendation: never do like this
for (int j = 0; j < strlen(ie); j++) { /* do something */ }
Do it like this instead:
for (int i = 0; ie[i] != '\0'; ++i) { /* do something */ }
or
int ie_len = strlen(ie);
for (int j = 0; j < ie_len; ++j) { /* do something */ }
because each loop condition check it calls strlen which takes length of string to calculate this function, so it takes square of string length in first case
I recommend use std::string and std::vector to store 2D array of strings, and avoid raw pointers and especially new operator (at least for code in question body you forgot delete for this new's). If you really want mess with raw pointers, see the end of this answer, but now recommended way to do what you want (as I understand what you want):
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main()
{
int M = 4;
int N = 4;
std::vector<std::vector<std::string>> A(M);
char ie[20];
for (int i = 0; i < M; i++) {
A[i] = std::vector<std::string>(N);
}
// can be used std::fill(A.begin(), A.end(), std::vector<std::string>(N)); instead for loop above but for loop simplier to understand
cout << "Row num" << endl;
int row = 0;
cin >> row;
cout << "Row col" << endl;
int col = 0;
cin >> col;
string temp;
cout << "Item" << endl;
cin >> temp;
A[row][col] = temp;
for (int i = 0; i < M; i++)
{
cout << std::string(N * (temp.size() + 3) + 1, '-') << "\n"; // add separator to be clear what happening
cout << "| "; // add separator to be clear what happening
for (int j = 0; j < N; j++) {
A[i][j].resize(temp.size(), ' '); // for all columns has equal width to be clear what happening
cout << A[i][j] << " | ";
}
cout << endl;
}
}
example of input and output of this code:
Row num
1
Row col
2
Item
bob
-------------------------
| | | | |
-------------------------
| | | bob | |
-------------------------
| | | | |
-------------------------
| | | | |
Messing about raw pointers (your code with some editions and useful comments):
#include<iostream>
#include<cstring> // cstring not string as #PaulMcKenzie mentioned in comments for strlen
using namespace std;
int main()
{
int M = 4;
int N = 4;
char *item;
char ie[20];
// dynamically create an array of pointers of size `M`
const char*** A = new const char**[M]; // need add one more star because two for two-dimensonal array and one more for ~string~(aka char array)
// dynamically allocate memory of size `N` for each row
for (int i = 0; i < M; i++) {
A[i] = new const char*[N];
}
const char empty_string[1] = "";
for (int i = 0; i < M; ++i){
for (int j = 0; j < N; ++j){
A[i][j] = empty_string; // make empty names on all shelves
}
}
cout << "Row num" << endl;
int row = 0;
cin >> row;
cout << "Row col" << endl;
int col = 0;
cin >> col;
//string temp;
cout << "Item" << endl;
cin >> ie;
/*not need this:
for (int j = 0; j < strlen(ie); j++)
{
A[row][col] = ie[j];
}
just save adress like this:*/
A[row][col] = ie;
int ie_len = strlen(ie);
/* can be done simply:
for (int i = 0; i < M; i++)
{
for (int j = 0; j < N; j++) {
cout << A[i][j] << " ";
}
cout << endl;
}
but it doesn't look like table*/
// add seprators for understanding what happenning
for (int i = 0; i < M; i++)
{
// add horizontal separator
for (int j = 0; j < N * (strlen(ie) + 3) + 1; ++j){
cout << "-";
}
cout << "\n";
cout << "| "; // add separator to be clear what happening
for (int j = 0; j < N; j++) {
cout << A[i][j];
// for equal width of columns add some spaces
for (int k = strlen(A[i][j]); k < ie_len; ++k){
cout << " ";
}
cout << " | ";
}
cout << endl;
}
// not forget to delete all what u newed
for (int i = 0; i < M; i++) {
delete A[i];
}
delete A;
}

How do I set all the diagonals in a matrix equal to zero?

I have a problem with my homework that asks me to have the compiler print out a matrix in which all the diagonals are outputted as zero. I also have to pass it to a function. However, I have no idea how to do this..
Here is my code:
#include <iostream>
using namespace std;
int diagonals();
int main()
{
//problem 1
int matrix[3][3];
for (int i = 1; i <= 3; i++)
{
for (int j = 1; j <= 3 ; j++)
{
cout << "Row " << i << " column " << j<< ": ";
cin >> matrix[i][j];
}
}
for (int i = 1; i <= 3; i++)
{
for (int j = 1; j <= 3; j++)
{
cout << matrix[i][j] << " ";
}
cout << endl;
}
cout << "\nReverse of the matrix:" << endl;
for (int j = 1; j <= 3; j++)
{
for (int i = 1; i <= 3; i++)
{
cout << matrix[i][j] << " ";
}
cout << endl;
}//end of problem 1
//problem 2
cout << "Diagonals changed to 0:\n" << endl;
}
your matrix declaration says int matrix[3][3]; that it has three 1-D array & in each 1-D array you can store three elements. And in C/C++ array index starts from zero.
Problematic statement is for (int i = 1; i <= 3; i++) as you are skipping matrix[0][0] and trying to store into matrix[3][3] which doesn't exist which in turn causes undefined behavior.
So firstly start iterating loop from 0 to number of rows & column respectively.
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3 ; j++) {
cout << "Row " << i << " column " << j<< ": ";
cin >> matrix[i][j];
}
}
Coming to task you mentioned, print out a matrix in which all the diagonals are outputted as zero. ? write one condition so that if row value & col value are equal then assign it to zero otherwise scan from user. Here is the sample code
int main(void) {
int matrix[3][3] = { 0 }; /* initialize it */
int row = sizeof(matrix)/sizeof(matrix[0]); /* find no of rows */
int col = sizeof(matrix[0])/sizeof(matrix[0][0]);/* find no of columns */
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if( i == j)
matrix[i][j] = 0;/* when i and j are equal means thats diagonal and assign it to zero */
else /* if its not diagonal then scan from user */
std::cin>>matrix[i][j];
}
}
return 0;
}
Secondly, I also have to pass it to a function. for this learn how to pass 2d array to a function. Here is the sample example.
void diagonal(int (*mat)[3],int row, int col) { /* mat is pointer to an array */
std::cout<<"printing matrix "<<std::endl;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
std::cout<<mat[i][j]<<"\t";
}
std::cout<<std::endl;
}
}
And call diagonal() like below from main() function as
diagonal(matrix,row,col); /* pass matrix, no of rows, no of columns */

C++ matrix output using ofstream

I am trying to make the function output numbers in a form of a matrix, not just a line
void SaveMatrix(TMatrix* mat){
ofstream SaveM;
SaveM.open("Matrix.txt", ios::out);
if (SaveM.is_open()){
for (int i=0; i<mat->line; ++i){
for (int j=0; j<mat->column; ++j){
SaveM<< mat->m[i][j]<<" ";
}
}
}else{
cout<<"file is open"<<endl;
}
}
I tried to put this in the second for-cycle, without a result
if(j==mat->column){
SaveM<<endl;
}
The matrix is declared:
struct TMatrix {
double* *m;
int line;
int column;
};
j will never reach mat->column in your inner for loop.
I think you could use something like this:
for (int i = 0; i < mat->line; i++){
SaveM << "[";
for (int j = 0; j < mat->column; j++){
SaveM << mat->m[i][j]);
if (j < sizeMatrix - 1){
SaveM << ", ";
}
}
SaveM << "]" << endl;
}

Taking the elements that are > 0 from 1 array to another

I make the user to type maximum elements and then enter that elements into first array p,then I want to take only the elements that are bigger than 0 and transfer them to a new array w. Here's the code and where exactly I make mistake:
void main(){
int p[10], w[10], n,i,j;
cout << "Maximum elements: "; cin >> n;
for (i = 0; i < n; i++){
cout << "Enter " << i << "-nd element"; cin >> p[i];
}
j = 0;
for (i = 0; i < n; i++){
if (p[i] > 0){
w[j] = p[i];
j++;
}
for (j = 0; j < n; j++){
cout << w[j];
}
}
system("pause");
}
In:
for (i = 0; i < n; i++){
if (p[i] > 0){
w[j] = p[i];
j++;
}
for (j = 0; j < n; j++){
cout << w[j];
}
}
the inner loop is printing every element of the array w. That loop is executed for every element of p (being it inside the outer for loop).
This mean that, for example, the first time it visits p to check if the first element is 0, it may assign w[0] and then go on and print all the elements of w. Problem is that w is not initialised at that point, so what you see is random garbage (probably).
Just move the loop outside and make it so it only prints the part of the array that is populated:
for (i = 0; i < n; i++){
if (p[i] > 0){
w[j] = p[i];
j++;
}
}
for (int k = 0; k < j; k++){
cout << w[k];
}
Live demo
Also learn how to use std::vector or std::array and the algorithms in <algorithm>.
Also remember that main has return type int.
Using std::copy_if from <algorithm> do the job you want, as in the example provided in http://www.cplusplus.com/reference/algorithm/copy_if/:
// copy_if example
#include <iostream> // std::cout
#include <algorithm> // std::copy_if, std::distance
#include <vector> // std::vector
int main () {
std::vector<int> foo = {25,15,5,-5,-15};
std::vector<int> bar (foo.size());
// copy only positive numbers:
auto it = std::copy_if (foo.begin(), foo.end(), bar.begin(), [](int i){return !(i<0);} );
bar.resize(std::distance(bar.begin(),it)); // shrink container to new size
std::cout << "bar contains:";
for (int& x: bar) std::cout << ' ' << x;
std::cout << '\n';
return 0;
}
For you code, the problem is that you modify j in the printing loop whereas it is primary used as output index. Try to reduce scope of your local variable to out spot those issues, creating sub function may also help.
Finnaly, your fixed code may be something like:
void main(){
std::cout << "Maximum elements: ";
int n;
std::cin >> n;
int p[10];
for (int i = 0; i < n; i++){
std::cout << "Enter " << i << "-nd element";
std::cin >> p[i];
}
int w[10];
int w_size = 0;
for (int i = 0; i < n; i++){
if (p[i] > 0){
w[w_size] = p[i];
w_size++;
}
}
for (int i = 0; i < w_size; i++){
std::cout << w[i];
}
system("pause");
}