User input into array. I am confused with output - c++

Most of the components for the array are in place.
I am however wondering what code is missing for the output to match what I am trying to do.
I tried searching for similar array coding. I would like to call the function and for the user to input numbers up to 20 different inputs.
#define size 20
using namespace std;
int i;
void Input(int student[]) {
for(int i = 0; i < size; i++)
cout << "Enter The Marks of Subject 2 of student no " << i + 1 << " ";
cin >> student[i];
}
void display(int student[]) {
for(int i = 0; i < size; i++)
cout << student[i];
}
int main() {
int student[size];
Input(student );
display(student);
return 0;

In your Input function:
void Input(int student[]) {
for(int i = 0; i < size; i++)
cout << "Enter The Marks of Subject 2 of student no " << i + 1 << " ";
cin >> student[i];
}
You not using brackets, so the cin >> student[i]; is outside of the loop. The i from the for loop is no longer in scope, so you are using the i here:
int i;
Which is never given a value, which leads to undefined behavior. Add brackets:
void Input(int student[]) {
for(int i = 0; i < size; i++) {
cout << "Enter The Marks of Subject 2 of student no " << i + 1 << " ";
cin >> student[i];
}
}

Related

How to make an array reject a duplicate as the user inputs them

I have to ask the user to put in an array size and then to ask the user to fill it out. When the user puts in a duplicate, the program should say "invalid" and the user is asked to replace the number. I am supposed to use traversing array search.
Like this example here:
Enter list size: 4
Enter value for index 0: 1
Enter value for index 1: 1
Invalid. Enter a new number: 2
Enter value for index 2: 5
Enter value for index 3: 6
This is my code so far:
#include <iostream>
using namespace std;
int main() {
int size;
cout << "Enter list size: ";
cin >> size;
int array1[size];
for (int i = 0; i < size; i++) {
cout << "Enter value for index " << i << ": ";
cin >> array1[i];
for (int j = i + 1; j < size; j++) {
if (array1[i] == array1[j]) {
cout << "Invalid! Enter a new value for index " << i << ": ";
cin >> array1[i];
}
}
}
return 0;
}
It does what was specified but the exercise probably was to write std::ranges::find.
#include <iostream>
#include <vector>
#include <cstddef>
#include <algorithm>
int main() {
size_t size;
std::cout << "Enter list size: ";
std::cin >> size;
std::vector<int> arr;
arr.reserve(size);
while(arr.size() < size) {
int t;
std::cout << "Enter value for index " << arr.size() + 1 << ": ";
std::cin >> t;
if (std::ranges::find(arr, t) == arr.end()) {
arr.push_back(t);
} else {
std::cout << "Invalid! ";
}
}
}
Try this approach, Every time user enter value helper function will check duplicate from already filled array
#include<iostream>
// Helper Function that will check duplicate from array
bool IsDuplicate (int arr[] ,const int idxSoFar, int element){
for(int i =0 ; i < idxSoFar ; i += 1 )
if( arr[i] == element){
std::cout << "Invalid! Enter a new value for index "<< idxSoFar + 1 << " : ";
return arr[i] == element;
}
return false;
}
int main () {
int size;
std::cout << "Enter list size: ";
std::cin >> size;
int array1[size];
for (int i = 0; i < size; i++) {
std::cout << "Enter value for index " << i << ": ";
do
std::cin >> array1[i];
while(IsDuplicate(array1 , i , array1[i]));
}
return 0;
}

array elements not printing when trying to print in the main function

I want to find the factors of a product by using arrays to check whether they equal it or not
the values do not print
here is the code
#include <iostream>
using namespace std;
int main() {
int arr[5] = { 1,3,5,7,2 };
int arr1[5] = { 0,6,5,4,9 };
int X;
cout << "Please enter X:"; cin >> X;
for (int i = 0, j = 0; i < 5 && j < 5; ++i, ++j) {
if (arr[i]*arr[j]==X) {
cout << arr[i] << " ";
cout << arr1[j] << " ";
}
}
}
Use this nested loops
for (int i = 0; i < 5 ;++i) {
for(int j=0 ;j<5;++j){
if (arr[i]*arr1[j]==X) {
cout << arr[i] << " ";
cout << arr1[j] << " ";
}
}
}

How to input string array from the structure in this case?

So, I am beginner. I have this code and a few problems. For better understanding, you will need this code:
struct student
{
double marks;
char name[50];
}stud[100],t;
int main()
{
int i,j,n;
cout<<"Enter the number of students: ";
cin>>n;
cout<<"Enter student info as name , marks\n";
for(i=0;i<n;i++)
{
cin>>stud[i].name;
cin>>stud[i].marks;
}
The problem is, instead of this part:
struct student
{
double marks;
char name[50];
}stud[100],t;
There should be this part:
struct student
{
double marks[];
string name[];
}stud[100],t;
But then I don't know how to enter that data into the program because then the cin >> doesn't work.
Task says that when the user enters ' ' (ENTER), the program should finish and show the students print in order.
The marks and name array are dynamic and they are called flexible array members and they are not supported in cpp u can refer to this link Are flexible array members valid in C++? and moreover they are supported in c and u can have atmost one flexible array member and it should be at end
https://www.geeksforgeeks.org/flexible-array-members-structure-c/
I believe this is close to what you want:
//10 marks by students
int m = 10;
struct student
{
double marks[m];
string name;
}stud[100],t;
int main()
{
int i,j,n;
cout<<"Enter the number of students: ";
cin>>n;
for(i=0;i<n;i++)
{
cout<<"Enter student info as name\n";
cin>>stud[i].name;
for(int j=0; j<m; ++j)
{
cout<<"Enter student marks "<<j+1<<endl;
cin>>stud[i].marks[j];
}
}
}
You'll need a second loop. I added constants -- this is good practice so you don't have "magic numbers" in your code. I added a display function to demonstrate that it works!
#include <iostream>
using namespace std;
const int MAX_MARKS = 25;
const int MAX_STR = 50;
const int MAX_STUDENTS = 100;
struct student
{
double marks[MAX_MARKS];
char name[MAX_STR];
}stud[MAX_STUDENTS],t;
int main()
{
int i,j,n;
bool complete = false;
cout<<"Enter the number of students: ";
cin>>n;
for(i=0; i < n && i < MAX_STUDENTS; ++i)
{
complete = false;
cout<<"Enter student info as name , marks\n";
cin>>stud[i].name;
for (j = 0; j < MAX_MARKS; ++j)
{
if (!complete)
{
cout << "Enter mark #" << j+1 << ": ";
if (!(cin >> stud[i].marks[j]))
{
complete = true;
stud[i].marks[j] = -1.0;
cin.clear();
cin.ignore(100, '\n');
}
}
else
stud[i].marks[j] = -1.0; //0.0 is a valid grade so need a different value
}
}
//Added a block for displaying the students
for (i = 0; i < MAX_STUDENTS && i < n; ++i)
{
complete = false;
cout << "Student #" << i+1 << ": " << stud[i].name << endl;
for (j = 0; j < MAX_MARKS && !complete; ++j)
{
if (stud[i].marks[j] == -1.0)
complete = true;
else
cout << "\tMark #" << j+1 << ": " << stud[i].marks[j] << endl;
}
}
}

Using for loops to enter data into arrays

So I have this C++ program that contains .h file and main.cpp. In .h I have this class:
class Plaza
{
public:
int length;
double x;
double y;
Plaza();
~Plaza();
};
In main.cpp, I am trying to enter the data using for loop, and I manage to store data for int i = 0 state, but when i is increased, no data that has been entered is being stored into array. For the inside loop, I tried to put j < n, j < n-1 and j < n+1, but it's not working. How can I store all the data and print it out?
#include <iostream>
#include "Plaza.h"
using namespace std;
int main() {
int n;
Plaza *obj1;
cout << "Enter limit number (N): ";
cin >> n;
obj1 = new Plaza[n];
for (int i = 0; i < n; i++) {
cout << "Enter length, x and y for " << i + 1 << ". plaza: " << endl;
for (int j = 0; j < 1; j++) {
cin >> obj1[j].length;
cin >> obj1[j].x >> obj1[j].y;
}
}
for (int i = 0; i < n; i++) {
cout << i + 1 << ". " << obj1[i].x << " " << obj1[i].y << " Length=" << obj1[i].length;
}
delete[] obj1;
system("pause");
return 0;
}
This is the print I get:
for (int i = 0; i < n; i++) {
cout << "Enter length, x and y for " << i + 1 << ". plaza: " << endl;
for (int j = 0; j < 1; j++) {
cin >> obj1[j].length;
cin >> obj1[j].x >> obj1[j].y;
}
}
Here's your culprit. Get rid of the inner for-loop (not the cin-statements, just the for... line and its closing bracket) and replace obj[j] with obj[i]. You are currently repeatedly writing to obj[0].
for (int i = 0; i < n; i++) {
cout << "Enter length, x and y for " << i + 1 << ". plaza: " << endl;
for (int j = 0; j < 1; j++) {
cin >> obj1[j].length;
cin >> obj1[j].x >> obj1[j].y;
}
}
Why there is a need of second for loop., if you check the j value, it is always 0 so only one value is inserted.,
try this
for (int i = 0; i < n; i++) {
cout << "Enter length, x and y for " << i + 1 << ". plaza: " << endl;
cin >> obj1[i].length;
cin >> obj1[i].x >> obj1[i].y;
}
}

Passing 2D array to a Function in c++

I am Having Problem with Passing a 2D array to a c++ Function. The function is supposed to print the value of 2D array. But getting errors.
In function void showAttributeUsage(int)
Invalid types for int(int) for array subscript.
I know the problem is with the syntax in which I am passing the particular array to function but I don't know how to have this particular problem solved.
Code:
#include <iostream>
using namespace std;
void showAttributeUsage(int);
int main()
{
int qN, aN;
cout << "Enter Number of Queries : ";
cin >> qN;
cout << "\nEnter Number of Attributes : ";
cin >> aN;
int attVal[qN][aN];
cout << "\nEnter Attribute Usage Values" << endl;
for(int n = 0; n < qN; n++) { //for looping in queries
cout << "\n\n***************** COLUMN " << n + 1 << " *******************\n\n";
for(int i = 0; i < aN; i++) { //for looping in Attributes
LOOP1:
cout << "Use(Q" << n + 1 << " , " << "A" << i + 1 << ") = ";
cin >> attVal[n][i];
cout << endl;
if((attVal[n][i] > 1) || (attVal[n][i] < 0)) {
cout << "\n\nTHE VALUE MUST BE 1 or 0 . Please Re-Enter The Values\n\n";
goto LOOP1; //if wrong input value
}
}
}
showAttributeUsage(attVal[qN][aN]);
cout << "\n\nYOUR ATTRIBUTE USAGE MATRIX IS\n\n";
getch();
return 0;
}
void showAttributeUsage(int att)
{
int n = 0, i = 0;
while(n != '\0') {
while(i != '\0') {
cout << att[n][i] << " ";
i++;
}
cout << endl;
n++;
}
}
I really suggest to use std::vector : live example
void showAttributeUsage(const std::vector<std::vector<int>>& att)
{
for (std::size_t n = 0; n != att.size(); ++n) {
for (std::size_t i = 0; i != att.size(); ++i) {
cout << att[n][i] << " ";
}
cout << endl;
}
}
And call it that way:
showAttributeUsage(attVal);
Looking at your code, I see no reason why you can't use std::vector.
First, your code uses a non-standard C++ extension, namely Variable Length Arrays (VLA). If your goal is to write standard C++ code, what you wrote is not valid standard C++.
Second, your initial attempt of passing an int is wrong, but if you were to use vector, your attempt at passing an int will look almost identical if you used vector.
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
typedef std::vector<int> IntArray;
typedef std::vector<IntArray> IntArray2D;
using namespace std;
void showAttributeUsage(const IntArray2D&);
int main()
{
int qN, aN;
cout << "Enter Number of Queries : ";
cin >> qN;
cout << "\nEnter Number of Attributes : ";
cin >> aN;
IntArray2D attVal(qN, IntArray(aN));
//... Input left out ...
showAttributeUsage(attVal);
return 0;
}
void showAttributeUsage(const IntArray2D& att)
{
for_each(att.begin(), att.end(),
[](const IntArray& ia) {std::copy(ia.begin(), ia.end(), ostream_iterator<int>(cout, " ")); cout << endl;});
}
I left out the input part of the code. The vector uses [] just like a regular array, so no code has to be rewritten once you declare the vector. You can use the code given to you in the other answer by molbdnilo for inputing the data (without using the goto).
Second, just to throw it into the mix, the showAttributeUsage function uses the copy algorithm to output the information. The for_each goes throw each row of the vector, calling std::copy for the row of elements. If you are using a C++11 compliant compiler, the above should compile.
You should declare the function like this.
void array_function(int m, int n, float a[m][n])
{
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
a[i][j] = 0.0;
}
where you pass in the dimensions of array.
This question has already been answered here. You need to use pointers or templates. Other solutions exists too.
In short do something like this:
template <size_t rows, size_t cols>
void showAttributeUsage(int (&array)[rows][cols])
{
for (size_t i = 0; i < rows; ++i)
{
std::cout << i << ": ";
for (size_t j = 0; j < cols; ++j)
std::cout << array[i][j] << '\t';
std::cout << std::endl;
}
}
You're using a compiler extension that lets you declare arrays with a size determined at runtime.
There is no way to pass a 2D array with such dimensions to a function, since all but one dimension for an array as a function parameter must be known at compile time.
You can use fixed dimensions and use the values read as limits that you pass to the function:
const int max_queries = 100;
const int max_attributes = 100;
void showAttributeUsage(int array[max_queries][max_attributes], int queries, int attributes);
int main()
{
int attVal[max_queries][max_attributes];
int qN = 0;
int aN = 0;
cout << "Enter Number of Queries (<= 100) : ";
cin >> qN;
cout << "\nEnter Number of Attributes (<= 100) : ";
cin >> aN;
cout << "\nEnter Attribute Usage Values" << endl;
for (int n = 0; n < qN; n++)
{
cout << "\n\n***************** COLUMN " << n + 1 <<" *******************\n\n";
for (int i = 0; i < aN; i++)
{
bool bad_input = true;
while (bad_input)
{
bad_input = false; // Assume that input will be correct this time.
cout << "Use(Q" << n + 1 << " , " << "A" << i + 1 << ") = ";
cin >> attVal[n][i];
cout << endl;
if (attVal[n][i] > 1 || attVal[n][i] < 0)
{
cout << "\n\nTHE VALUE MUST BE 1 or 0 . Please Re-Enter The Values\n\n";
bad_input = true;
}
}
}
}
cout << "\n\nYOUR ATTRIBUTE USAGE MATRIX IS\n\n";
showAttributeUsage(attVal, qN, aN);
getch();
return 0;
}
void showAttributeUsage(int att[max_queries][max_attributes], int queries, int attributes)
{
for (int i = 0; i < queries; i++)
{
for (int j = 0; j < attributes; j++)
{
cout << att[i][j] << " ";
}
cout << endl;
}
}
For comparison, the same program using std::vector, which is almost identical but with no size limitations:
void showAttributeUsage(vector<vector<int> > att);
int main()
{
cout << "Enter Number of Queries (<= 100) : ";
cin >> qN;
cout << "\nEnter Number of Attributes (<= 100) : ";
cin >> aN;
vector<vector<int> > attVal(qN, vector<int>(aN));
cout << "\nEnter Attribute Usage Values"<<endl;
for (int n = 0; n < qN; n++)
{
cout<<"\n\n***************** COLUMN "<<n+1<<" *******************\n\n";
for (int i = 0; i < aN; i++)
{
bool bad = true;
while (bad)
{
bad = false;
cout << "Use(Q" << n + 1 << " , " << "A" << i + 1 << ") = ";
cin >> attVal[n][i];
cout << endl;
if (attVal[n][i] > 1 || attVal[n][i] < 0)
{
cout << "\n\nTHE VALUE MUST BE 1 or 0 . Please Re-Enter The Values\n\n";
bad = true;
}
}
}
}
cout << "\n\nYOUR ATTRIBUTE USAGE MATRIX IS\n\n";
showAttributeUsage(attVal);
getch();
return 0;
}
void showAttributeUsage(vector<vector<int> > att);
{
for (int i = 0; i < att.size(); i++)
{
for (int j = 0; j < att[i].size(); j++)
{
cout << att[i][j] << " ";
}
cout << endl;
}
}
The Particular Logic worked for me. At last found it. :-)
int** create2dArray(int rows, int cols) {
int** array = new int*[rows];
for (int row=0; row<rows; row++) {
array[row] = new int[cols];
}
return array;
}
void delete2dArray(int **ar, int rows, int cols) {
for (int row=0; row<rows; row++) {
delete [] ar[row];
}
delete [] ar;
}
void loadDefault(int **ar, int rows, int cols) {
int a = 0;
for (int row=0; row<rows; row++) {
for (int col=0; col<cols; col++) {
ar[row][col] = a++;
}
}
}
void print(int **ar, int rows, int cols) {
for (int row=0; row<rows; row++) {
for (int col=0; col<cols; col++) {
cout << " | " << ar[row][col];
}
cout << " | " << endl;
}
}
int main () {
int rows = 0;
int cols = 0;
cout<<"ENTER NUMBER OF ROWS:\t";cin>>rows;
cout<<"\nENTER NUMBER OF COLUMNS:\t";cin>>cols;
cout<<"\n\n";
int** a = create2dArray(rows, cols);
loadDefault(a, rows, cols);
print(a, rows, cols);
delete2dArray(a, rows, cols);
getch();
return 0;
}
if its c++ then you can use a templete that would work with any number of dimensions
template<typename T>
void func(T& v)
{
// code here
}
int main()
{
int arr[][7] = {
{1,2,3,4,5,6,7},
{1,2,3,4,5,6,7}
};
func(arr);
char triplestring[][2][5] = {
{
"str1",
"str2"
},
{
"str3",
"str4"
}
};
func(triplestring);
return 0;
}