In which part Im doing a mistake which results in overflow? - arrays

`I have print the numbers of words in letter in a sentence in a array
for Example:
hello ALL Im jabish
the output is
5 3 2 6
but getting
5 3 2 12381917 ,some overflow in last word,
I uploaded my code as image As it not getting indented properly Sorry for that
enter image description here
So this is my input,
-> hello ALL Im jabish
the output is
5 3 2 6
but Im getting
5 3 2 12381917 `

So there's a minor issue with the code. When you are trying to calculate the last element it was setting with the overflow in the last count because when the 2nd loop exits you need to set the last word count in array like a[d]=count1.
Here's the complete code:
// Online C compiler to run C program online
#include <stdio.h>
#include<string.h>
int main() {
char str[100];
scanf("%[^\n]%*c",str);
int g=strlen(str);
int count = 1;
for(int i=0; i<g; i++) {
if(str[i] == ' '){
count++;
}
}
int a[count];
int count1=0;
int d=0;
for(int i = 0; i<g; i++) {
if(str[i] != ' '){
count1++;
}
if(str[i] == ' '){
if(count1 < 100){
a[d] = count1;
}
count1=0;
d++;
}
}
a[d]=count1;
int c= sizeof(a)/sizeof(a[0]);
for(int i=0;i<c;i++){
printf("%d", a[i]);
}
}

Related

I want that my string that i enter maunaly displays numbers of repeted character "ma" but i am stuck i am new to C

I am new to C programming and I want to display how many times did "ma" showed up for example "mamama" there is 3 "ma" but in my code when I write "mamam" it displays 3 "ma". Sorry for my bad explanation... I recently started studying C programming.
I tried with do-while but I end up screwing even more..
#include <string.h>
#include <stdio.h>
int main()
{
char a[81];
int i, j;
int zbroj=0;
i=0;
fgets(a,81,stdin);
for(i=0; i<'m';i++)
{
for(j=0; j<'a';j++)
{
while(a[i] !='\0')
{
if(a[i] == 'm' || a[j]=='a')
{
zbroj++;
}
i++;
}
}
}
printf("%d\n", zbroj);
return 0;
}
Well, the end goal is when I type "mamam" program should write down there is 2 "ma".
This is what you need:
int main()
{
char a[81];
int i, j;
int zbroj=0;
i=0;
fgets(a,81,stdin);
while(a[i] !='\0') {
if(a[i] == 'm' && a[i+1]=='a')
{
zbroj++;
i++;
}
i++;
};
printf("%d\n", zbroj);
return 0;
}
Your first iteration are not needed. You need to iterate though the string and check if you have found the letter you want and then check the next one. Then increase the counter. Try to understand what is that each line of code does though. You will need it.
hint I have also changed || to &&

Printing lowercase, uppercase, and number of numbers

#include<stdio.h>
int main() {
char text[1000];
int ch;
int index = 0;
while ((ch = getchar()) != EOF) {
text[index] = ch;
index++;
}
text[index] = '\0';
int i =0;
int num_Count=0;
int lower_Count=0;
int upper_Count =0;
while(i < index) {
if((text[i]>='0') && (text[i]<='9')){
num_Count ++;
i++;
}
else if((text[i]>='A') && (text[i]<='Z')){
upper_Count++;
i++;
}
else if((text[i]>='a') && (text[i] <='z')){
lower_Count++;
i++;
}
else
i++;
}
printf("%d %d %d", num_Count, lower_Count, upper_Count);
return 0;
}
It is a program that outputs the number of lower case, upper case, and number when the sentence is inputted.
For example,
Hi
Name
100
Would output 3 4 2
I keep seeing a runtime error.
The (while) part seems to be wrong.. I do not know what's wrong.
I ran your code in my system and checked for the input: Hi Name 100. The output I got is 3 4 2 which is the expected output. I feel the only place where the code can run in an infinite loop is while reading the inputs. Try to use ctrl+ d for EOF or ctrl+ z for windows.
Rest every thing is fine.
EOF means End Of File. It is used when you read data from a file. I suggest put a character like newline ('\n').

Exiting Do While loop

I was working on some homework, and came across this issue.
Write a program that reads several lines of text and prints a table indicating the number of one-letter words, two-letter words,
three-letter words, and so on, appearing in the text. For example the
phrase "Whether 'tis nobler in the mind to suffer"
Will contain
1 letter words: 0
2 letter words: 2
3 letter words: 1
4 letter words: 2 (including 'tis)
5 letter words: 0
6 letter words: 2
7 letter words: 1
My code for the question is below.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXDIMENSIONS 1000 //set max dimensions
#define MAXLENGTH 1000 //set max length
void separate(char stringArray[][MAXLENGTH], int words);
void printTable(char stringArray[][MAXLENGTH], int c);
int main(int argc, char** argv) {
char txt[MAXLENGTH];
char *token;
char mat[MAXDIMENSIONS][MAXLENGTH];
int i=0,wordcount=0;
do{
printf(">>>Write and press enter (EXIT for end of program)<<< : ",49);
fgets(txt,sizeof txt,stdin);
if(strcmp(txt,"EXIT")!=0)
{
token=strtok(txt," ");
strcpy(mat[i],token);
i++;
while(token!=NULL){
token=strtok(NULL, " ");
if(token!=NULL){
strcpy(mat[i],token);
i++;
}
}
}
}while(strcmp(txt,"EXIT")!=0);
separate(mat,i);
printTable(mat,i);
return (EXIT_SUCCESS);
} // end of main
void separate(char stringArray[][MAXLENGTH], int words){
for(int i=0; i<words; i++){
for(int j=0; j<strlen(stringArray[i]); j++){
if((stringArray[i][j]<65 && stringArray[i][j]!=39) || (stringArray[i][j]>90 && stringArray[i][j]<97)|| stringArray[i][j]>122){
for(int g=j; g<strlen(stringArray[i]); g++){
stringArray[i][g]=stringArray[i][g+1];
}
}
}
}
}
void printTable(char stringArray[][MAXLENGTH], int c){
int max;
int value=0,j;
max=strlen(stringArray[0]);
for(int i=1; i<c; i++){
if(max<strlen(stringArray[i])){
max=strlen(stringArray[i]);
}
}
printf("\n***********WORD LENGTH READER***********\n");
printf("| LENGTHS || VALUES | \n");
for(j=1; j<=max; j++){
for(int i=0; i<c; i++){
if(strlen(stringArray[i])==j){
value++;
}
}
printf("| %d || %d | \n",j,value);
value=0;
}
printf("\n****************************************\n");
}
My issue is getting out of the do while loop on line 17-33. It is my first time using fgets and I believe that this is probably what is causing the issue. I had written the code using gets and it works like that, but I know that gets is not supposed to be used due to its vulnerability.
Any help is appreciated.
Thanks in advance!
Because fgets also reads the newline, your exit condition will not be met because of the newline. You can either include the newline in your check, "EXIT\n" or you can patch out the newline after fgets.
The following example also makes the loop a bit simpler:
do {
fgets(txt,sizeof txt,stdin);
char *p= strrchr(txt,'\n'); if (p) *p= '\0';
if(strcmp(txt,"EXIT")==0)
break;
//....
while(1);

Program won't store characters in 2d array in c

I am creating a program where I insert a number of sentences and the program outputs them in order. I have finished the program, but when I run it it seems like the characters I input into the array aren't displayed or stored correctly, getting as a result random letters instead of the full sentence. Here is the code of the program:
char ch;
int i,j,k;
int nothing = 0;
int count = 1;
char lines[5][256];
int length[256];
int main() {
printf("Please insert up to a max of 5 lines of text (Press enter to go to next line and twice enter to stop the program):\n");
i = 0;
while (i<5){
j = 0;
ch = getche();
if (ch == '\r'){
if(i!= 0){
break;
}
printf("You have not inserted anything, please insert a line:");
i=-1;
}
if(ch != '\r'){
lines[i][j]=ch;
while (ch!='\r'){
ch = getche();
lines[i][j] = ch;
j++;
}
}
printf("\n");
i++;
}
for (k=i ; k > 0; k--){
printf("\tphrase %i :", count);
for ( j =0 ; j <= length[k]; j++){
printf("%c",lines[j][k]);
}
count++;
printf("\n");
}
return 0;
}
How can I get the characters to be stored and displayed correctly? Any help is appreciated, thank you!!
There are numerous problems with your code. I'll try and summarise here, and give you improved code.
Fist, some changes that I made to get this to compile on my system:
Changed getche() to getchar() (getche() does not appear to be available on Ubuntu).
I took out the section about re-entering a string, and just focused on the rest (since the logic there was slightly broken, and not relevant to your question). It will still check for at least one line though, before it will continue.
I had to change the check for \r to \n.
I changed your length array to size 5, since you'll only have the lengths of maximum 5 strings (not 256).
Some problems in your code:
You never updated the length[] array in the main while loop, so the program never knew how many characters to print.
Arrays are zero indexed, so your final printing loops would have skipped characters. I changed the for parameters to start at zero, and work up to k < i, since you update i after your last character in the previous loop. The same with j.
Your reference to the array in the printing loop was the wrong way around (so you would've printed from random areas in memory). Changed lines[j][k] to lines[k][j].
No need for a separate count variable - just use k. Removed count.
The nothing variable does not get used - removed it.
#include <stdlib.h>
#include <stdio.h>
char ch;
int i,j,k;
char lines[5][256];
int length[5];
int main()
{
printf("Please insert up to a max of 5 lines of text (Press enter to go to the next line and twice enter to stop the program):\n");
i = 0;
while (i<5)
{
j = 0;
ch = getchar();
if ((ch == '\n') && (j == 0) && (i > 0))
{
break;
}
if (ch != '\n')
{
while (ch != '\n')
{
lines[i][j] = ch;
j++;
ch = getchar();
}
}
length[i] = j;
printf("\n");
i++;
}
for (k = 0; k < i; k++)
{
printf("\tPhrase %i : ", k);
for (j = 0; j < length[k]; j++)
{
printf("%c", lines[k][j]);
}
printf("\n");
}
return 0;
}

Bug in reversing word order

I am a beginner to C programming and am trying to "Split a string into separate words and write the string in reverse".
Sample Input : Hello World it's FUBAR
Sample Output: FUBAR it's World Hello
I have tried it with this code so far on CodeBlocks 13.12(Windows 8.1/AMD A8) :
#include<stdio.h>
#include<string.h>
char str[100];
char word[100][100];
int main(){
fgets(str,100,stdin);
int i=0,j=0,k=0;
for(i=0;i<100;i++){
while(str[i]!=' ' || str[i]!='\0')
{
word[j][k]=str[i];
i++;
j++;
}
if(str[i]==' '){
k++;
}
}
while(k>0){
for(j=0;j<100;j++){
printf("%s",word[j]);
}
printf(" ");
k--;
}
return 0;
}
The code compiles with 0 errors, 0 warnings.
But when I build and run the code, it crashes with error message -1073741510.
I have been trying for many hours now but have not been able to figure out where exactly the code is breaking.Please help me with this one.
Please try this code.
1) Eliminated extra looping.
2) Swapped j and k variables . Each row would constitute a new word.
3) word[0][1..100] would the first word and word[1][1..100] would be second word.
int main(){
fgets(str,100,stdin);
printf("str is [%s]\n",str);
int i=0,j=0,k=0;
for(i=0;i<100;i++){
printf("char is [%c]\n",str[i]);
if( str[i]!=' ' && str[i]!='\0' )
{
word[j][k]=str[i];
k++;
}else if(isspace(str[i]) || str[i] == ' '){
printf("space found\n");
j++;
}
}
printf("value of j [%d]\n",j);
while(j>=0){
for(k=0;k<100;k++){
printf("%c",word[j][k]);
}
printf(" ");
j--;
}
return 0;
}
Your for loop looks wrong, it should be
for(i=0;i<100;i++)
{
while(str[i]!=' ' || str[i]!='\0')
{
word[j][k]=str[i];
i++;
k++;
}
if(str[i]==' ')
{
j++;
}
}
Notice the k and j increment swap.
In the first while increase k instead of j.
In if(str[i]==' ') set the null termination for word[j][k] and then increase j instead of k.
Below is a Corrected Code. Note the Output doesn't come exactly in one single line. For example the output will always come like this,
EDIT: Thanks to a point reminded by Rad Lexus in the comments. I was able to mitigate the problem a bit
Changes made in Code:
Changed the following code line to
for(i=0;i<strlen(str);i++)
This,
for(i=0;i<strlen(str)-1;i++)
Although, the problem of outputting all the words in the same line is solved,
but there is another problem. Now there is no space between the first and the Second word.
So, the new problem is,
Example 1:
Input: Welcome to Bravo
Output: Bravoto Welcome
Example 2:
Input: Hello World it's FUBAR
Output: FUBARit's World Hello
A temporary solution to the above problem is to change this code
for(m=j;m>=0;m--){
printf("%s",word[m]);
}
To this code,
for(m=j;m>=0;m--){
if(m == j){
printf("%s ",word[m]);
}
else{
printf("%s",word[m]);
}
}
(I guess this problem occurs due to mapping from a 1D Array to a 2D Array and there is probably some padding involved.) -> Edit:This is not due to padding but, "I guess this problem occurs due to.." – no, it occurs due to fgets which also stores the terminating newline code-Rad Lexus.
Anyways, here is the code,
#include<stdio.h>
#include<string.h>
char str[100];
char word[100][100];
int main(){
int i=0,j=0,k=0;
int m=0;
fgets(str,100,stdin);
for(i=0;i<strlen(str)-1;i++){
if(str[i]!=' '){
word[j][k]=str[i];
//printf("%c",word[j][k]);
k++;
}
if(str[i] == ' ' || str[i] == '\0'){
word[j][k]=' ';
k=0;
j++;
}
}
for(m=j;m>=0;m--){
printf("%s",word[m]);/*----->TEMPORARY SOLUTION
for(m=j;m>=0;m--){
if(m == j){
printf("%s ",word[m]);
}
else{
printf("%s",word[m]);
}
}*/
}
return 0;
}

Resources