C for loop failing - c

So I'm new in C language and I'm trying to do a histogram with the length of the words the user typed, I have a solution but my second for loop always fail, I code like 5 for loop and every of them just stop after the second or third iteration, Am I missing something please help. Here's my code.
#include<stdio.h>
int main(){
int i,x,c,r,size;
int wa[10];
size=0;
for(i=0;i<10;i++){
wa[i]=0;
}
while((c=getchar())!=EOF){
switch(c){
case' ':{
wa[size]++;
size=0;
break;}
case'\n':{
wa[size]++;
size=0;
break;}
case'\t':{
wa[size]++;
size=0;
break;}
default:{
size++;
break;
}
}
}
for(r=0;r<=10;++r){
printf("%d",r);
for(x=0;x<wa[r];x++){
printf("*");
}
printf("\n");
}
return 0;
}

first, for testing purposes when running from Linux commandline Ctrl+d emulates EOF
second, your for loop iterates between ( 0 -10 inclusive ), your wa array index however is ranging from (0 - 9 inclusive ) which means:
for(x=0;x
call may cause SEGFAULT
third, you are missing a simple case where the input is just one word with no whitespace after, something like
abcdEOF
fourth, following the second paragraph when entering valus to the array your indexing is wrong
as far as the assumption that the longest words is 10char long thats fine but you must verify that the size never exceeds the value of 9 or if you will correct the wa update then 10 exceeding this value will cause segfault due to updating un-allocated index in the array
Hope this helps

The first for loop will start from 1, and in the second for loop replace wa[4] with wa[r].
Your code also assume that no word will be longer than 10 char.

Related

my for loop is not working properly in my code it keeps stopping after 1st cycle?

#include<stdio.h>
int main()
{
int i,n;
int arr[10]={};
printf("\n print all the entered elements in array");
printf("\n enter the value of n");
scanf("%d",&n);
for(i=0;i<=n;i++)
{
printf("\n element no %d",n);
scanf("%d",arr[i]);
}
printf("\n the reversed elements are");
for(i=n-1;i<=0;i--)
{
printf("\n the numbers are %d",arr[i]);
}
return 0;
}
hey there this is my c program code and i have first enter the no of elemnts as how many element i want in that array and the have to print it in reverse order and i am facing some problem with this as when my first loop starts after 1 complete cycle or after taking one input on element i=0 it stops. i dont have any idea whats going on here so pls help me..
You want the address of the array element, not its value.
So, change
scanf("%d",arr[i]);
to
scanf("%d",&arr[i]);
(And, for your own sake, learn to not ignore the return value of scanf().)
Also, if you enter N as number of elements, then your code will need N+1 numbers entered, hoping that N+1 is less than 10.
This is because for(i=0;i<=n;i++) will need numbers entered for 0,1,2, ...N, because of the <=, you probably want <. You will then be asked one number less, which should fix the problem you describe. I.e. you should then see the "the reversed elements are" output after entering N elements. Your program currently seems to "stop" because it waits for another number being entered.
When you fixed that the next problem you encounter will be the one described in the comment by Tom Karzes. It prevents the output of "the numbers are".
Your continuation test is backwards. You want i >= 0, not i <= 0, since i is counting down to zero.
This means that, with your code as is, the body of the second loop will never be executed because with any meaningful n value, i<=0 for i==n-1 will already be false for the first check and the loop is immediatly done.

Debug-print for loop omitting 1st value

I was debugging a low level program, I had to ensure that my array exp have all values I expect it to have. So I wrote a code snippet that prints my array to help debug it. Problem is standard library isn't available so I need to use my own code.
My code snippet:
int test=0;char val[5]={};
int l=0;
for(int k=0;exp[k]!=0;k++)
{
test=exp[k]; //taking in value
int_to_ascii(test, val);
print_char(val,2*l,0xd);
for(int m=0;val[m]!='\0';m++)//clearing out val for next iteration
val[m]='\0';
l=k*0xA0; //next line
}
exp is an integer array..
code for int_to_ascii:
if(src==0)
{
stack[i++]='\0'; //pushing NULL and 0 to stack
stack[i++]='0';
}
else
{
while(src!=0) //converting last digit and pushing to stack
{
stack[i]=(0x30+src%10);
src/=10;
i++;
}
}
i--;
len=i;
while(i>=0)
{
dest[len-i]=stack[i]; //popping and placing from left to right
i--; //inorder not to get reversed.
}
print_char works because I use it to print entire window and interface. It basically takes
char* szarray,int offset,int color.
I was yelling at my computer for nearly 2 hours because I thought my array is incorrect but it shouldn't be, but the actual problem was in this debug code.It doesn't print exp[0].
When it should output:
20480
20530
5
It just prints
20530
5
I even tried brute forcing values into exp[0]. If I give any value except 20480 into that, it will print invalid characters into first entry,like this:
20530P\. ;not exact value, demonstration purpose only
5
I think something is off in int_to_ascii, but that also is extensively used in other parts without any problems.
Any one have any idea with it?

Why does my for loop go out of bounds?

I have a program to check if a sentence read on the keyboard is a pangram.
But when displaying the results (in the last for-loop), it goes out of the expected bounds. If you uncomment the printf statement, you can see that even thought i<26 is set as the loop condition, it runs upto i = 27 and the array of size 26 has elements cache[26] = garbage value and cache[27] = 0. What is wrong with my last for loop ?
int main() {
char* string = (char*)malloc(1024*sizeof(char));
fgets(string, 1024, stdin);
int i=0, cache[25]={0};
while(string[i]!='\0' ){
cache[(toupper(string[i])-'A')]++;
i++;
}
for( i=0; i<26; i++){
// printf("%d - %d\n",i,cache[i]);
if(!cache[i]){
printf("not pangram");
return(0);
}
}
printf("pangram");
return 0;
}
The problem is that your array is first too small for the 26 letters of the alphabet. It should be at least cache[26].
Then the following might go out of range for any non alphabetic chars (comma, space, etc...):
cache[(toupper(string[i])-'A')]++;
Going out of range will corrupt your memory (for example overwrite i or whatever else can happen when the behavior is undefined).
How to solve the issue?
You may consider protecting your cache increment:
if (isalpha(string[i]))
cache[(toupper(string[i])-'A')]++;
Note that some more exotic locale might consider some chars outside the range 'A'-'Z' as being alpha. So you may even want to be even stricter:
int letter=toupper(string[i])-'A';
if (letter>=0 && letter<26)
cache[(toupper(string[i])-'A')]++;

reversing a string of integers user enters (C)

What I want to do is reverse a string of numbers that the user enters. what happens is it compiles and runs till i hit enter after the scanf. then I get some Microsoft runtime error... what's going wrong???
NOTE: this is homework, but i've got the logic figured out. what baffles me is this error.
#include <stdio.h>
int main()
{
unsigned int giveStr = 0;
char* charIt;
printf("Enter a number to be reversed.\t");
scanf("%d", &giveStr);
fflush(stdin);
sprintf(charIt, "%d", giveStr);
revStr(giveStr);
getchar();
return 0;
}
revStr(unsigned int n)
{
char buffer[100];
int uselessvar, counter = 0;
for (; n > 0;)
{
uselessvar = sprintf(&buffer[counter], "%d", n);
counter++;
}
for (counter = 0; counter > 0;)
{
printf("%c", buffer[counter]);
counter--;
}
return 0;
}
EDIT: flushing stdin for newlines :/ and also image here just not with that program. with mine.
You are trying to access memory which is not allocated in:
sprintf(charIt, "%d", giveStr);
Change char* charIt; to char charIt[50]; and all should be well (well, at least the segmentation fault part)
Also... pass charIt to revStr, as charIt contains the string with our number.
Then, a simple for loop in revStr will do the trick (what was the purpose of the second one, anyway?)
void revStr(char *giveStr)
{
int counter;
for (counter = strlen(giveStr)-1; counter >= 0; counter--)
{
printf("%c", giveStr[counter]);
}
printf("\n");
}
This will print each char our char representation has from the last one till the first one. You should read more on for loops.
For your home work problem, if you have the K&R book, turn to section 3.5 and read it thoroughly.
Note the functions reverse() and itoa(). They should give you a pretty good idea on how to solve your problem.
How does your program get out of the for (; n > 0;) loop? Won't counter simply increase until you get a bus error?
ED:
Respectfully, I think the claim that "i've got the logic figured out" is a little optimistic. :^) Doubtless someone will post the way it should have been done
by the time I'm done writing this, but it's probably worth drawing attention to what went wrong (aside from the memory allocation problems noted elsewhere):
Your first loop, "for (; n > 0;)", is strange because you're printing the entire number n into the buffer at counter. So why would you need to do this more than once? If you were selecting individual digits you might, but you're not, and obviously you know how to do this because you already used "sprintf(charIt, "%d", giveStr);". [Aside: giveStr isn't a great name for an unsigned integer variable!]
Your second loop also has strange conditions: you set counter to 0, set the condition that counter > 0, and then decrease counter inside. This obviously isn't going to loop over the characters in the way you want. Assuming you thought the first loop was character-by-character, then maybe you were thinking to loop down from counter-1 to 0?

Simply C loop is driving me nuts

So I have only ever programmed in c++, but I have to do a small homework that requires the use of c. The problem I encountered is where I need a loop to read in numbers separated by spaces from the user (like: 1 5 6 7 3 42 5) and then take those numbers and fill an array.
the code I wrote is this:
int i, input, array[10];
for(i = 0; i < 10; i++){
scanf("%d", &input);
array[i] = input;
}
EDIT: added array definition.
any suggestions or hints would be very highly appreciated.
Irrespective of whatever is wrong here, you should quickly learn to NEVER write code that does not check the return value from any API call that you make. scanf returns a value, and you have to be interested in what it says. If the call fails, your logic is different, yes?
Perhaps in this case it would tell you what's going wrong. The docs are here.
Returns the number of fields
successfully converted and assigned;
the return value does not include
fields that were read but not
assigned. A return value of 0
indicates that no fields were
assigned.
This code working good.
If your numbers is less than 10, then you must know how many numbers is before you start reading this numbers, or last number must be something like 0 to terminate output then you can do while(true) loop, but for dynamically solution you must read all line into string and then using sscanf to reading numbers from this string.
You need the right #include and a proper main. The following works for me
#include <stdio.h>
int main(void) {
/* YOUR CODE begin */
int i, input, array[10];
for (i = 0; i < 10; i++) {
scanf("%d", &input);
array[i] = input;
}
/* end of YOUR CODE */
return 0;
}
i'm not a c programmer but i can suggest an algorithm which is to use scanf("%s",&str) to read all the input into a char[] array then loop over it and test using an if statment if the current char is a space, if it is then add the preceeding number to the array

Resources