Currently, I am trying to use the linked node to represent the matrix. My codes are working fine, while I not sure it is possible to represent my matrix in tabular form instead of (x,y) = value.
While my printout() method only print it out when temp != NULL, and this is the result
Element position(3,3) = 9
I want to represent it like
1 2 3
4 5 6
7 8 9
Below is my codes with the linked node in the matrix
#include <iostream>
#include <conio.h>
#include <process.h>
#include <stdio.h>
#include <stdlib.h>
#include <cstdlib>
using namespace std;
typedef struct node
{
int column;
int value;
int row;
struct node *next;
} element;
void Init(element *x[])
{
int i;
for (i = 0; i < 11; i++) {
x[i] = NULL;
}
}
void Insert(element *x[], int row, int column, int value)
{
int r = row;
element *p;
element *news = (element*)malloc(sizeof(element));
news->row = row;
news->column = column;
news->value = value;
if (x[r] == NULL)
{
x[r] = news;
news->next = NULL;
}
else
{
p = x[r];
if (news->column < p->column)
{
news->next = p;
x[r] = news;
}
else if (news->column > p->column)
{
while (p->next != NULL && p->next->column < news->column)
{
p = p->next;
}
news->next = p->next;
p->next = news;
}
else cout << "An element already exists there!!\n";
}
}
void Printout(element *x[])
{
int i, test = 0;
element *temp;
for (i = 0; i < 11; i++) {
temp = x[i];
while (temp != NULL) {
cout << "Element position" << "(" << i << "," << temp->column << ") = " << temp->value << endl;
test = 1;
temp = temp->next;
}
}
if (test == 0) {
cout << "This matrix is empty" << endl;
}
}
int main(int argc, const char * argv[]) {
int choice, column, row, value, number;
element *a[10], *b[10], *sum[10];
Init(a); Init(b); Init(sum);
do
{
cout << "Add Sparse Matrix" << endl;
cout << "1. Insert in A" << endl;
cout << "2. Insert in B" << endl;
cout << "3. Print 2 matrix" << endl;
cout << "0. Exit" << endl;
cout << "Please enter your option" << endl;
cin >> choice;
switch (choice)
{
case 1:
do
{
cout << "Enter row -> ";
cin >> row;
} while (row < 0 || row > 11);
do
{
cout << "Enter column -> ";
cin >> column;
} while (column < 0);
cout << "Enter value -> ";
cin >> value;
Insert(a, row, column, value);
break;
case 2:
do
{
cout << "Enter row -> ";
cin >> row;
} while (row < 0 || row > 11);
do
{
cout << "Enter column -> ";
cin >> column;
} while (column < 0);
cout << "Enter value -> ";
cin >> value;
Insert(b, row, column, value);
break;
case 3:
cout << "\n::::::: MATRIX A :> \n\n";
Printout(a);
cout << "\n::::::: MATRIX B :> \n\n";
Printout(b);
break;
default:
cout << "WRONG CHOICE\n\n";
}
} while (choice != 0);
return 0;
}
Sorry for asking this question, I am just started to learn C++ programming, need someone to enlighten me. Thank you for your concern.
Since your linked list is used to saves the memory usage, you can write some codes to print the zero until the width is reached.
void SM::Printout(element *x[])
{
int width = -1;
for (int row = 0; row < 11; row++)
{
for (element *node = x[row]; node != NULL; node = node->next)
if (node->column > width)
width = node->column;
}
width++;
for (int row = 0; row < 11; row++)
{
int col = 0;
for (element *node = x[row]; node != NULL; node = node->next)
{
for (; col < node->column; col++)
cout << "0 ";
if (node->value != NULL)
cout << node->value << " ";
col = node->column + 1;
}
for (; col < width; col++)
cout << "0 ";
cout << "\n";
}
}
Related
#include <iostream>
#include <stdio.h>
#include <ctype.h>
using namespace std;
class List{
private:
int A[10];
int i;
public:
List(){
i = 0;
}
void insert(){
int v;
for(int j = 0 ; j < 10 ; j++){
cout << "\nElement you want to insert: (" << i+1 << "). ";
cin >> v;
if(i <= 9){
A[i] = v;
i++;
}
else{
cout << "\nWrong Input" << endl;
break;
}
}
if(i > 9){
cout << "\nYour List Capacity is Full.\n" << endl;
}
}
void display(){
cout << "\n{ ";
for(int j = 0 ; j < i ; j++)
cout << A[j] << " ";
cout << "}\n" << endl;
}
void remove(){
int p;
cout << "\nElement you want to remove (0 - 9): ";
cin >> p;
if (i == 0){
cout << "\nList is empty!\n" << endl;
return;
}
if (p >= 0 && p < i){
for(int j = p ; j < i-1 ; j++)
A[j] = A[j + 1];
i--;
}
}
void size(){
cout << "\nYour list size is: " << i << endl;
}
void checkcapacity(){
int arrSize = sizeof(A)/sizeof(A[0]);
cout << "\nThe Capacity of the array is: " << arrSize << endl;
}
};
int main(){
List l;
int a;
cout << "\t\t\t\t\t\tWelcome to List Program!";
while(a != 4){
int choose;
cout << "\nThe Program have following options:\n1. Insert\n2. Display\n3. Remove\n4. Check Size\n5. Check Capacity\n6. Exit\n\nNote: Your list capacity is 10!";
cout << "\n\nChoose (1 - 5): ";
cin >> choose;
if (choose == 1){
l.insert();
}
else if (choose == 2){
l.display();
}
else if (choose == 3){
l.remove();
}
else if (choose == 4){
l.size();
}
else if (choose == 5){
l.checkcapacity();
}
else if (choose == 6){
a = 4;
}
}
cout << "Thank you for using this program!";
}
I'm using this class in my main function in which I call them but when the user inputs a char or string in the insert function it goes into infinte loop. Int i is my counter and it just contains the size of my array list im just trying to put a check of character that if user input a character is should show an error.
Here's one way to write your insert function
void insert()
{
int v;
for(int j = 0 ; j < 10 ; j++)
{
cout << "\nElement you want to insert: (" << i+1 << "). ";
if (cin >> v)
{
if (i < 10)
{
A[i] = v;
i++;
}
}
else
{
cin.clear(); // clear error
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // discard any pending input
}
}
if (i >= 10)
cout << "\nYour List Capacity is Full.\n" << endl;
}
The important part is the recovery from bad input. First cin.clear() is called to clear the stream error state, secondly cin.ignore(...) is called to discard any pending input.
More details here
in my project there are 2 structures, one of which relates to a binary tree, the second to students data
in ' int main ' I can’t access the add function GETDATA
' 'ZKR' does not refer to a value . ' (xcode)
I also can’t create a counter of the number of vertices of my tree
#include <iostream>
#include <ctime>
#include <cstring>
using namespace std;
struct ZKR {
char FACULTY[30];
int ACADEMIC_DEGREE;
char FIO[30];
};
struct point
{
char *data;
point *left;
point *right;
};
point* tree(int n, point* p)
{
point *r;
int nl, nr;
if (n == 0) { p = NULL; return p; }
nl = n / 2;
nr = n - nl - 1;
r = new point;
char s[50];
cout << "Значение: ";
cin >> s;
r->data = new char[strlen(s) + 1];
strcpy(r->data,s);
r->left = tree(nl, r->left);
r->right = tree(nr, r->right);
p = r;
return p;
}
void GETDATA(ZKR*M, int N)
{
cin.ignore();
for (int i = 0; i < N; i++)
{
cout << "\n";
cout << "FACULTY: ";
cin.getline(M[i].FACULTY, 30);
cout << "\n";
cout << "FIO: ";
cin.getline(M[i].FIO, 30);
cout << "\n";
cout << "ACADEMIC DEGREE: ";
cin >> M[i].ACADEMIC_DEGREE;
cin.ignore();
}
}
void treeprint(point *p, int &count) {
if (p != NULL) {
treeprint(p->left, count);
cout << p->data << " ";
treeprint(p->right, count);
if ((p->left == NULL) && (p->right == NULL))
count = count + 1;
}
}
int main()
{
setlocale(LC_ALL, "russian");
srand(time(NULL));
int n = 0, k = 0, count = 0;
point *beg = nullptr;
cout << "Enter the number of students" << endl;
int N;
cin >> N;
ZKR*M = new ZKR[N];
do
{
cout << "1. BUILD a binary tree\n";
cout << "2. SHOW a binary tree\n";
cout << "3. GETDATA\n";
cin >> k;
switch (k)
{
case 1:
cout << "Введите количество элементов" << endl;
cin >> n;
beg = tree(n, beg);
cout << endl;
break;
case 2:
treeprint(beg, count);
cout << endl;
cout << "Листьев в дереве: " << count << endl;
break;
case 3:
GETDATA(ZKR*M, N);
break;
}
} while (k != 4);
system("pause");
return 0;
}
I will be grateful for any help
This line is not syntactically correct:
GETDATA(ZKR*M, N);
Replace it with:
GETDATA(M, N);
M is a pointer to an object of type ZKR.
My apologies for being a little vague about the issue(s) in the topic, but I really am not sure. I am attempting to create a course_directory as a lab project for school, and up until now everything had been progressing quite well. I have written and tested each of the function in the main.cpp before attempting to move the class functions into the .hpp file. My goal is to have nothing in main except for a call to "Run" that will open a file, and in turn make a call to "displayMenu", and allow the user to interact with the information as they choose, but now everything is compiling correctly, and nothing is being displayed.
Course_directory.hpp
#include "Course_Directory.h"
using namespace std;
Course_Directory::Course_Directory(){};
Course_Directory courses[1001];
void Course_Directory::displayMenu(){
cout << "1.Print all courses" << endl;
cout << "2.Print all courses for a department" << endl;
cout << "3.Print roster for a course" << endl;
cout << "4.Print the largest class" << endl;
cout << "5.Swap two classes" << endl;
cout << "6.Print schedule for a student" << endl;
cout << "7.Exit" << endl;
char dept[50], dept2[50];
int courseNo, courseNo2, i, choice;
while (choice != 7) {
cout << "\nEnter your choice: ";
cin >> choice;
if (choice == 1)
printAllCourses(i);
else if (choice == 2) {
cout << "\nEnter department name:";
cin >> dept;
for(int j = 0; j < sizeof(dept); j++)
{
dept[j] = (toupper(dept[j]));
}
coursesInDept(dept, i);
}
else if (choice == 3) {
cout << "\nEnter course number:";
cin >> courseNo;
studentsInCourse(courseNo, i);
}
else if (choice == 4) {
largestClass(i);
}
else if (choice == 5) {
cout << "\nEnter first department name :";
cin >> dept;
for(int j = 0; j < sizeof(dept); j++)
{
dept[j] = (toupper(dept[j]));
}
cout << "\nEnter first course number: ";
cin >> courseNo;
cout << "\nEnter second department name :";
cin >> dept2;
for(int k = 0; k < sizeof(dept2); k++)
{
dept2[k] = (toupper(dept2[k]));
}
cout << "\nEnter second course number: ";
cin >> courseNo2;
swap2(dept, courseNo, dept2, courseNo2, i);
}
else if (choice == 6) {
int id;
cout << "\nEnter a student Id:";
cin >> id;
schedule(id, i);
}
}
cout << "Goodbye!\n";
}
void Course_Directory::printAllCourses(int len){
for (int i = 0; i < len; i++)
cout << "Course name: " << courses[i].courseName << ", Course
number: " << courses[i].courseNum << endl;
cout << len;
}
void Course_Directory::coursesInDept(char *dept, int len) {
for (int i = 0; i < len; i++)
if (strcmp(dept, courses[i].courseName) == 0)
cout << "Course Name: " << courses[i].courseName << ",
Course number: " << courses[i].courseNum << endl;
}
void Course_Directory::studentsInCourse(int courseNo, int len) {
for (int i = 0; i < len; i++)
if (courseNo == courses[i].courseNum) {
for (int m = 0; m < courses[i].numStudents - 1; m++)
cout << courses[i].IDs[m] << ",";
cout << courses[i].IDs[courses[i].numStudents - 1] <<
endl;
}
}
void Course_Directory::largestClass(int len) {
int max = -999;
for (int i = 0; i < len; i++) {
if (courses[i].numStudents > max)
max = courses[i].numStudents;
}
for (int i = 0; i < len; i++) {
if (courses[i].numStudents == max){
cout << "\nThe largest class is in department: " <<
courses[i].courseName
<< ", and the course number is: " << courses[i].courseNum
<< "\n";
cout << "The class currently has " << max << " students
enrolled.\n";
}
}
}
void Course_Directory::swap2(char *firstDep, int firstNo, char
*secondDep, int secondNo, int len) {
Course_Directory temp;
int firstIndex, secondIndex;
for (int i = 0; i < len; i++) {
if (strcmp(firstDep, courses[i].courseName) == 0 &&
courses[i].courseNum == firstNo)
firstIndex = i;
if (strcmp(secondDep, courses[i].courseName) == 0 &&
courses[i].courseNum == secondNo)
secondIndex = i;
}
temp = courses[firstIndex];
courses[firstIndex] = courses[secondIndex];
courses[secondIndex] = temp;
}
void Course_Directory::schedule(int id, int len) {
cout << "Courses student " << id << " is enrolled in: " << endl;
for (int i = 0; i < len; i++) {
for (int j = 0; j < courses[i].numStudents; j++)
if (courses[i].IDs[j] == id)
cout << courses[i].courseNum << " \n";
}
}
Course_Directory.h
#ifndef COURSE_DIRECTORY_H
#define COURSE_DIRECTORY_H
#include <iostream>
using namespace std;
class Course_Directory{
private:
int* deptSize;
string filename;
public:
char courseName[1001];
int courseNum;
int numStudents;
int IDs[1001];
int* choice;
void displayMenu();
Course_Directory();
//Course_Directory(const Course_Directory& original);
//~Course_Directory();
//void run(string);
void coursesInDept(char*, int);
void studentsInCourse(int, int);
void largestClass(int);
void swap2(char*, int, char*, int, int);
void schedule(int, int);
void printAllCourses(int);
};
#include "Course_Directory.hpp"
#endif //COURSE_DIRECTORY_H
main.cpp
#include "Course_Directory.h"
using namespace std;
class Course_Directory;
int main() {
ifstream file;
file.open("input.txt");
char *token;
int i = 0, j;
Course_Directory courses[100];
if (!file.fail()) {
std::string line;
while (getline(file, line)) {
j = 0;
char *str = const_cast<char *>(line.c_str());
token = strtok(str, " ");
while (token != NULL)
{
if (j == 0)
strcpy(courses[i].courseName, token);
else if (j == 1)
courses[i].courseNum = atoi(token);
else if (j == 2)
courses[i].numStudents = atoi(token);
else
courses[i].IDs[j - 3] = atoi(token);
j++;
token = strtok(NULL, " ");
cout << courses[i].courseName << endl;
}
i++;
}
file.close();
}
else{
cout << "File not found." << endl;
}
//menu
Course_Directory displayMenu();
return 0;
}
If I leave Course_Directory off of displayMenu(); then I get "displayMenu" was not declared in this scope. I'm not sure what the problem is or why the menu will not display. Any help would be greatly appreciated!
I am using C++ and want to do a 2-dimensional array. 10 rows and 3 columns. First column is(1 through 10). For Second column, user enters his/her choice of a number from (1-10) resulting in a times table displaying the results as follows: In this example the user's choice is '4':
1x4=4
2x4=8
3x4=12
4x4=16
5x4=20
6x4=24
7x4=28
8x4=32
9x4=36
10x4=40
I can't get the user's input to calculate correctly when using the for loop.
Well you can try this to get that output
#include<iostream>
using namespace std;
int main()
{
int n; //To take input
int table[10][3]; // Table
cout << "Input a number: ";
cin >> n;
// Generating Output
for (int i = 0; i < 10; i++)
{
table[i][0] = i + 1;
table[i][1] = n;
table[i][2] = table[i][0] * table[i][1];
}
for (int i = 0; i < 10; i++)
{
cout << table[i][0] << " * " << table[i][1] << " = " << table[i][2]<<endl;
}
return 0;
}
Output
SOLVED: Everything seems to be working now!! Here's the code:
#include <iostream>
#include<cstdlib>
#include<iomanip>
#include <ctime>
using namespace std;
void displayTable(int table[10][3]);
bool testMe(int testTable[10][3]);
void createTables(int testTable[10][3], int ansTable[10][3], int
usersChoice);
bool AllAnswersAreTested(bool tested[10]);
void gradeMe(int testTable[10][3], int ansTable[10][3]);
void displayMenu();
int main()
{
srand(time(NULL));
int userInput = 0;
int tableChoice = 0;
int myTable[10][3] = {0};
int testTable[10][3];
int ansTable[10][3];
bool tested = false;
do
{
displayMenu(); //Display the menu of choices
cin >> userInput;
cout << endl;
switch (userInput) //Validate menu choices 1-4
{
case 1: //Display a users choice of table
displayTable(myTable);
break;
case 2: //Test user on users choice of table
cout << "What times table test would you like to take? > ";
cin >> tableChoice;
createTables(testTable, ansTable, tableChoice);
tested = testMe(testTable);
if (tested)
{
gradeMe(testTable, ansTable);
}
break;
case 3: //Display a new table of the users choice
displayTable(myTable);
break;
case 4: //Quit program menu option
cout << "Program ending.\n";
return 0;
default: //Invalid entry
cout << "You entered an invalid item number. Please enter a number from 1 to 4.\n";
cout << endl;
}
} while (userInput != 4);
return 0;
}
void displayTable(int myTable[10][3])
{
int num; //initialize local variables
//Ask the user what times table they would like to review
cout << "What times table would you like to review?" << endl;;
cout << "Please enter a value from 1 to 12 > \n";
cout << "\n";
cin >> num;
cout << endl;
for (int i = 0; i < 10; i++)
{
myTable[i][0] = i + 1;
myTable[i][1] = num;
myTable[i][2] = myTable[i][0] * myTable[i][1];
}
for (int i = 0; i < 10; i++)
{
cout << setw(3)<< myTable[i][0] << " * " << myTable[i][1] << " = " << myTable[i][2] << endl;
}
cout << endl;
}
void createTables(int testTable[10][3], int ansTable[10][3], int usersChoice)
{
for (int i = 0; i < 10; i++)
{
testTable[i][0] = i + 1;
testTable[i][1] = usersChoice;
testTable[i][2] = 0;
ansTable[i][0] = i + 1;
ansTable[i][1] = usersChoice;
ansTable[i][2] = usersChoice * (i + 1);
}
}
bool testMe(int testTable[10][3])
{
bool tested[10] = { false, false, false, false, false,false, false, false, false, false };
while (!AllAnswersAreTested(tested))
{
int index = rand() % 10;
if (tested[index] == false)
{
int randomNum = testTable[index][0];
int tableChoice = testTable[index][1];
int answer;
cout << "What is " << randomNum << " X " << tableChoice << " = ";
cin >> answer;
testTable[index][2] = answer;
tested[index] = true;
}
}
return true;
}
bool AllAnswersAreTested(bool tested[10])
{
for (int i = 0; i < 10; i++)
{
if (tested[i] == false)
{
return false;
}
}
return true;
}
void gradeMe(int testTable[10][3], int ansTable[10][3])
{
int correctAnswers = 0;
for (int i = 0; i<10; i++)
{
if (testTable[i][2] == ansTable[i][2])
{
correctAnswers++;
}
}
int score = (correctAnswers * 10);
if (score == 100)
{
cout << "You passed the test! PERFECT SCORE!!" << endl;
cout << endl;
}
else if (score >= 70)
{
cout << "You passed the test. Your Score is: ";
cout << score;
cout << endl;
}
else if (score < 70)
{
cout << "You did not pass the test. Your Score is: ";
cout << score;
cout << endl;
}
}
//Display the menu function
void displayMenu()
{
cout << " Multiplication Tables" << endl;
cout << endl;
cout << " 1. Review MyTable" << endl;
cout << " 2. Test Me" << endl;
cout << " 3. Enter a New Multiplication Table (1-12)";
cout << " 4. Quit" << endl;
cout << " Enter a Menu Item > ";
}
#include <iostream>
using namespace std;
int main()
{
int a[100][100];
for(int i=1;i<10;i++){
for(int j=1;j<10;j++){
a[i][j] = (i)*(j);
cout<<a[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
There is how the output looks like:
I wanna simulate dynamic array by using static array. However, when I delete some elements from the array and then try to add the array, I got an error saying 'Heap Corruption Detected'.
Here's my code:
#include <iostream>
#include <algorithm>
using namespace std;
int INIT_SIZE = 5;
int MAX_SIZE = INIT_SIZE;
void printArray(int *arr, int n){
cout << "n= " << n << " >> [";
for(int i = 0; i < n ;i++){
cout << arr[i];
if ( i < n-1)
cout << ",";
}
cout << "]\b\n";
}
bool deleteEl(int *&arr, int &n, int el){
int *newArr;
bool found = false;
int cnt = 0;
if( n == 0){
return false;
}
else{
for(int i = 0; i < n;i++){
if( arr[i] == el){
found = true;
cnt++;
}
}
if( !found){
return false;
}
newArr = new int[n-cnt];
int k = 0;
for(int i = 0; i < n ; i++){
if( arr[i] != el){
newArr[k++] = arr[i];
}
}
n -= cnt;
if (n <= (MAX_SIZE / 2) && (MAX_SIZE / 2) >= INIT_SIZE){
MAX_SIZE /= 2;
}
delete[] arr;
arr = newArr;
}
return true;
}
bool addEl(int *&arr, int &n, int el){
int *newArr;
if( n >= MAX_SIZE){
newArr = new int[2 * MAX_SIZE];
//std::copy(arr,arr+MAX_SIZE, newArr);
for(int i = 0 ; i < n;i++){
newArr[i] = arr[i];
}
n++;
newArr[n-1] = el;
MAX_SIZE *= 2;
delete[] arr;
arr = newArr;
}else{
arr[n++] = el;
}
return true;
}
int main(int argc, char *argv[]){
int *arr = new int[MAX_SIZE];
int n = 0;
int input = 0;
do{
cout << "1. Add Element : " << endl;
cout << "2. Del Element : " << endl;
cout << "3. Exit : " << endl;
cin >> input;
if( input == 1){
cout << "Enter new element : " << endl;
int newEl;
cin >> newEl;
if( addEl(arr, n, newEl)){
cout << "New Element Added. " << endl;
}else{
cout << "Add new element failed. " << endl;
}
}else if (input == 2){
cout << "Enter deleted element : " << endl;
int del;
cin >> del;
if( deleteEl(arr, n, del)){
cout << "Deletion OK" << endl;
}else{
cout << "Deletion Fail. Data Not found." << endl;
}
}else if(input == 3){
cout << "Program exiting ..." << endl;
}else{
cout << "Input is wrong. Enter correct input (1,2, or 3)." << endl;
}
printArray(arr,n);
}while(input != 3);
delete [] arr;
return 0;
}
Have a look at the Hinnant's stack allocator and consider using STL instead of naked arrays.