Beginner programmer. I have an assignment where I am to output numbers using loops. The input is the size of the output. The first assignment is to output the same #s vertically: For example. Input? 5. Output:
12345
12345
12345
12345
12345
My current code is incorrect but here is what I have:
int main(){
unsigned size;
cout <<"Size: ? ";
cin >>size;
cout <<"Numbers Vertically!" <<endl;
for ( unsigned r = 0; r < size; r++ ){
for ( unsigned c = 0; c < size; c++)
cout <<size;
cout <<endl;
}
cout <<endl;
}
You need to make two changes.
First is to actually read in the input using cin.
Second is to print c+1 in your inner loop instead of size.
Here is the code:
int main() {
unsigned size;
cout <<"Size: ? ";
cin >> size; // Read input size
cout <<"Numbers Vertically!" <<endl;
for ( unsigned r = 0; r < size; r++ ) {
for ( unsigned c = 0; c < size; c++) {
cout << c+1; // Print c+1 instead of size
}
cout <<endl;
}
cout <<endl;
}
Here is a running example
You're missing a 'cin >> size;' instruction.
I prefer this way.
#include <iostream>
using namespace std;
int main(){
unsigned size = 10;
unsigned n = size * size;
unsigned i = 1;
for (unsigned r = 0; r < n; r++ ){
cout << i % (size + 1);
if (i % (size + 1) == size) {
cout <<endl;
i = 1;
}
else {
i++;
}
}
cout <<endl;
return 0;
}
Related
I want to create an array of Bitset .Binary Bitset(example "100","1010",etc)
After that I want to input from user and store in the the Bitset .
I have tried the following line but it says error.
#include<bits/stdc++>
using namespace std;
int main()
{
int n,i;
string bit_string;
cin>>n // size of Bitset array.
bitset<8> brr[n];//
for(i=0;i<n;i++)
{
cin>>bit_string;
brr[i](bit_string);
}
return 0;
}
I want to create n Bitset each of size 8 bits.Where n is given by user.
my input is binary string like.
"110010","001110"
please help
The error ocurrs because you are trying to creat a C-style array using n which is not compile-time constant. It's not possible to creat a C-style array without being n known at compile time.
The following is a good way to do what you want
Creat a std::vector<std::bitset<8>> to hold your bitset<8>s, as follows.
Note that the code ignores the excess of characters in strings iput like "111111110" (makes it "11111111") and treats any character except '1' as if it were '0' and if the input string is less than 8 characters, the code adds zeros by the default of the bitsets
#include <vector>
#include <bitset>
#include <iostream>
int main() {
int n, i;
std::string bit_string;
std::cout << "Enter the size";
std::cin >> n; // size of Bitset array.
std::vector<std::bitset<8>> brr(n);//
for (i = 0; i < n; i++) {
std::cin >> bit_string;
for (int j{}; j < bit_string.size() && j < 8; ++j) {
brr[i][j] = (bit_string[j] == '1') ? 1 : 0;
}
}
//To test
for(auto const& el :brr)
{
for(int i{}; i < 8;)
std::cout << el[i++];
std::cout<<"\n";
}
}
See Why is "using namespace std;" considered bad practice?
and
Why should I not #include <bits/stdc++.h>?
For dynamic count of the objects , Please try vector<> instead of array[]
#include<bits/stdc++>
using namespace std;
int main()
{
int n, i;
string bit_string;
cin >> n; // size of Bitset array.
vector<bitset<8>> arr; //size()=>0
arr.resize(n); //size()=>n
for (i = 0; i < n; i++)
{
cin >> bit_string;
bitset<8>& br = arr[i]; //get the i of n
int maxlen = 8;
if (bit_string.size() <= 8)
maxlen = bit_string.size();
else
cout << "warning invalid len " << bit_string.size() << " of " << bit_string << endl;
for (int j = 0; j < maxlen; j++)
{
if (bit_string[j] == '1')
br.set(j, true);
}
//cout << endl << br << endl; //output test
}
return 0;
}
If you still want to use array , please try this way
#include<bits/stdc++>
using namespace std;
int main()
{
int n, i;
string bit_string;
cin >> n; // size of Bitset array.
bitset<8>* arr = new bitset<8>[n];
for (i = 0; i < n; i++)
{
cin >> bit_string;
bitset<8>& br = arr[i]; //get the i of n
int maxlen = 8;
if (bit_string.size() <= 8)
maxlen = bit_string.size();
else
cout << "warning invalid len " << bit_string.size() << " of " << bit_string << endl;
for (int j = 0; j < maxlen; j++)
{
if (bit_string[j] == '1')
br.set(j, true);
}
//cout << endl << br << endl; //output test
}
delete[] arr; //IMPROTAND , delete the array and free memory
return 0;
}
I make some program in C++ which in matrix finds longest horizontal line of 0s.
In first line I input n and m (rows and columns in matrix array a), and later array. Main problem is when I insert first line (all correct with it) the program stops with error -1073741510, line.exe has stopped working.
#include <iostream>
using namespace std;
int main()
{
int n, m;
cin >> n, m;
int a[n][m];
int i,j,k;
for (i=0;i<n;i=i+1){
for(j=0;j<m;j=j+1){
int temp;
cin >> temp;
a[i][j] = temp;
}
}
int max;
for (i=0;i<n;i++){
for(j=0;j<m;j++){
if(a[i][j]==0){
for(k=j+1;k<m;k++){
if(a[i][k]==0){
max++;
}else{break;}
}
}
}
}
cout << max;
return 0;
}
Sorry for big amount of for loops, I don't know better way of solving problem.
To read both numbers n and m use:
cin >> n >> m;
Otherwise, as you have cin >> n, m; it is equivalent with
cin >> n;
m; // This has no effect
For a solution to the correct operation of your algorithm, try this:
int maxZeros = 0;
int lineContainingMaxZeros = 0;
for (i = 0; i < n; i++) {
int countZero = 0;
for (j = 0; j < m; j++) {
if (a[i][j] == 0)
countZero++;
}
if (countZero > maxZeros) {
maxZeros = countZero;
lineContainingMaxZeros = i;
}
}
cout << "Line: " << lineContainingMaxZeros << " containing " << maxZeros << " zeros";
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
So my question is how to efficiently write a program where in we are able to take multiple inputs (the amount of inputs given is determined by the user) and then give the outputs at once. Lets consider a program which gives gives the sum of its digits. Eg - 12345 = 15.
//Single input single output
#include <iostream>
using namespace std;
int main()
{
int T, N;
cout << "Enter the value of T (No. of test cases)" << endl;
cin >> T;
cout << "Enter the value of N : " << endl;
while (T > 0)
{
cin >> N;
int ans = 0,temp1,temp2;
while(N!=0)
{
temp1= N %10;
N = (N - temp1)/10;
ans = ans + temp1;
}
cout << ans << endl;
T--;
}
return 0;
}
// Taking in all inputs then giving out all outputs ( Not working properly)
#include <iostream>
using namespace std;
int SumCal(int Number, int TestCase, int t);
int main()
{
int N, T;
cout << " Enter the value of T ( Total number of test cases) " << endl;
cin >> T;
int *Ans(new int[T]);
if (T >= 1 && T <= 1000)
{
cout << "Enter the value of N" << endl;
for (int i = 1; i <= T; i++)
{
cin >> N;
if (N >= 1 && N <= 100000)
Ans[i] = SumCal(N, i, T);
}
}
for (int z = 1; z <= T; z++)
{
cout << Ans[z] << endl;
}
delete[] Ans;
return 0;
}
int SumCal(int Number, int TestCase, int t)
{
int temp1, temp2 = 0;
int *AnsTemp(new int[t]);
temp1 = Number % 10;
temp2 = Number / 10;
if (temp2 < 10 && temp2 > 0)
AnsTemp[TestCase] = (temp1 + temp2);
while (temp2 > 10)
{
AnsTemp[TestCase] = (AnsTemp[TestCase] + temp1);
temp2 = temp2 / 10;
temp1 = temp1 % 10;
}
return AnsTemp[TestCase];
delete[] AnsTemp;
}
// This will work properly for multiple inputs multiple outputs
#include <iostream>
using namespace std;
int SumCal(int Number, int TestCase);
int main()
{
int N, T;
cout << " Enter the value of T ( Total number of test cases) " << endl;
cin >> T;
int Ans[1000] = {};
if (T >= 1 && T <= 1000)
{
cout << "Enter the value of N" << endl;
for (int i = 1; i <= T; i++)
{
cin >> N;
if (N >= 1 && N <= 100000)
Ans[i] = SumCal(N, i);
}
}
for (int z = 1; z <= T; z++)
{
cout << Ans[z] << endl;
}
return 0;
}
int SumCal(int Number, int TestCase)
{
int temp1, temp2 = 0;
int ans;
temp1 = Number % 10;
temp2 = Number / 10;
if (temp2 < 10 && temp2 > 0)
ans = (temp1 + temp2);
while (temp2 > 10)
{
ans = (ans + temp1);
temp2 = temp2 / 10;
temp1 = temp2 % 10;
}
return ans;
}
These are the codes I could think of. The first one is a simple one, which takes in an input and then gives out a output. In the second one I tried to use dynamic memory allocation but the program gives error. ( I know I haven't made proper use of * and & in it but I already tried using it in various manners and failed). The third program is successful but as we are setting up a large constraint value to the array, (i.e int Ans[1000]) it makes the program a bit inefficient.
So my question is how would one dynamically allocate memory during runtime successfully to take in multiple inputs and then give multiple outputs at once.
It's very hard to work with your code. I just took the 1st example, minimized the code and did what you should have done:
#include <iostream>
using std::cout;
using std::endl;
using std::cin;
int main()
{
int T;
cout << "Enter the value of T (No. of test cases)" << endl;
cin >> T;
int *buf = new int[T](); // buffer to hold the answers
for(int i = 0; i < T; ++i)
{
int N;
cout << "Enter the value of N : " << endl;
cin >> N;
while(N)
{
buf[i] += N % 10; // calculate on the buffer element
N /= 10;
}
}
for(int i = 0; i < T; ++i)
cout << buf[i] << endl; // print the buffer
delete [] buf; // delete buffer
return 0;
}
There's not much to do for managing the dynamically allocated array here, but take a look at std::vector and its uses.
I'm trying to write the code for a C++ program which will get some numbers (integers) and will put them into a 100 sized array, and will begin searching for possibly given negative ones (Negative of given positive numbers) after the user had inputted the sentinel number (101). For example; when we give the integers 1, 45, 12, -32, 103, 2015 and 32 to the program, it should give us the the integer 32 (because the negative form of it is existing) and if there were no numbers with this statement, then it will prints nothing. I wrote something like below; but I don't know how to do the rest... Any help or suggestions are appreciated.
I forgot to say that I use CodeBlocks 13.12 .
#include <iostream>
using namespace std;
int number = 0, nCounter = 0, sentinel = 101, i;
int myArray[100];
int main (){
cout << "Please enter your numbers: " << endl;
while ( number != 101 ){
cin >> number;
myArray[0]= number;
nCounter += 1;
}
for ( i = 0; i <= nCounter; i++ ){
if (myArray[i] > 0) // I'm stuck at here!
}
return 0;
}
Thanks and please apologize for possible English mistakes.
Here are some mistakes in the code :
First, you are assigning all the input elements to the 0th indexed element of the array.
The user can very well give 200 elements without typing 101, in that case you will overrun your array size.
A simple algorithm should be like this:
Pick the ith positive element and search through out the array for its negative.
Repeat 1 for every possible positive element in the array.
Here is a working example.
The input should be like this :
while ( (nCounter < 100) && (number != sentinel) ) {
std::cin >> number;
myArray[nCounter]= number;
nCounter += 1;
}
And the checking condition:
for ( i = 0; i < nCounter; i++ ){
if (myArray[i] > 0) {
for( j = 0; j < nCounter; j++) {
if(myArray[i] + myArray[j] == 0) // positive and negative add up to 0
std::cout << myArray[i] << std::endl ;
}
}
}
Here's a slight modification of your code that will get you what you need
#include <iostream>
using namespace std;
int number = 0, nCounter = 0, sentinel = 101, i, negMatch;
int myArray[100];
int main (){
cout << "Please enter your numbers: " << endl;
while ( number != 101 ){
cin >> number;
myArray[nCounter]= number;
nCounter += 1;
}
cout << "Enter the number to negative match";
cin >> negMatch;
for ( i = 0; i < nCounter; i++ ){
if ( (myArray[i] + negMatch) == 0) {
cout << myArray[i];
return 0;
}
}
return 0;
}
Please note the following changes:
You were inserting all the elements into the first slot, I changed it so that you enter them in the correct spot
Getting the number to be matched as input (negMatch is "32" in your question)
Modified the loop to check the numbers
However, this program is not ideal. Ideally, you would use something like Vectors, which can dynamically grow. Also, it might be better to have the user input the count of numbers, instead of using a sentinel number that he might want to give as input.
If I understand this correctly you want to print the negative ones but with positive sign. With this simple code you can do it!
#include <iostream>
using namespace std;
int number = 0, nCounter = 0, sentinel = 101;
int myArray[100];
int main (){
cout << "Please enter your numbers: " << endl;
while ( (nCounter < 100) && (number != sentinel) ) {
std::cin >> number;
myArray[nCounter]= number;
nCounter += 1;
}
for (int i = 0; i < nCounter; i++ ){
if (myArray[i] < 0) {
std::cout << (myArray[i] * -1) << std::endl ;
}
}
return 0;
}
A simple change that reduce the computational cost is the following: you can try to get information from the number given when you read it
#include <iostream>
#include <vector>
using namespace std;
int number = 0, sentinel = 101;
int main (){
cout << "Please enter your numbers: " << endl;
vector<int> array;
while (number != sentinel) {
std::cin >> number;
if(number < 0)
array.push_back(number);
}
for (int i = 0; i < array.size(); i++ )
std::cout << (array[i] * -1) << std::endl ;
return 0;
}
I suggest to write positive numbers in the beginning of the array and negative numbers in the end of the array.
Here is a demonstrative program
#include <iostream>
int main()
{
const size_t N = 100;
const int SENTINEL = 101;
int a[N];
int number;
size_t positive_end = 0;
size_t negative_begin = N;
for ( size_t i = 0; i < N && std::cin >> number && number != SENTINEL; i++ )
{
if ( number < 0 )
{
a[--negative_begin] = number;
}
else
{
a[positive_end++] = number;
}
}
if ( positive_end != 0 && negative_begin != N )
{
for ( size_t i = 0; i < positive_end; i++ )
{
size_t j = negative_begin;
while ( j != N && a[i] + a[j] != 0 ) ++j;
if ( j != N ) std::cout << a[i] << '\t' << a[j] << std::endl;
}
}
return 0;
}
If for example to enter the following sequence of numbers
1 2 -3 4 -5 6 7 3 -9 9 101
then the output will be
3 -3
9 -9
Also you could sort each part of the array (the part of positive numbers and the part of negative numbers) and apply standard algorithm std::set_intersection. In this case you could exclude situations when one negative number corresponds to several positive numbers.:)
You did not pay enough attention to the logic of your code. I'll assume you are very new at this, but no person will want to enter 100 inputs before they see what your program does.
Here is what's wrong with your code:
#include <iostream>
using namespace std;
int number = 0, nCounter = 0, sentinel = 101, i; // OK
int myArray[100]; // OK, an array with 100 elements
int main (){
cout << "Please enter your numbers: " << endl;
while ( number != 101 ){ //this is where you got it wrong
// this should have been nCounter instead of number
// If you are looking at 100 elements then the condition
// should be "nCounter != 100"
cin >> number;
myArray[0]= number; // this should have been "myArray [nCounter]=number;"
nCounter += 1;
}
for ( i = 0; i <= nCounter; i++ ){ // defining i from outer scope is unnecessary
// since it is only used in the for loop
if (myArray[i] > 0) // I'm stuck at here! // Put a semicolon here
// the remainder of the code probably here
}
return 0;
}
#include<iostream>
using namespace std;
int main()
{
//initialize size and empty array
int size = 10, x;
int myArray[10] = {};
//enter integers into array
for (int i = 0; i < size; i++)
{
cin >> myArray[i];
}
//search array for negative numbers
for (int i = 0; i < size; i++)
{
if (myArray[i] < 0)
{
x = (myArray[i] * (-1)); //multiply by -1 to get (+)
cout << x << ' ';
}
}
return 0;
}
I have a homework problem I'm having bit of a problem with, I'm asked to sort an array of C strings alphabetically using C++, sorting algo used must be bubble sort. What I've done so-far (replicated below) can sort the array but only based on the first alphabet. How do I further sort strings the strings with the same initial alphabet ?
<snipped>#arch:~/College/OOP/Lab/W3$ cat 2.cpp
/*
* Write a function which sorts an array of C strings in ascending order using bubble sort. The
* number of strings in the array and the array must be passed as parameters to the function
*/
#include <iostream>
#include <cstring>
using namespace std;
void sort(char **sar, unsigned num, unsigned len)
{
char *temp = new char[len];
if (temp == NULL)
{
cout << "\nOut-Of-Memory\n";
return;
}
for (unsigned a = 0; a < num-1; a++)
{
for (unsigned b = 0; b < ((num-a)-1); b++)
{
if (sar[b][0] > sar[b+1][0])
{
strcpy(temp, sar[b]);
strcpy(sar[b], sar[b+1]);
strcpy(sar[b+1], temp);
}
}
}
delete[] temp;
}
int main(int argc, char *argv[])
{
char **sar;
unsigned num;
unsigned len;
cout << "Number of Strings: ";
cin >> num;
cout << "Length of Strings: ";
cin >> len;
cin.ignore(); // Flush buffer to fix a bug (getline after cin).
sar = (char **) new char*[num];
if (sar == NULL)
{
cout << "\nOut-Of-Memory\n";
return -1;
}
for (unsigned i = 0; i < num; i++)
{
sar[i] = (char *) new char[len];
if (sar[i] == NULL)
{
// Let's pretend we 'know' memory management
// because obviously modern OSs are incapable
// of reclaiming heap from a quitting process..
for (unsigned j = 0; j < i; j++)
delete[] sar[j];
cout << "\nOut-Of-Memory\n";
return -1;
}
}
for (unsigned x = 0; x < num; x++)
cin.getline(&sar[x][0], 512);
sort(sar, num, len);
cout << '\n';
for (unsigned y = 0; y < num; y++)
cout << sar[y] << '\n';
for (unsigned z = 0; z < num; z++)
delete[] sar[z];
delete[] sar;
return 0;
}
change
if (sar[b][0] > sar[b+1][0])
to
if (stricmp(sar[b], sar[b+1]) > 0)
UPDATE: instead of stricmp, you can use strcasecmp