how to print out x amount of results per line - c++

For this code I created that outputs the ASCII characters corresponding to ints, I need to print out 16 ASCIIs per line. How would I go about doing so? I'm not sure how to approach these? Do I create another for loop inside?
int main()
{
int x = 0;
for (int i = 0; i <= 127; i++)
{
int x = i;
char y = (char) x;
cout << y;
}
return 0;
}
Or should I put the cout outside with 16 separate lines? I am trying to print 17 ASCIIs starting from 1 in a row.

Use another variable that counts up along with i. When it reaches 16, reset it and print a new line. Repeat until the loop terminates.
i.e.(I may be off by one here, I didn't think about it too deeply)
for (int i=0, j=1; i<=127; i++,j++)
{
int x = i;
char y = (char) x;
cout << y;
if (j == 16) {
j = 0;
cout << '\n';
}
}
Alternatively, you could just check if (i % 16 == 0)

You don't need another variable to track it. i is already an int.
so if i modulo 16 equals 0 then print a newline
else print (char)i
EDIT:
Note, using variables like i is ok for simple iteration but its always good practice to name them better.
So think about how changing i to ascii in your program improves the readability. It instantly makes it even more clear what is it that you are trying to do here.

int main()
{
int charsThisLine =0;
for (int currentChar=0; currentChar<128; currentChar++)
{
if(charsThisLine==16)
{
cout<<endl;
charsThisLine = 0;
}
else
{
cout<<(char)currentChar;
charsThisLine++;
}
}
}

How about:
#include <iostream>
int main()
{
for(int i = 0, j = 0; i < 128; ++i, ++j)
{
if(j == 16)
{
j = 0;
std::cout << std::endl;
}
std::cout << static_cast<char>(i);
}
return 0;
}
Every iteration, j increases by 1; after 16 iterations, j is reset to 0, and a newline is printed.
Alternatively, as #Sujoy points out, you could use:
if((i % 16) == 0)
std::cout << std::endl;
But this introduces the problem of printing an extra newline character at the beginning of the output.

Yes, you need a second loop inside the first. (I misunderstood what is being requested.)
You also need to clean up the code. The first x is unused; the second x isn't needed since you could perfectly well use char y = (char)i; (and the cast is optional). You should normally use a loop for (int i = 0; i < 128; i++) with a < condition rather than <=.
You will also need to generate a newline somewhere (cout << endl; or cout << '\n';). Will you be needing to deal with control characters such as '\n' and '\f'?
Finally, I'm not sure that 'asciis' is a term I've seen before; the normal term would be 'ASCII characters'.

Related

Unıque Random Number Check form Array c++

#include <iostream>
#include<ctime>
#include<cstdlib>
#include<string>
#include<cmath>
using namespace std;
int main()
{
bool cont = false;
string str;
int num, num2;
cin >> str >> num;
int arr[10];
int a = pow(10, num);
int b = pow(10, (num - 1));
srand(static_cast<int>(time(NULL)));
do {
num2 = rand() % (a - b) + b;
int r;
int i = 0;
int cpy = num2;
while (cpy != 0) {
r = cpy % 10;
arr[i] = r;
i++;
cpy = cpy / 10;
}
for (int m = 0; m < num; m++)
{
for (int j = 0; j < m; j++) {
if (m != j) {
if (arr[m] == arr[j]) {
break;
}
else {
cont = true;
}
}
}
}
cout << num2 << endl;
} while (!cont);
return 0;
}
I want to take a number from the user and produce such a random number.
For example, if the user entered 8, an 8-digit random number.This number must be unique, so each number must be different from each other,for example:
user enter 5
random number=11225(invalid so take new number)
random number =12345(valid so output)
To do this, I divided the number into its digits and threw it into the array and checked whether it was unique. The Program takes random numbers from the user and throws them into the array.It's all right until this part.But my function to check if this number is unique using the for loop does not work.
Because you need your digits to be unique, it's easier to guarantee the uniqueness up front and then mix it around. The problem-solving principle at play here is to start where you are the most constrained. For you, it's repeating digits, so we ensure that will never happen. It's a lot easier than verifying if we did or not.
This code example will print the unique number to the screen. If you need to actually store it in an int, then there's extra work to be done.
#include <algorithm>
#include <iostream>
#include <numeric>
#include <random>
#include <vector>
int main() {
std::vector<int> digits(10);
std::iota(digits.begin(), digits.end(), 0);
std::shuffle(digits.begin(), digits.end(), std::mt19937(std::random_device{}()));
int x;
std::cout << "Number: ";
std::cin >> x;
for (auto it = digits.begin(); it != digits.begin() + x; ++it) {
std::cout << *it;
}
std::cout << '\n';
}
A few sample runs:
Number: 7
6253079
Number: 3
893
Number: 6
170352
The vector digits holds the digits 0-9, each only appearing once. I then shuffle them around. And based on the number that's input by the user, I then print the first x single digits.
The one downside to this code is that it's possible for 0 to be the first digit, and that may or may not fit in with your rules. If it doesn't, you'd be restricted to a 9-digit number, and the starting value in std::iota would be 1.
First I'm going to recommend you make better choices in naming your variables. You do this:
bool cont = false;
string str;
int num, num2;
cin >> str >> num;
What are num and num2? Give them better names. Why are you cin >> str? I can't even see how you're using it later. But I presume that num is the number of digits you want.
It's also not at all clear what you're using a and b for. Now, I presume this next bit of code is an attempt to create a number. If you're going to blindly try and then when done, see if it's okay, why are you making this so complicated. Instead of this:
num2 = rand() % (a - b) + b;
int r;
int i = 0;
int cpy = num2;
while (cpy != 0) {
r = cpy % 10;
arr[i] = r;
i++;
cpy = cpy / 10;
}
You can do this:
for(int index = 0; index < numberOfDesiredDigits; ++index) {
arr[index] = rand() % 10;
}
I'm not sure why you went for so much more complicated.
I think this is your code where you validate:
// So you iterate the entire array
for (int m = 0; m < num; m++)
{
// And then you check all the values less than the current spot.
for (int j = 0; j < m; j++) {
// This if not needed as j is always less than m.
if (m != j) {
// This if-else is flawed
if (arr[m] == arr[j]) {
break;
}
else {
cont = true;
}
}
}
}
You're trying to make sure you have no duplicates. You're setting cont == true if the first and second digit are different, and you're breaking as soon as you find a dup. I think you need to rethink that.
bool areAllUnique = true;
for (int m = 1; allAreUnique && m < num; m++) {
for (int j = 0; allAreUnique && j < m; ++j) {
allAreUnique = arr[m] != arr[j];
}
}
As soon as we encounter a duplicate, allAreUnique becomes false and we break out of both for-loops.
Then you can check it.
Note that I also start the first loop at 1 instead of 0. There's no reason to start the outer loop at 0, because then the inner loop becomes a no-op.
A better way is to keep a set of valid digits -- initialized with 1 to 10. Then grab a random number within the size of the set and grabbing the n'th digit from the set and remove it from the set. You'll get a valid result the first time.

Prevent loop from echoing if another same-value array element has been already echoed in C++

First of all, sorry for the mis-worded title. I couldn't imagine a better way to put it.
The problem I'm facing is as follows: In a part of my program, the program counts occurences of different a-zA-Z letters and then tells how many of each letters can be found in an array. The problem, however, is this:
If I have an array that consists of A;A;F;A;D or anything similar, the output will be this:
A - 3
A - 3
F - 1
A - 3
D - 1
But I am required to make it like this:
A - 3
F - 1
D - 1
I could solve the problem easily, however I can't use an additional array to check what values have been already echoed. I know why it happens, but I don't know a way to solve it without using an additional array.
This is the code snippet (the array simply consists of characters, not worthy of adding it to the snippet):
n is the size of array the user is asked to choose at the start of the program (not included in the snippet).
initburts is the current array member ID that is being compared against all other values.
burts is the counter that is being reset after the loop is done checking a letter and moves onto the next one.
do {
for (i = 0; i < n; i++) {
if (array[initburts] == array[i]) {
burts++;
}
}
cout << "\n\n" << array[initburts] << " - " << burts;
initburts++;
burts = 0;
if (initburts == n) {
isDone = true;
}
}
while (isDone == false);
Do your counting first, then loop over your counts printing the results.
std::map<decltype(array[0]), std::size_t> counts;
std::for_each(std::begin(array), std::end(array), [&counts](auto& item){ ++counts[item]; });
std::for_each(std::begin(counts), std::end(counts), [](auto& pair) { std::cout << "\n\n" << pair.first << " - " pair.second; });
for (i = 0; i < n; i++)
{
// first check if we printed this character already;
// this is the case if the same character occurred
// before the current one:
bool isNew = true;
for (j = 0; j < i; j++)
{
// you find out yourself, do you?
// do not forget to break the loop
// in case of having detected an equal value!
}
if(isNew)
{
// well, now we can count...
unsigned int count = 1;
for(int j = i + 1; j < n; ++j)
count += array[j] == array[i];
// appropriate output...
}
}
That would do the trick and retains the array as is, however is an O(n²) algorithm. More efficient (O(n*log(n))) is sorting the array in advance, then you can just iterate over the array once. Of course, original array sequence gets lost then:
std::sort(array, array + arrayLength);
auto start = array;
for(auto current = array + 1; current != array + arrayLength; ++current)
{
if(*current != *start)
{
auto char = *start;
auto count = current - start;
// output char and count appropriately
}
}
// now we yet lack the final character:
auto char = *start;
auto count = array + arrayLength - start;
// output char and count appropriately
Pointer arithmetic... Quite likely that your teacher gets suspicious if you just copy this code, but it should give you the necessary hints to make up your own variant (use indices instead of pointers...).
I would do it this way.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string s;
vector<int> capCount(26, 0), smallCount(26, 0);
cout << "Enter the string\n";
cin >> s;
for(int i = 0; i < s.length(); ++i)
{
char c = s.at(i);
if(c >= 'A' && c <= 'Z')
++capCount[(int)c - 65];
if(c >= 'a' && c <= 'z')
++smallCount[(int)c - 97];
}
for(int i = 0; i < 26; ++i)
{
if(capCount[i] > 0)
cout << (char) (i + 65) << ": " << capCount[i] << endl;
if(smallCount[i] > 0)
cout << (char) (i + 97) << ": " << smallCount[i] << endl;
}
}
Note: I have differentiated lower and upper case characters.
Here's is the sample output:
output

i want to show the sequence ftom 16 to 31 decimal number but its not showing :\ could anyone help me out here

#include <iostream>
using namespace std;
void bi(int a);
int main()
{
// here is the issue how do start a loop, where i want the answer from 16 to 31 numbers
int a=0;
cout<<"Baum-Sweet Sequence From 16 to 31 \n";
for(int j=a;j>16 && j<31;j++)
{
cout<<j;
}
bi(a);
system("Pause");
}
// Rest is working properly
void bi(int a)
{
int myArr[15],i=0,f=0,n=0;
for (int h = 0 ; h <= a; h++)
{
int num = h;
for (i = 0 ; i < 4 ; i++)
{
myArr[i] = num%2;
num = num/2;
}
for (int t = 0 ; t < 4 ; t++)
{
if (myArr[t]%2==0)
f++;
}
if (f%2==0)
cout << " = " << 1;
else
cout << " = " << 0;
cout <<endl;
}
}
i want to show the sequence from 16 to 31 decimal number but its not showing :\ could anyone help me out here
There is an error in the for loop.
The for loop has three parts separated by a semicolon.
for (INITIALIZATION; CONDITION; AFTERTHOUGHT)
{
// Source code for the for-loop's body
}
The first part initializes the variable (e.g. "int j = 16;" means that through the variable j you begin counting by 16);
The second part checks a condition and it quits the loop when false (e.g. j <=31 means that it quits the loop when j will have value 31);
The third one is performed once each time the loop ends and then repeats (e.g. j++ means that at each iteration of the loop j will be incremented by 1).
Each iteration will execute the code in the body of the for loop.
Considering that you want to call the bi function for each value from 16 to 31 your for loop body should include bi(j). Your main should be modified like the code below:
int main()
{
cout<<"Baum-Sweet Sequence From 16 to 31 \n";
for(int j=16;j<=31;j++)
{
cout<<j;
bi(j);
}
system("Pause");
return 0;
}
Your problem is that you set j to 0, but then make a condition for the loop that it will only execute if j (which is set to a), is bigger than 16.
Your first thing to do is to make the loop conditions this:
for (int j = 16; j <= 32; j++)

What is the purpose of the increment statement?

Why are increment statements a thing in for-loops in C++? To me it seems redundant, because you could simply put the increments inside the conditional code. Am I misunderstanding something important here?
To illustrate my question better, I'm including some pseudocode:
What is the difference between ->
for( int a = 10; a < 20; a = a + 1 )
{
cout << a << endl;
}
and
for( int a = 10; a < 20;)
{
a = a + 1
cout << a << endl;
}
It's more than mere convenience sometimes.
These are equivalent:
for (int a = 10; a < 20; a = a + 1) {
cout << a << endl;
}
for (int a = 10; a < 20; ) {
cout << a << endl;
a = a + 1;
}
But, these are not:
// this works ...
for (int a = 10; a < 20; a = a + 1) {
if (blah ...)
continue;
cout << a << endl;
}
// this doesn't
for (int a = 10; a < 20; ) {
if (blah ...)
continue;
cout << a << endl;
a = a + 1;
}
Since you're coming from python, an idiomatic for loop is like a python range, but much more powerful. Your C for loop, expressed in python would be:
for a in range(10,20,1)
It's more idiomatic to express this as:
for (a = 10; a < 20; a += 1)
Because the loop increment is 1, it's even more idiomatic to do this:
for (a = 10; a < 20; ++a)
But, for loops are:
for ([init_stmt]; [test_stmt]; [incr_stmt])
Where any of the *_stmt can be compound:
for (x = 0, y = 0; x < 10; ++x, y += 2)
Convenience.
However, your equivalent code should be:
for (int a = 10; a < 20;)
{
cout << a << endl;
a = a + 1;
}
It runs at the end of the loop body.
[ snips grumbling about quality of now deleted/ edited answers ;-) ]
This:
for (unsigned counter = 1; counter <= 10; ++counter) {
doStuff();
}
is largely equivalent to this:
unsigned counter = 1;
while (counter <= 10) {
doStuff();
++counter;
}
with the notable exception that, in the 1st case, you have the considerable benefit that counter is scoped only to within the for block and automatically goes out-of-scope as soon as it finishes - whereas with the latter, counter must remain in-scope after the loop, where it's potentially useless or even an obstacle.
(tangential: Note that C did not support within-for declaration, or any non-top-of-block declarations, until C99 - but barring extenuating circumstances, anyone not using at least C99 by now is making a questionable choice imho.)
edit: Craig also makes a very good point regarding continue - an oft-forgotten but certainly useful statement. I'm sure there are probably other differences we could conjure up.
for this example:
using namespace std;
int main(int argc, char** argv) {
for( int a = 10; a < 20;)
{
a = a + 1;
cout << a << endl;
}
return 0;
}
the output will be from 11-->20
the first example will be from 10-->19
your are putting the increment part outside the loop and this possible, but notice that the value 10 will not appear, because you are increment before printing the value of a
so in the 2nd example your printing the value and then increment, and at the end of the loop, you are quiting the loop without reaching 20, because the condition get you out the loop
executing code block before increment is the key for you, the for loop increment just after the code block is executed
Well it is not required, it is just for convenience.
In your second code, you made a little mistake which would make the code nonequivalent to the the first one.
Your increment should be at the end of loop in order to be equivalent to the first code
so it should rather be:
for( int a = 10; a < 20;)
{
cout << a << endl;
a = a + 1; //increment at the end of instructions
}
These little errors and also errors like forgetting to include your increment is why it is convenient to include the increment in the for loop.
Or you can use the while loop instead:
while (condition)
{//instructions here;}

C++ removing leading zeros in a binary array

I am making a program that adds two binary numbers (up to 31 digits) together and outputs the sum in binary.
I have every thing working great but I need to remove the leading zeros off the solution.
This is what my output is:
char c[32];
int carry = 0;
if(carry == '1')
{
cout << carry;
}
for(i = 0; i < 32; i++)
{
cout << c[i];
}
I tried this but it didn't work:
char c[32];
int carry = 0;
bool flag = false;
if(carry == '1')
{
cout << carry;
}
for(i=0; i<32; i++)
{
if(c[i] != 0)
{
flag = true;
if(flag)
{
for(i = 0; i < 32; i++)
{
cout << c[i];
}
}
}
}
Any ideas or suggestions would be appreciated.
EDIT: Thank you everyone for your input, I got it to work!
You should not have that inner loop (inside if(flag)). It interferes with the i processing of the outer loop.
All you want to do at that point is to output the character if the flag is set.
And on top of that, the printing of the bits should be outside the detection of the first bit.
The following pseudo-code shows how I'd approach this:
set printing to false
if carry is 1:
output '1:'
for each bit position i:
if c[i] is 1:
set printing to true
if printing:
output c[i]
if not printing:
output 0
The first block of code may need to be changed to accurately output the number with carry. For example, if you ended up with the value 2 and a carry, you would want either of:
1:10 (or some other separator)
100000000000000000000000000000010 (33 digits)
Simply outputting 110 with no indication that the leftmost bit was a carry could either be:
2 with carry; or
6 without carry
The last block ensures you have some output for the value 0 which would otherwise print nothing since there were no 1 bits.
I'll leave it up to you whether you should output a separator between carry and value (and leave that line commented out) or use carry to force printing to true initially. The two options would be respectively:
if carry is 1:
output '1 '
and:
if carry is 1:
output 1
set printing to true
And, since you've done the conversion to C++ in a comment, that should be okay. You state that it doesn't work, but I typed in your code and it worked fine, outputting 10:
#include <iostream>
int main(void)
{
int i;
int carry = 0;
int c[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0};
bool print = false;
// This is the code you gave in the comment, slightly modified.
// vvvvvv
if(carry == 1) {
std::cout << carry << ":";
}
for (i = 0; i < 32; i++) {
if (c[i] == 1) {
print = true;
}
if (print) {
std::cout << c[i];
}
}
// ^^^^^^
std::cout << std::endl;
return 0;
}
const char * begin = std::find(c, c+32, '1');
size_t len = c - begin + 32;
std::cout.write(begin, len);
Use two fors over the same index. The first for iterates while == 0, the second one prints starting from where the first one left off.