So I am a Beginner in C and I was going through Arrays and i was having success with arrays restricted to bounds of constant integers...
But i also wanted to find out what happens if we give in a random number for the Numbers of Rows and columns..
However when i executed the program all was fine until the 4th element wherein Vscode with display an error message of Matrix.exe(The compiled file) not working..
I somehow guessed that the error was with vscode itself..(i might be horribly wrong)
So i went for an online compiler and didnt get the desired result..which was received easily with bounded constant integers..
The code is about treating a two dimensional array as a Matrix and then getting the desired result in a table form i.e to get a print of all the elements in a tabular form.
I will post the code now:
`
#include<iostream>
using namespace std;
int main()
{
int m,n;
int matrix[m][n];
cout<<"Please give the number of Rows:";
cin>>m;
cout<<"Please give the number of columns:";
cin>>n;
for (int i=0;i<m;++i)
{
for (int j=0;j<n;++j)
{
cout<<"Please enter matrix element:";
cin>>matrix[i][j];
}
}
//printingmatrix
cout<<"The Matrix is:";
for (int a=0;a<m;a++)
{
for (int b=0;b<n;b++)
{
cout<<matrix[a][b]<< " ";
}
cout<<endl;
}
}`
I dont actually know what the problem is the code might be incorrect but seemed logically correct to me...
I actually dont have any idea of why i am not receiving the result!
Also this is my first stack ques so sorry if I sucked at asking! ;)
Any help will be appreciated!
Thanks!
int m,n;
int matrix[m][n];
There are two big problems here.
Problem 1: You don't give any value to m nor n. Then you use these ungiven values as the size of an array. C++ is not a "dataflow" language. If you use a value, the program won't stop, and wait for you to initialise the value later. If you use an uninitialised value, then the behaviour of the program will be undefined. There are exceptions, but none that apply to this case, so the behaviour of your program is undefined. That is something to avoid. Solution: Don't ever use uninitialised values.
Problem 2: The values that you later give are not compile time constant. The size of an array variable must be compile time constant in C++. The program is ill-formed. Solution: If you need an array with runtime size, then you must allocate it dynamically. The simplest solution is to use std::vector provided by the standard library.
So I am a Beginner in C
Note that C and C++ are two distinct languages.
In addition to #eerorika's answer, if you want to have a modern solution to your problem you can use std::vector<std::vector<int>> to have a dynamic 2d array.
A std::vector can be resized by simply calling .resize(n).
A std::vector stores the length, get it by calling .size()
An element inside a vector can be accessed via []
With this information, you can rewrite your code to look like this:
#include <iostream>
#include <vector>
int main() {
int m, n;
std::cout << "Please give the number of Rows: ";
std::cin >> m;
std::cout << "Please give the number of columns: ";
std::cin >> n;
std::vector<std::vector<int>> matrix;
matrix.resize(m);
for (int i = 0; i < matrix.size(); ++i) {
matrix[i].resize(n);
}
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
std::cout << "Please enter matrix element [" << i << ", " << j << "] : ";
std::cin >> matrix[i][j];
}
}
std::cout << "The Matrix is:\n";
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
std::cout << matrix[i][j] << " \t";
}
std::cout << '\n';
}
}
Example run:
Please give the number of Rows: 3
Please give the number of columns: 2
Please enter matrix element [0, 0] : 0
Please enter matrix element [0, 1] : 5
Please enter matrix element [1, 0] : -3
Please enter matrix element [1, 1] : 11
Please enter matrix element [2, 0] : 20
Please enter matrix element [2, 1] : 99
The Matrix is:
0 5
-3 11
20 99
You can read here why using namespace std; is considered bad practice.
Read about range-based for loop to learn more on how to use std::vector in a modern approach.
The problem with your original code is that C++ does not allow you to declare or initialize arrays with non-constant values for dimensions.
You can easily fix this issue if you use C++ STL vector as shown in the code below:
First, please note that you will need to include the header vector
Second, please see how I instantiate the vector matrix as a 2D array in the code. And, I also removed one line of your old code, and instead added the declaration for the vector matrix.
#include<iostream>
#include<vector> // This line must be added to use STL vector
using namespace std;
int main()
{
int m,n;
//int matrix[m][n]; // I removed this line
cout<<"Please give the number of Rows:";
cin>>m;
cout<<"Please give the number of columns:";
cin>>n;
vector<vector<int>> matrix(m, vector<int>(n, 0) ); // I added this line
for (int i=0;i<m;++i)
{
for (int j=0;j<n;++j)
{
cout<<"Please enter matrix element:";
cin>>matrix[i][j];
}
}
//printingmatrix
cout<<"The Matrix is:";
for (int a=0;a<m;a++)
{
for (int b=0;b<n; b++)
{
cout<<matrix[a][b]<< " ";
}
cout<<endl;
}
}
Note: I have tested and verified the code above run well. Please let me know if you have any issue.
Related
I'm a beginner in programming and as you can see, I created a program where the user is asked to input three numbers. It will display the greatest among the numbers given. But after I finished the code, a question came into my mind, what if the user was asked to input a hundreds of numbers and should display the greatest among the numbers given. So the question is, is it possible to do that? what are the things I need to learn to produce that result? is there any hints you can give me?
#include <iostream>
#include <string>
using std::cout, std::cin, std::endl, std::string;
int main() {
string result = " is the greatest among the numbers given";
double x, y, z;
cout<<"Enter three numbers to decide which is the largest: "<<endl;
cin >>x;
cin >>y;
cin >>z;
system("clear");
if(x>y && x>z){
cout<< x << result;
} else if (y>z && y>x){
cout << y << result;
} else
cout<< z << result;
return 0;
}
With the program below, you can get as many numbers as you want from the user and find the largest of them.
#include <iostream>
int main()
{
int size=0, largestValue=0, value=0;
std::cout << "Enter total numbers you want to add :" << "\n";
std::cin >> size;
for (int i{ 0 }; i < size; ++i)
{
std::cout << "Enter value to add : ";
std::cin >> value;
if (i == 0 || value > largestValue)
{
largestValue = value;
}
}
std::cout << "Largest value = " << largestValue << "\n";
return 0;
}
One solution would be to store your inputs in a list and sort them afterwards. Just google "sorting alorithms". Also there are nice youtube visualizations.
Another one would be to not save the inputs into dedicated variables - in your case x, y, z - but to always save the largest given input:
int largestInput = std::numeric_limits<int>::min();
int input;
for (int i = 0; i < 10000; i++)
{
std::cin >> input;
largestInput = input > largestInput ? input : largestInput;
}
If you know the inputs are large, you can use vectors.
#include <bits/stdc++.h>
using namespace std;
int main(){
int total_num=0;
cout << "Enter total numbers:" << "\n";
cin>>total_num;
int max_number = INT_MIN;
vector<int> v;
for(int i=0;i<total_num;i++){
int x;
cin>>x;
v.push_back(x);
max_number = max(max_number,x);
}
cout<<"Maximum number present: "<< max_number<<endl;
return 0;
}
Although there is no need to store numbers. But it's your choice if you need it later you can use it in that program.
> what are the things I need to learn
what if the user was asked to input a hundreds of numbers
For this, you'll need to learn about arrays. I suggest you first learn about C-style arrays (int x[3]{};), and then std::array (std::array<int, 3> x{};). You also need to learn about loops.
and should display the greatest among the numbers given
Having to find the largest number in an array is very common. If you want to learn how to do so manually, the other answers here should answer your question. Otherwise, look towards the standard library algorithms std::ranges::max() (C++20) and std::max_element.
Examples
Example 1
Here's a program that uses a C-style array and a simple algorithm to get the largest number:
#include <iostream>
int main(){
// Amount of numbers user should input
constexpr int count{ 3 };
std::cout << "Enter " << count
<< " numbers to decide which is the largest:\n";
// The numbers entered by the user
double numbers[count]{}; // Declare and zero-initialize a C-style array of 3 ints
// Get each number from the user and put it in the array
for (int i{ 0 }; i < count; ++i) {
std::cin >> numbers[i];
}
// The biggest number found so far
int max{ numbers[0] }; // Initialize it with the first number
for (int i{ 1 }; i < count; ++i) { // Start at the second element (element 1)
if (numbers[i] > max) { // If the current number is larger than max...
max = numbers[i]; // ...assign it to max
}
}
std::cout << max << " is the greatest among the numbers given\n";
return 0;
}
Note:
int numbers[count]{};
This creates a C-style array called numbers which has count (3) elements. The first element's "index" is 0 and the last element's is 2. The {} initializes the values of all of the numbers to 0 (good practice).
for (int i{ 0 }; i < count; ++i)
std::cin >> numbers[i];
This loops until i isn't less than count (3) and increments i (++i) each time. It starts at 0, so it loops 3 (0 1 2) times. On each iteration, it gets a number from the console and stores it in numbers[i].
Example 2
Here's a shorter program that uses the standard library:
#include <algorithm> // ranges::max()
#include <array> // array<>
#include <iostream> // cin, cout
int main() {
// Amount of numbers user should input
constexpr int count{ 3 };
std::cout << "Enter "
<< count
<< " numbers to decide which is the largest:\n";
std::array<double, count> numbers{}; // Declare an array of 3 ints
for (int i{ 0 }; i < count; ++i) {
std::cin >> numbers[i];
}
// Return the largest number in array "numbers"
std::cout << std::ranges::max(numbers)
<< " is the greatest among the numbers given\n";
return 0;
}
Note:
std::array<int, count> numbers{};
Declares an array of count (3) ints and zero-initializes it.
std::ranges::max(numbers)
This neat function finds the largest number in numbers. It was added in C++20 -- if you're using an older compiler, you should use *std::max_element(numbers.begin(), numbers.end()). If you want to learn how the latter works, you need to learn about iterators and pointers.
Here are some good practices that your tutorial hasn't taught you yet (if it ever will):
DON'T use using namespace std. It's unsafe because it brings everything in the standard library into global scope. The standard library contains a lot of commonly used identifiers like count and list. Bringing these into global scope is dangerous because it can cause naming conflicts.
Don't use copy initialization (int x = 3). Use uniform/brace/list initialization instead (int x{ 3 }). The former sometimes makes an unnecessary copy, whereas the latter doesn't. The latter also refuses to do narrowing conversions (e.g. initializing a short with a long).
Always initialize variables (do: int x{}, don't: int x), even when it seems redundant. If you don't, then the value stored is undefined - it could be anything. Undefined behaviour is hard to debug but luckily easy to avoid.
Use \n instead of std::endl. Both do the same, except std::endl does an extra buffer flush which is slow and unnecessary. \n is shorter anyways.
DRY -- Don't Repeat Yourself. You have the string " is the greatest among the numbers given" three times in your code. You could have stored it in a std::string instead -- then it wouldn't have repeated.
Repeating code is bad, because:
It's harder to read
It's harder to maintain (you would have to modify it everywhere it's repeated)
Maintenance is more error-prone
If I were you, I'd immediately find a different tutorial/book. See this thread.
#include <stdio.h>
int main()
{
int num1, num2, num3, num4;
printf("Enter num1\n");
scanf("%d",&num1);
printf("Enter num2\n");
scanf("%d",&num2);
printf("Enter num3\n");
scanf("%d",&num3);
printf("Enter num4\n");
scanf("%d",&num4);
if(num1>num2 && num1>num3 && num1>num4){
printf("greatest number is %d",num1);
}
if(num2>num3 && num2>num1 && num2>num4){
printf("greatest number is %d",num2);
}
if(num3>num1 && num3>num2 && num3>num4){
printf("greatest number is %d",num3);
}
if(num4>num1 && num4>num2 && num4>num3){
printf("greatest number is %d",num4);
}
return 0;
}
I have following piece of code,
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int input,n;
cin >> n;
vector<int> v(n);
for(int i=0;i<n;i++){
cin>>input;
v.push_back(input);
}
for(int i=0; i<v.size();i++){
cout << v[i] << endl;
}
cout << v.size() << endl;
return 0;
}
and
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int input,n;
vector<int> v(n);
cin >> n;
for(int i=0;i<n;i++){
cin>>input;
v.push_back(input);
}
for(int i=0; i<v.size();i++){
cout << v[i] << endl;
}
cout << v.size() << endl;
return 0;
}
for the following input, n=5, 1 2 3 4 5 , first program gives the output
0
0
0
0
0
1
2
3
4
5
10
and the second program gives the result
1
2
3
4
5
5
I donot understand why vector is initializing 0's in the first doubling the size but not in the second
Actually, neither of those are correct for what you want (I'm assuming here you want the five elements you input and nothing more - that may be an invalid assumption but it seems like a good bet to me).
In your first one, you have (comments added to explain what's happening):
int input,n; // n has arbitrary value.
cin >> n; // overwritten with 5.
vector<int> v(n); // initial vector has five zeros.
This means your vector will be created with five (assuming you input that for n) default-constructed entries. Then you go and insert five more, which is why you get five zeros followed by your actual data.
Your second one has:
int input,n; // n has arbitrary value.
vector<int> v(n); // initial vector of that arbitrary value (probably).
cin >> n; // overwritten with five but it's too late anyway.
This is actually undefined behaviour since you have no idea what n will be when you create a vector of that size. In your case, it appears to be zero but that's just a lucky coincidence.
Note the use of the word "probably" above. While it's likely that the vector will be created with some arbitrary number of entries, undefined behaviour means exactly that - you should not rely on it at all. By rights, it could quite easily delete all your files while playing derisive_laughter.wav through your sound system :-)
The most likely case however will be one of:
it'll work as you thought, because n is zero;
it'll have some arbitrary number of zeros at the start, similar to your first code snippet;
it'll cause an out-of-memory exception because n is ridiculously large; or
it'll cause an exception because n is negative.
In any case, you should generally either pre-allocate and just set the already-existing values:
vector<int> v(2);
v[0] = 7;
v[1] = 42;
or not pre-allocate, using push_back to expand the vector on demand:
vector<int> v;
v.push_back(7);
v.push_back(42);
Hope, one can write the 1st case of writing program in the question in the following way to get correct result
1
2
3
4
5
5
for the input given as in the question
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int n;
cin>>n;
vector<int> v(n);
for(int i=0;i<n;i++){
cin>>v.at(i);
}
for(int i=0;i<v.size();i++){
cout << v[i] << endl;
}
cout << v.size() << endl;
return 0;
}
I am a beginner and I would like to ask you something.
We have an array whose size depends on value input by user in a variable ‘arraysize’. Look at below code and comments please, is it a correct way to achieve this said be behaviour?
int * myArray = NULL;
int arraySize;
cout << "Enter array size: ";
cin >> arraySize;
myArray = new int[arraySize];
delete [] myArray;
The earlier answer was a community wiki. Since you asked for an example, here's a more detailed answer.
A std::vector is a class belonging to the standard template library read in detail.
//since you used "using namespace std;" I'm omitting the "std::"
Declaration
vector< int > v; //creates a vector of integers
vector< double > vd; //vector of double values
This is quite similar to int a[/*any number*/].
Inserting values
v.push_back(5); //adds 5 to the end of the vector (or array of variable size)
With the above two lines you dont need to know in advance how many numbers you'll have to store.
One more sample code.
#include <iostream>
#include <vector>
int main ()
{
std::vector<int> myvector;
int myint;
std::cout << "Please enter some integers (enter 0 to end):\n";
do {
std::cin >> myint;
myvector.push_back (myint);
} while (myint);
std::cout << "myvector stores " << int(myvector.size()) << " numbers.\n";
return 0;
}
This program reads values and saves to myvector till 0 is entered in input.
Iteration
std::vector<int>::size_type sz = myvector.size(); //even int works here
// assign some values:
for (unsigned int i=0; i<sz; i++) myvector[i]=i;
Deletion
v.pop_back(); //removes last element
Use std::vector as a C++ best practice.
so i wrote this code in c++ to solve this equation (x+y+z=30) where each of these variables has a limited amount of possible of values (1,3,5,7,9,11,13,15) so repetition is allowed and here's my code :
#include <iostream>
using namespace std;
int main()
{
int x[8]={1,3,5,7,9,11,13,15};
int y[8]={1,3,5,7,9,11,13,15};
int z[8]={1,3,5,7,9,11,13,15};
for (int i=0; i<8; i++)
{
for (int j=0; j<8; j++)
{
for (int k=0; k<8; j++)
{
if (x[i]+y[j]+z[k]==30)
{
cout << x[i] << "\n" << y[j] << "\n" << z[k]<< "\n"<< endl;
break;
}
}
}
}
}
now i don't know if this is the right way to approach it (I'm a beginner) but still this program did okay since it gave set of three number that did equal to 30 but it didn't stick to the possible values e.g (7,22,1), now that what you see their is the best i could come up with other attempts or fixes just made things worse e.g crashing or what so ever.
if you could help that would be great and most importantly tell me where i went wrong as this whole purpose of this is to learn not solve the problem.
thank you so much in advance !
You are using break statement which only breaks one of the loops. You have nested loops in your program, so i would recommend you to use goto: instead.
for (int i=0; i<8; i++)
{
for (int j=0; j<8; j++)
{
for (int k=0; k<8; j++)<----- it should be k++
{
if (x[i]+y[j]+z[k]==30)
{
goto stop;
}
}
}
}
stop:
cout << x[i] << "\n" << y[j] << "\n" << z[k]<< "\n"<< endl;
I actually ran the code and there is 2 more problems:
As mentioned on the answer below, it 3 odd numbers never add up to 30;
variables i , j and k need to be global variables. So initialize them before using in loops. Then it should work perfectly(if the number isn't even).
I don't see 22 in the values you initialized the arrays with. You also can just use one array with the possible values; 3 arrays are not needed.
I see that you only have odd integers as possible values. 3 odd integers can never sum up to an even integer like 30, so there is no solution to your problem as stated. The one solution you provided has 22 as one value, an even integer.
Write a program to input a series of 12 integers from the keyboard and store them in a one-dimensional array, x[12], then displayed them on the computer screen in reverse order.
I have a basic understanding that:
My numbers in the array will go from {0 to 11}
I am using a for loop (which I don't currently know how to do)
Now... How do I write this program?
You would do this:
loop from 0 to 11 using a for loop (for(size_t i = 0; i < 12; i++))
for each i, std::cin into the item at index i std::cin >> array[i];
To print them out you can use a while loop with i--. It will stop when i is zero and it will be backwards.
Because this is a homework question, I won't give you the full code but I hope this answer helps.
Learn about loops: while for do, while etcetera and you just might find the solution that you have been looking for
Example:
for(i = 0; i < 10; i++){
cout << i;
}
Since you know the quantity of numbers, you could insert them into the array in reverse order:
cin >> x[11]; cin >> x[10]; cin >> x[09]; //...
Next you would display the array in normal order:
cout << x[0]; cout << x[1]; cin << x[02]; //...
Since I didn't use a for loop, that's not going to help, is it?
The key concept is the 3rd parameter of the for loop, which can control the direction of a loop.
Let us investigate some examples:
for (unsigned int i = 0; i < 10; i += 2) {cout << i << endl; }
The above loop skips items because the variable is incremented by 2. That is 2 is added to index variable. This shows that loops don't always have to use ++.
So, what would happen if the index were set to the end value and then subtracted each time?
for (int i = 10; i >= 0; i -= 2) {cout << i << endl;}
This is for you to figure out.
Now, you will need to either ask questions in class, ask the professor after class or get a book that you will read and can understand easily (in addition to the one you have).