Printing triangle with given letter in C++ - c++

I would like to to print a triangle with a given letter. For example, if I input D, the program should return:
A
AB
ABC
ABCD
So far, I have managed to print all letters until the given one in my example, but as you see this method is not quite effective since I need to do this for all 26 cases since the English alphabet is 26 chars. Is there some way to optimize my code?
#include <iostream>
using namespace std;
int main() {
char i;
cout << "Enter char ";
cin >> i;
int c = static_cast<int>(i);
if (65 < c) {
cout << "A";
cout << endl;
}
if (66 < c) {
cout << "AB";
cout << endl;
}
if (67 < c) {
cout << "ABC";
cout << endl;
}
for (int i = 64; i < c; i++) {
cout << static_cast<char>(i + 1);
}
return 0;
}

You definitely need to work on your comprehension of loops. This one works just fine and it even has some checks on what is typed in and it eventually converts lower case letters into upper casse.
char first = 'A';
char last = 0;
cout << "Enter a char: ";
cin >> last;
fflush(stdin);
cout << "\n\n";
if ((last > 96) && (last < 123)) //97 to 122 are lower case letters
{
last -= 32; //32 is the delta between each lower case letter and its upper case "twin"
}
if ((last > 64) && (last < 91))
{
for (char i = 65; i <= last; i++)
{
for (char j = 65; j <= i; j++)
{
cout << j;
}
cout << "\n";
}
}
else
{
cout << "\nWrong character!!\n\n";
return 0;
}

Use a nested loop structure. Use the outer loop to 'walk' down your triangle,
lineLength = 1;
while(lineLength <= (c - 64)){
...stuff...
lineLength++;
cout << endl;
}
Use the inner loop to 'walk' down the alphabet (you've already done most of this):
for (int i = 0; i < lineLength; i++) {
cout << static_cast<char>(i + 65);
}
Putting it together:
lineLength = 1;
while(lineLength <= (c - 64)){
for (int i = 0; i < lineLength; i++) {
cout << static_cast<char>(i + 65);
}
lineLength++;
cout << endl;
}
I see that someone else has posted a similar answer. Between these two answers, you should be able to find your way. I haven't compiled and run this code, but I believe that it should work or be very close.

Don't harcode ascii integer values into code. Explicitly use the character or string literals (e.g. 'A' instead of 65)
Start with a helper function to print exactly one line
// prints all the characters of the alphabetic sequence from "A" to the final char designated by <c>
void printTriangleLine(char c)
{
if ((c < 'A') || (c > 'Z'))
{
return;
}
for (char x = 'A'; x <= c; x++)
{
cout << x;
}
cout << endl;
}
Then put it all together in your main:
int main()
{
char i;
cout << "Enter char ";
cin >> i;
if ((i < 'A') || (i > 'Z'))
{
return 0;
}
for (char x = 'A'; x <= i; x++)
{
printTriangleLine(x);
}
return 0;
}

We must run the loop from position is above 'A' character
until we reached the charanter you enter
// procead until reached input letter
while (chNew != c)
{
// go to next letter
chNew++;
// start with 'A' until current char + 1
for (int j = 'A'; j < chNew + 1; j++)
cout << (char)j;
// go to next line
cout << endl;
}
in each loop we increment character value by 1 to go to the next value
// go to next letter
chNew++;
inner loop simply print the character from A to next value relative to current chNew + 1, it is because we also want to include current character to our printed line.
Here is your working code.
#include <iostream>
using namespace std;
int main()
{
char i;
cout << "Enter char ";
cin >> i;
int c = static_cast<int>(i);
// start with 'A' - 1 character
char chNew = 'A' - 1;
// procead until reached input letter
while (chNew != c)
{
// go to next letter
chNew++;
// start with 'A' until current char + 1
for (int j = 'A'; j < chNew + 1; j++)
cout << (char)j;
// go to next line
cout << endl;
}
// we have done
return 0;
}

Related

nested looping C++

i want to asking this problem.
this output is the expected output
*
*#
*#%
*#%*
*#%*#
*#%*#%
and this is my solution
#include <iostream>
using namespace std;
int main(){
int a,b,n;
cout << "Input the row";
cin >> n;
for (a = 1; a <= n; a++){
for(b = 1; b <= a; b++){
if (b == 1 || b == 1 + 3){
cout << "*";
}
if (b ==2 || b == 2 + 3){
cout << "#";
}
if (b ==3 || b == 3 + 3){
cout << "%";
}
}
cout << endl;
}
}
this solution is only work if the n = 6. what should i do if i want this work in every row when user input the row to the n
thank you in advance.
Here, I tried using the modulo "%" on your if's
#include <iostream>
using namespace std;
int main(){
int a,b,n;
cout << "Input the row";
cin >> n;
for (a = 1; a <= n; a++){
for(b = 1; b <= a; b++){
// After every first digits will cout #
if (b % 3 == 2){
cout << "#";
}
// The first after the third digit will cout *
if (b % 3 == 1){
cout << "*";
}
// The third digit after the second digit will cout %
if (b % 3 == 0){
cout << "%";
}
}
cout << endl;
}
}
To make your solution work for any value of n, you can use the modulo operator % to check whether a given value of b is the first, second, or third element of each row.
Here is one way you could modify your code to do this:
#include <iostream>
using namespace std;
int main() {
int a, b, n;
cout << "Input the row: ";
cin >> n;
for (a = 1; a <= n; a++) {
for (b = 1; b <= a; b++) {
// Use the modulo operator to check whether b is the first, second, or third element of each row
if (b % 3 == 1) {
cout << "*";
} else {
if (b % 3 == 2) {
cout << "#";
} else {
cout << "%";
}
}
}
cout << endl;
}
return 0;
}
With this change, the code will output the correct pattern for any value of n.
Just adding a nice optimisation (note: C++ loops naturally go up from 0 to not including n, i.e. for(int i = 0; i < n; ++i) – this is especially relevant if you are indexing arrays which have a first index of 0 and last of n - 1, while n already is invalid!).
While you do use b % 3 to decide which character and you indeed can use this by chaining if(){} else if(){} else{} (where a switch() { case: case: default: } actually would have been preferrable) you can have a much more compact version as follows (and even more efficient as it avoids conditional branching):
for(int b = 0; b < a; ++b)
{
std::cout << "*#%"[b % 3];
}
The C-string literal "*#%" actually represents an array of char with length four (including the terminating null character) – and you can index it just like any other array you have explicitly defined (like int n[SOME_LIMIT]; n[7] = 1210;)...

Can't get output right, need same code on different line

Hey so my code works but I need to get this output right, I need it to output the letters I put in 2 times. It will print it once correctly but I added a loop and it bunches the Chars together instead of printing it 2 times in the loop. If I separate it with endl or \n it will separate the chars. I just want it to print the whole line I enter 2 times
{
char c;
string s;
int index = 0;
cout << "Enter a line:";
cin.get(c);
while (c != '\n' && index < size) {
x[index] = c;
cin.get(c);
index++;
}
Letter = index;
cout << "" << Letter << endl;
int k = 0;
for (int i = 0; i < Letter; ++i)
{
bool found = false;
for (int j = 0; j < k; ++j)
if (x[i] == x[j])
found = true;
if (!found)
x[k++] = x[i];
s = +x[i];
for (int z = 0; z < 1; z++) {
cout << "" << s;
}
}
Letter = k;
}
To read a line and print it twice:
std::string line;
if (std::cin.getline(line))
{
std::cout << line << '\n' << line << '\n';
}

Maximum number of vowels in a word in string array

I have written a program to input 2 strings in a string array.
And then print the maximum vowels stored in the list.
Where am i going wrong here,and is there a more elegant method to this.
#include<iostream.h>
#include<string.h>
int main()
int i,j,c=0,k=0,maxo=0,len1,maxo1=0,len3;
char vow[] = "AEIOUaeiou";
char list[100][100],vow[]={"AEIOUaeiou"};
for(i=0;i<2;i++) {
cout<<"Enter word: ";
gets(list[i]);
for(i=0;i<2;i++) {
len1=strlen(list[i]);
for(k=0;k<len1;k++) {
for(j=0;list[j][k]!='\0';j++)
if(list[j][k]==vow[j])
c++;
}
if(c>maxo)
maxo=c;
c=0;
}
cout<<"Maximum Vowel count:"<<maxo<<endl;
}
fflush(stdin);
getchar();
return 0;
}
The bigger programme where i am trying to incorporate this code.The necessary comments are in the code.I really cannot undertand where i am going wrong in the last part.
Should i include the last bit of code at first so that the program works?
#include<iostream.h>
#include<string.h>
int main()
{
int i,n,len=0,sum=0,j,max,min,c=0,c2=0,k=0,maxo=0,len1,maxi=0,c1=0,len2;
float avg;
char list[100][100] = { 0 };
char vow[] = "AEIOUaeiou";
for(i=0;i<2;i++)
{
cout<<"Enter word: ";
gets(list[i]);
len=strlen(list[i]);
sum=sum+len;
cout<<"Length of word: "<<len<<endl;
if(list[i][len-1]=='s')
{cout<<"The Word "<<list[i]<<" ends with s"<<endl;
c2++;
}
}
//Word input by user.Prints word along with length.
min=strlen(list[0]);
max=strlen(list[0]);
//Initialising max and min.
for(i=0;i<2;i++)
{
if(strlen(list[i])<min)
{min=strlen(list[i]);}
if(strlen(list[i])>max)
{max=strlen(list[i]);}
}
for(i=0;i<2;i++)
{
if(max==strlen(list[i]))
cout<<"The max value of the lengths stored:"<<list[i]<<endl<<"Word count:"<<max<<endl;
if(min==strlen(list[i]))
cout<<"The min value of the lengths stored:"<<list[i]<<endl<<"Word count:"<<min<<endl;
}
//Max and Min value of string lengths are printed.
avg=sum/2;
cout<<"Avg length:"<<avg<<endl;
//Average value printed.
cout<<"The number of words with s:"<<c2<<endl;
//Word ending with s.
{for (i = 0; i <2; i++)
len1 = strlen(list[i]);
for (k = 0; k < len1; k++)
{
for (j = 0; j < strlen(vow); j++)
//if (list[j][k] == vow[j])
if (list[i][k] == vow[j])
c++;
}
cout << "Number of vowels in line " << i << ": " << c << '\n';
if (c>maxo) maxo = c;
c = 0;
cout << "Maximum Vowel count so far:" << maxo << "\n\n";
cout << "Maximum Vowel count:" << maxo << endl;
}
for(i = 0 ;i < 2 ;i++)
{ len3 = strlen(list[i]);
letter = list[i][0];
{for(j=0;j<len3;j++)
if(list[i][j]==letter)
counter++;
}
cout << "Number of identical letters as first letter in line " << i << ":
" << counter << '\n';
if (c>maxo1) maxo1 = counter;
counter = 0;
cout << "Maximum letter count so far:" << maxo1 << "\n\n";
cout << "Maximum letter count:" << maxo1 << endl;
}
PS:
I have edited my code one more time to display the alphabet which has occurred the maximum number of times as starting letter of a word in the list,and the number of times it has occurred.
This won't compile for me for two reasons:
1) gets()
The most recent revision of the C standard (2011) has definitively
removed this function from its specification. The function is
deprecated in C++ (as of 2011 standard, which follows C99+TC3).
And so I can't use the gets() function.
2) You can't declare
char list[100][100], char vow[] = {"AEIOUaeiou"};
both with a comma separator.
You read the input for the first line string into the first row of the array i = 0; then you instantly loop through i, which doesn't make sense. The following is not a good solution as in C++ you should be using std::vectors and std::string, and not generally mixing C and C++ but I've tried to keep it as close to your version, using my telepathic powers to read your mind about what you're trying to do.
#include <iostream>
#include <cstring>
using namespace std;
const int numLinesToGet = 10;
const int maxCharsPerLine = 100;
int main()
{
int i, j, c = 0, k = 0, maxo = 0, len1;
//char list[100][100], char vow[] = {"AEIOUaeiou"};
char list[100][100] = { 0 };
char vow[] = "AEIOUaeiou";
//for (i = 0; i < 2; i++)
for (i = 0; i < numLinesToGet; i++)
{
cout << "Enter word: ";
std::cin.getline(list[i], maxCharsPerLine);
//gets(list[i]);
//for (i = 0; i < 2; i++) Get rid of this second loop entirely
len1 = strlen(list[i]);
for (k = 0; k < len1; k++)
{
//for (j = 0; list[j][k] != '\0'; j++)
for (j = 0; j < sizeof(vow); j++)
//if (list[j][k] == vow[j])
if (list[i][k] == vow[j])
c++;
}
cout << "Number of vowels in line " << i << ": " << c << '\n';
if (c>maxo) maxo = c;
c = 0;
cout << "Maximum Vowel count so far:" << maxo << "\n\n";
}
cout << "Maximum Vowel count:" << maxo << endl;
fflush(stdin);
getchar();
return 0;
}
Online example here
#include<stdio.h>
int main ()
{
char a[] = "i love to code in education";
int i, count = 0, vow = 0, mvow = 0;
for (i = 0; a[i] != '\0'; i++)
{
if (a[i] == 'a' || a[i] == 'e' || a[i] == 'i' || a[i] == 'o'
|| a[i] == 'u')
{
vow++;
}
if (a[i]==' ')
{
count++;
mvow = vow;
vow = 0;
}
}
printf ("Total words: %d\n", count+1);
if(vow>mvow) printf ("Max Vowels in a word: %d", vow);
else printf("Max Vowels in a word: %d", mvow);
return 0;
}

program to check is there any alphabet(a-z) exists in all string(list of novels) and print number of alphabets found

will you please tell me what will be the procedure to find alphabet occur in all strings(char string lists) in c++
the output will only return matched values(alphabet numbers)
i m trying this
#include <vector>
#include <iostream>
#include <cstdio>
int main()
{
//setup
std::vector<int> alphabetCount;
for (int i = 0; i < 26; ++i)
{
alphabetCount.push_back(0);
}
//now the interactive bit
std::cout << "Enter a line of text\n";
std::string line;
std::getline(std::cin, line);
for (size_t i = 0; i < line.size(); ++i)
{
char currentChar = tolower(line[i]);
if (isalpha(currentChar))
{
++alphabetCount[currentChar - 'a']; //subtract a, so if currentChar = a, 'a' - 'a' = 0, so its index 0
}
}
for (size_t i = 0; i < alphabetCount.size(); ++i)
{
std::cout << "there were " << alphabetCount[i] << " occurences of " << static_cast<char>(i + 'a') << "\n"; //add 'a' for the same reason as above, though we have to cast it to a char.
}
system("pause");
return 0;
}
but it only returns values from single string i want result from all string
The reason why it is taking one string at a time is because you are taking one as input, you should make a vector of string and take input in it.
You have not read the string more than once in program. below is sample program, which is very naive to demonstrate the process. The loop terminating condition can be much better than mine though.
int main()
{
//setup
std::vector<int> alphabetCount;
for (int i = 0; i < 26; ++i)
{
alphabetCount.push_back(0);
}
//now the interactive bit
std::cout << "Enter a line of text\n";
std::string line;
do{
std::getline(std::cin, line);
for (size_t i = 0; i < line.size(); ++i)
{
char currentChar = tolower(line[i]);
if (isalpha(currentChar))
{
++alphabetCount[currentChar - 'a']; //subtract a, so if currentChar = a, 'a' - 'a' = 0, so its index 0
}
}
}while(line != "exit");
--alphabetCount['e' - 'a'];
--alphabetCount['x' - 'a'];
--alphabetCount['i' - 'a'];
--alphabetCount['t' - 'a'];
for (size_t i = 0; i < alphabetCount.size(); ++i)
{
std::cout << "there were " << alphabetCount[i] << " occurences of " << static_cast<char>(i + 'a') << "\n"; //add 'a' for the same reason as above, though we have to cast it to a char.
}
system("pause");
return 0;
}

Strange first element of array after reading in from file

I'm reading in a sodoku board from a text file. The board is represented by 9 rows of 9 digit numbers, like this:
594632817
123478569
678159234
215346798
346897125
789215346
437561982
851924673
962783451
EDIT
Here are the results when I change the while condition to (input >> char):
Output as chars are read in:
96212486
71931369
48728254
35185947
67350
Output of printArray:
962124867
193136948
728254351
859476735
�$%w��
����QȿȔ
L�`g�Pw
���w�
And here's the output for while (!input.eof()):
�94632817
123478569
678159234
215346798
346897125
789215346
437561982
851924673
962783451
END EDIT
The trouble is, when I place each digit into a multidimensional array, the element at [0][0] appears as a shaded question mark (compiled with g++). The problem only surfaces when I'm printing out the contents of the array, the data as it's read in appears to be fine. For what it's work, this also happens if I cout << board[0][0] from the main function.
Any help would be appreciated!
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int createArray(string filename);
bool checkRows(char board[][9]);
bool checkColumns(char board[][9]);
bool checkBoxes(char board[][9]);
void printArray(char board[][9]);
int main ()
{
char board [9][9];
int i = 0;
int j = 0;
int count = 0;
ifstream input("board.txt");
char ch;
while (input >> ch)
{
// ch = input.get();
if (ch != '\n')
{
cout << ch;
board[i][j] = ch;
j++;
if (j % 9 == 0)
{
i++;
}
}
if (j > 8)
j = 0;
if (i > 8)
i = 0;
count++;
if (count % 10 == 0)
cout << endl;
}
input.close();
printArray(board);
cout << checkRows(board) << endl;
cout << checkColumns(board) << endl;
return 0;
}
void printArray(char board[][9])
{
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
cout << board[i][j];
}
cout << endl;
}
cout << board[0][0] << endl;
cout << board[0][1] << endl;
}
By doing this, reading ch two times.
Remove ch = input.get(); and you will read each number correctly.
while (input >> ch)
{
ch = input.get();
...
}
Again, consider changing condition below to make sure correct endl placement
if (count % 10 == 0)
cout << endl;
to
if (count % 9 == 0)
cout << endl;