Trying to multiply matrices. Getting absurd result - c++

#include <iostream>
#include <malloc.h>
using namespace std;
int main()
{
int r,c,r2,c2;
cout << "Enter the number of rows:- \n";
cin >> r;
cout << "\n" <<"Enter the number of columns: \n";
cin >> c;
int **mat;
int **mat2;
mat=(int**)malloc(sizeof(int)*r); // allocating memory to a row
for (int i=0;i<r;i++)
{
*(mat+i)=(int*)malloc(sizeof(int)*c); /* allocating memory to
columns in rows ( double pointers ) */
}
cout << "\n\n" << "Please enter the 1st matrix of order:- " << r << 'x'
<< c<< endl;
for (int i=0;i<r;i++)
{ for (int j=0;j<c;j++)
{
cin >> *(*(mat+i)+j);
cout << endl;
}
}
cout << "Enter the number of rows(2nd):- \n";
cin >> r2;
cout << "\n" <<"Enter the number of columns(2nd): \n";
cin >> c2;
mat2=(int**)malloc(sizeof(int)*r2);
for (int i=0;i<r2;i++)
{
*(mat2+i)=(int*)malloc(sizeof(int)*c2);
}
cout << "\n\n" << "Please enter the 2nd matrix of order:- " << r2 << 'x'
<< c2 <<endl;
for (int i=0;i<r2;i++)
{
for (int j=0;j<c2;j++)
{
cin >> *(*(mat2+i)+j);
cout << endl;
}
}
cout <<"\n\n\n" <<"The 1st matrix you entered is:- \n";
for (int i=0;i<r;i++)
{ for (int j=0;j<c;j++)
{
cout << *(*(mat+i)+j) << '\t';
}
cout << endl;
}
cout << "\n\n" << "The second matrix you entered is:- \n";
for (int i=0;i<r2;i++)
{ for (int j=0;j<c2;j++)
{
cout << *(*(mat2+i)+j) << '\t';
}
cout << endl;
}
int **mat4;
mat4=(int**)malloc(sizeof(int)*r);
for (int i=0;i<r;i++)
{
*(mat4+i)=(int*)malloc(sizeof(int)*c2);
}
if (c!=r2)
{
cout << "\n\n These two matrices cannot be multiplied as number of
columns("<< c<< ")of 1st matrix \nis not equal to number of
rows("<< r2<< ") of second matrix.";
}
if( c==r2)
{
for (int i=0;i<r;i++)
{
for (int z=0;z<c2;z++)
{
for (int j1=0;j1<r2;j1++)
{
mat4[i][z]+= mat[i][j1] * mat2[j1][z]; /* logic to
multiply two matrices */
}
}
}
for (int i=0;i<r;i++)
{
for (int j=0;j<c2;j++)
{
cout << mat4[i][j] << '\t';
}
cout << endl;
}
}
return (1);
}
The problem occurs when I enter a 2x2 and a 2x3 matrix or any combination with c2=c+1. I get random large number in the output. Else if I enter any other combination of number of rows and columns, it works just fine. For example- If I put r2=3 and c2=4 , I'll get absurd values at column 1 and 3 no matter what input I do.

Related

Output does not include all input for my array

I have this program that is barely started:
#include <iostream>
#include <iomanip>
#include <ctime>
#include <string>
using namespace std;
class Grade
{
public:
string studentID;
int userChoice = 0;
int size = 0;
double* grades = new double[size]{0};
};
void ProgramGreeting(Grade &student);
void ProgramMenu(Grade& student);
string GetID(Grade& student);
int GetChoice(Grade& student);
void GetScores(Grade& student);
int main()
{
Grade student;
ProgramGreeting(student);
ProgramMenu(student);
}
// Specification C1 - Program Greeting function
void ProgramGreeting(Grade &student)
{
cout << "--------------------------------------------" << endl;
cout << "Welcome to the GPA Analyzer! " << endl;
cout << "By: Kate Rainey " << endl;
cout << "Assignment Due Date: September 25th, 2022 " << endl;
cout << "--------------------------------------------" << endl;
GetID(student);
cout << "For Student ID # " << student.studentID << endl;
}
void ProgramMenu(Grade &student)
{
cout << "--------------------------------------------" << endl;
cout << setw(25) << "Main Menu" << endl;
cout << "1. Add Grade " << endl;
cout << "2. Display All Grades " << endl;
cout << "3. Process All Grades " << endl;
cout << "4. Quit Program." << endl;
cout << "--------------------------------------------" << endl;
GetChoice(student);
}
string GetID(Grade &student)
{
cout << "Enter the student's ID: ";
cin >> student.studentID;
if (student.studentID.length() != 8) {
cout << "Student ID's contain 8 characters ";
GetID(student);
}
return student.studentID;
}
int GetChoice(Grade &student)
{
cout << "Enter your selection: ";
cin >> student.userChoice;
if (student.userChoice == 1) {
GetScores(student);
}
else if (student.userChoice == 2)
{
}
else if (student.userChoice == 2)
{
}
else if (student.userChoice == 4)
{
exit(0);
}
else
{
cout << "Please enter 1, 2, 3 or 4" << endl;
GetChoice(student);
}
}
void GetScores(Grade &student)
{
int count = 0;
double score = 0;
cout << "How many test scores would you like to enter for ID# "
<< student.studentID << "? ";
cin >> student.size;
while (count != student.size) {
cout << "Enter a grade: ";
cin >> score;
for (int i = 0; i < student.size; i++) {
student.grades[i] = score;
}
count++;
}
for (int i = 0; i < student.size; i++) {
cout << student.grades[i] << " ";
}
}
I am trying to make sure my array is recording all test scores, but when I output the array in my GetScore function, each element in the array is the same or equal to the last score I entered. For example, if I choose 3 for size and then enter three values of 99.2 86.4 90.1, all three elements will read 90.1.
Why is this happening?
Your Grade class is allocating an array of 0 double elements (which is undefined behavior), and then your GetScores() function does not reallocate that array after asking the user how many scores they will enter, so you are writing the input values to invalid memory (which is also undefined behavior).
Even if you were managing the array's memory correctly (ie, by using std::vector instead of new[]), GetScores() is also running a for loop that writes the user's latest input value into every element of the array, instead of just writing it to the next available element. That is why your final output displays only the last value entered in every element. You need to get rid of that for loop completely.
Try something more like this instead (there are several other problems with your code, but I'll leave those as separate exercises for you to figure out):
class Grade
{
public:
...
int size = 0;
double* grades = nullptr;
};
...
void GetScores(Grade &student)
{
int size = 0;
double score = 0;
cout << "How many test scores would you like to enter for ID# " << student.studentID << "? ";
cin >> size;
if (student.size != size) {
delete[] student.grades;
student.grades = new double[size]{0};
student.size = size;
}
for(int i = 0; i < size; ++i) {
cout << "Enter a grade: ";
cin >> score;
student.grades[i] = score;
}
for (int i = 0; i < size; ++i) {
cout << student.grades[i] << " ";
}
}
Alternatively:
#include <vector>
...
class Grade
{
public:
...
vector<double> grades;
};
...
void GetScores(Grade &student)
{
size_t size = 0;
double score = 0;
cout << "How many test scores would you like to enter for ID# " << student.studentID << "? ";
cin >> size;
student.grades.resize(size);
for (size_t i = 0; i < size; ++i) {
cout << "Enter a grade: ";
cin >> score;
student.grades[i] = score;
}
/* alternatively:
student.grades.clear();
for (size_t i = 0; i < size; ++i) {
cout << "Enter a grade: ";
cin >> score;
student.grades.push_back(score);
}
*/
for (size_t i = 0; i < size; ++i) {
cout << student.grades[i] << " ";
}
}
I removed my for loop from my while loop.
void GetScores(Grade &student)
{
int count = 0;
double score = 0;
cout << "How many test scores would you like to enter for ID# "
<< student.studentID << "? ";
cin >> student.size;
while (count != student.size) {
cout << "Enter a grade: ";
cin >> score;
student.grades[count] = score;
count++;
}
for (int j = 0; j < student.size; j++) {
cout << student.grades[j] << " ";
}
}

How do i add up my array values and display it along side with my other values

I am trying to add up all the values that have been stored into array b and have it display under the "total column" and don't know how to only have the scores add together.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int array[5][4];
int sum = 0;
cout<<"Enter grades for 4 exams for the 5 students \n";
for(int i=0;i<5;i++)
{
for(int b=1;b<=4;b++)
{
cout <<setw(8)<< "enter student "<< i << "'s grade for exam " << b << '\n';
cin >> array[i][b];
}
}
cout <<"ID"<<setw(11)<<"score 1"<<setw(11)<<"score 2"<<setw(11)<<"score 3"<<setw(11)<<"score 4"<<setw(11)<<"total"<<setw(11)<<"letter"<<endl;
cout <<"--------------------------------------------------------------------------------------------------------------\n";
for(int i=0;i<5;i++)
{
cout << i<< " ";
for(int b=1;b<=4;b++)
{
sum = sum + array[b];
cout <<setw(10)<<array[i][b]<<sum;
}
cout <<'\n';
}
cout <<"--------------------------------------------------------------------------------------------------------------\n";
return 0;
}
To be more specific around line 28
for(int i=0;i<5;i++)
{
cout << i<< " ";
for(int b=1;b<=4;b++)
{
sum = sum + array[b];
cout <<setw(10)<<array[i][b]<<sum;
}
cout <<'\n';
Arrays indexes start at 0, not 1. You are correctly looping through your array's 1st dimension, but not its 2nd dimension. You need to change the inner for loops from for(int b=1;b<=4;b++) to for(int b=0;b<4;b++)
Also, to handle the total column, you simply need to reset sum to 0 on each iteration of the 1st dimension, and then print the result after the iteration of the 2nd dimension.
Try this:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int array[5][4];
cout << "Enter grades for 4 exams for the 5 students \n";
for(int i = 0; i < 5; i++)
{
for(int b = 0; b < 4; b++)
{
cout << "Enter student " << i+1 << "'s grade for exam " << b+1 << '\n';
cin >> array[i][b];
}
}
cout << "ID" << setw(11) << "score 1" << setw(11) << "score 2" << setw(11) << "score 3" << setw(11) << "score 4" << setw(11) << "total" << setw(11) << "letter" << endl;
cout << "--------------------------------------------------------------------------------------------------------------\n";
for(int i = 0; i < 5; i++)
{
cout << setw(2) << left << i+1 << right;
int sum = 0;
for(int b = 0; b < 4; b++)
{
sum = sum + array[i][b];
cout << setw(11) << array[i][b];
}
cout << setw(11) << sum << '\n';
}
cout << "--------------------------------------------------------------------------------------------------------------\n";
return 0;
}
Online Demo

How can I display only cars with 5 seats?

How can I make the program display only cars that have 5 seats, for now no matter what, it shows all cars that I write infos about them, for example if I write in the console that there are 3 cars and give information about them and say that one has 2 seats and the others have 5 after I run the program it still displays all 3 of them. Any idea of how can I display only cars with 5 seats? Can I somehow use the quicksort() function ?
#include <iostream>
using namespace std;
struct Car
{
int no_seats;
int year;
char brand[20];
char color[20];
float horse_power;
};
void read_cars(Car C[], int &n)
{
int i;
cout << "Number of parked cars "; cin >> n;
for(i=1; i<=n; i++)
{
cout << "Brand " ; cin >> M[i].brand;
cout << "The year it was made in " ; cin >> M[i].year;
cout << "Color " ; cin >> M[i].color;
cout << "Power " ; cin >> M[i].horse_power;
cout << "Number of seats " ; cin >> M[i].no_seats;
}
}
void display_cars(Car C[], int n)
{
int i;
for(i=1; i<=n; i++)
{
cout << "Brand " ; cout << M[i].brand << endl;
cout << "The year it was made in " ; cout << M[i].year << endl;
cout << "Color " ; cout << M[i].color << endl;
cout << "Power " ; cout << M[i].horse_power << endl;
cout << "Number of seats " ; cout << M[i].no_seats << endl;
}
}
int main()
{
Car C[50];
int n;
read_cars(M, n);
display_cars(M, n);
return 0;
}
You need to add a condition in the loop:
void display_cars(Car C[], int n)
{
int i;
for(i=1; i<=n; i++)
{
if(M[i].no_seats == 5) // <- like this
{
cout << "Brand " ; cout << M[i].brand << endl;
cout << "The year it was made in " ; cout << M[i].year << endl;
cout << "Color " ; cout << M[i].color << endl;
cout << "Power " ; cout << M[i].horse_power << endl;
cout << "Number of seats " ; cout << M[i].no_seats << endl;
}
}
}
Other notes:
Your n can only go up to 49 - remember that. That also means that you are wasting an element at M[0] (yes arrays are zero based in C++).
Prefer to use std::vector<Car> C over an array of fixed size. A std::vector grows as you push_back more and more elements into it - and it keeps track of the number of contained elements, so you do not need to pass the size of the vector around. C.size() would tell you the number of elements.
void display_cars(const std::vector<Car>& C)
{
std::cout << "There are " << C.size() << " cars in the vector\n";
for(const Car& a_car : C) // a range based for-loop
{
if(a_car.no_seats == 5) // a_car will be a reference to each car in the loop
{
// use "a_car" to display info about one particular car
}
}
}

about arrays in c++

i've been studying c++ for 3 months , and i studied the arrays , i wrote a program such that will take inputs from user , then the program will store these numbers in a special array , then the program will split them into two arrays , one for even numbers, the other one for odd numbers , my question is , when i tried to display them , there was something wrong happened , but i could not figure it out , can you help me please ?
int main () {
int even[5];
int odd[5];
int num;
cout << "enter 4 numbers!";
for(int i=0; i<4; i++) {
cin >> num;
if( num%2 == 0){
cout << "its an even number!";
even[i] += num;
}
else{
cout << "its an odd number!";
odd[i] += num;
}
}
cout << "The odd number/s is/are: ";
for( int u=0; u<4; u++){
cout << odd[u] << endl;
}
cout << endl;
cout << "The even number/s is/are: " << endl;
for(int z=0; z<4; z++){
cout << even[z] << endl;
}
}
Thank you for helping me!
From your question, it looks like you're trying to split a given integer array into two arrays even and odd. The problem here is the way in which you're allocating the values into the new arrays, You have a counter i which is responsible to put the values into even[i] and odd[i]. So you have a lot of broken sections even[0] might exist but the odd[1] might be the first odd value you obtain. You should have individual counters for storing these values. So the corrections to your code would look as follows
int main () {
int even[5];
int odd[5];
int num;
int evencount = 0;
int oddcount = 0;
cout << "enter 4 numbers!";
for(int i=0; i<4; i++) {
cin >> num;
if( num%2 == 0){
cout << "its an even number!";
even[evencount++] = num;
}
else{
cout << "its an odd number!";
odd[oddcount++] = num;
}
}
cout << "The odd number/s is/are: ";
for( int u=0; u < oddcount; u++){
cout << odd[u] << endl;
}
cout << endl;
cout << "The even number/s is/are: " << endl;
for(int z=0; z<evencount; z++){
cout << even[z] << endl;
}
}
I have a slightly different approach:
#include <iostream>
using namespace std;
int main () {
int array[4]; // array size needs to be 4 only and not 5
/*int num;*/ // not required
bool is_odd[4] = {false, false, false, false};
cout << "enter 4 numbers!\n";
for(int i=0; i<4; i++) {
cin >> array[i];
if( array[i]%2 == 0){
cout << "its an even number!\n";
}
else{
cout << "its an odd number!\n";
is_odd[i] = true;
}
}
cout << "The odd number/s is/are:\n";
for( int u=0; u < 4; u++){
if (is_odd[u] == true)
cout << array[u] << endl;
}
cout << endl;
cout << "The even number/s is/are:\n" << endl;
for(int u=0; u < 4; u++) {
if (is_odd[u] == false)
cout << array[u] << endl;
}
}
Check the answer here: check-answer
You access values of the array that are declared but not initialized. So there are any values in it. like 6.49e154. Always initialize when declaring!

Two Dimensional Array outputs one continuous row

Hello I am new to C++ and am having trouble understanding why this two dimensional array is only producing one row and many columns. It reads the correct information but does not output it with the correct columns and rows.
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
#include <windows.h>
using namespace std;
char pat [9][9]= {'$','$','$','$','$','$','$','$','$',
'$','$','$','$','$','$','$','$','$',
'$','$','$','$','$','$','$','$','$',
'$','$','$','$','$','$','$','$','$',
'$','$','$','$','$','$','$','$','$',
'$','$','$','$','$','$','$','$','$',
'$','$','$','$','$','$','$','$','$',
'$','$','$','$','$','$','$','$','$',
'$','$','$','$','$','$','$','$','$'}; // 9x9 matrix
int main ()
{
int pattern,
dimensions;
do
{
cout << "1) Display Pattern 1" << endl; //menu selections
cout << "2) Display Pattern 2" << endl;
cout << "3) Display Pattern 3" << endl;
cout << "4) Display Pattern 4" << endl;
cout << "5) Exit Program" << endl << endl;
cout << "Please select an option. ";
cin >> pattern;
if (pattern == 1)
{
system("cls");
do
{
cout << "Note: Choose a number between 1 and 10." << endl;
cout << "Choose a number ";
cin >> dimensions;
cout << endl;
if (dimensions > 1 && dimensions < 10)
/* based on the user's input for dimension
it will output a square i.e. 2x2, 3x3, 4x4 etc */
{
cout << "True!" << endl;
for (int rows = 0; rows < dimensions; rows++)
{
for (int cols = 0; cols < dimensions; cols++)
cout << pat[cols][rows];
}
}
else
{
cout << "Error! Number is not between this set!" << endl;
Sleep(3000);
cout << endl;
}
}
while (pattern == 1);
}
else if (pattern == 2)
{
system("cls");
do
{
cout << "Note: Choose a number between 1 and 10." << endl;
cout << "Choose a number ";
cin >> dimensions;
cout << endl;
if (dimensions > 1 && dimensions < 10)
{
cout << "True!";
}
else
{
cout << "Error! Number is not between this set!" << endl;
Sleep(3000);
cout << endl;
}
}
while (pattern == 2);
}
else if (pattern == 3)
{
system("cls");
do
{
cout << "Note: Choose a number between 1 and 10." << endl;
cout << "Choose a number ";
cin >> dimensions;
cout << endl;
if (dimensions > 1 && dimensions < 10)
{
cout << "True!";
}
else
{
cout << "Error! Number is not between this set!" << endl;
Sleep(3000);
cout << endl;
}
}
while (pattern == 3);
}
else if (pattern == 4)
{
system("cls");
do
{
cout << "Note: Choose a number between 1 and 10." << endl;
cout << "Choose a number ";
cin >> dimensions;
cout << endl;
if (dimensions > 1 && dimensions < 10)
{
cout << "True!";
}
else
{
cout << "Error! Number is not between this set!" << endl;
Sleep(3000);
cout << endl;
}
}
while (pattern == 4);
}
else if (pattern == 5)
{
return 0;
}
else
{
cout << "Please input a valid entry." << endl << endl;
Sleep(3000);
cout << endl;
}
}
while (pattern != 5);
}
When you're printing the array:
for (int rows = 0; rows < dimensions; rows++)
{
for (int cols = 0; cols < dimensions; cols++)
cout << pat[cols][rows]
}
You never print a new line, so it's all on one row. You want something like this:
for (int rows = 0; rows < dimensions; rows++)
{
for (int cols = 0; cols < dimensions; cols++)
cout << pat[cols][rows]
cout << endl;
}
If you want to initialize a multidimensional array, you have to do it like so:
int multiarray[3][3] =
{
{1,2,3},
{4,5,6},
{7,8,9}
};
Using nested braces to separate the dimensions.
After this to output it the way you want you do it as such:
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
std::cout << multiarray[i][j];
}
std::cout << std::endl;
}