problem in program :(

well in this program while i was debugging my cursor fly over two while statements can any one describe my why
-----> (where problem is)


#include<conio.h>
#include<stdio.h>
void main ()
{
char arr[20];
int i=0,j=0,k=0;
int a;
printf("enter alphabets\n");

while((arr[i]=getche())!='\r');
{
i=i+1;
}
;
printf("\n\nstring in lower case\n");
-----> while (arr[j]!='\r')
{
//upper case to lower case
if (arr[j]>=65&&arr[j]<=90)
{
arr[j]=arr[j]+32;
}
printf("%c",arr[j]);
j++;
}

printf("\n\nstring in upper case\n");
------> while (arr[k]!='\r')
{
//lower case to upper case
if (arr[k]>=97&&arr[j]<=122)
{
arr[k]=arr[k]-32;
}
printf("%c",arr[k]);
k++;
}

getch();
}
Could you be more specific as to the problem? conio.h is a nonstandard header (which my system doesn't have.)

In the first while loop, you don't have anyway to ensure you're not exceeding the bounds of arr.

1
2
while ( i<sizeof(arr)  &&  (arr[i++]=getche()) != '\r' )
    ; 


Of course, then the following loop conditions should also change as there may not be a '\r' in the array:

1
2
3
4
5
6
while ( j < i )
{
    if ( arr[j] >= 'A'  &&  arr[j] <= 'Z' )
        arr[j] = arr[j] -'A' + 'a' ;
    // ...
}

1
2
3
4
5
while((arr[i]=getche())!='\r')    ; // <--- semicolon not needed
{
    i=i+1;
}
; // another not needed, but harmless here. 


The first loop has an extraneous semicolon on line 1. That means counter i is never incremented, all the input is stored in arr[0]

Other than the semicolon, it's fine - though Cire is correct that you risk exceeding the array boundary.

But personally I'd prefer to replace the stored '\r' with the null character in the array. That means it can then be treated as a standard null-terminated string, for example using puts(arr).

My idea, just for consideration as an alternative, in the final loop.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include<conio.h>
#include<stdio.h>

void main ()
{
    char arr[200];
    int i=0;
    int j=0;
    int k=0;
    int a;

    printf("enter alphabets\n");

    while ( (arr[i]=getche()) != '\r')
    {
        i=i+1;
    }

    arr[i] = '\0'; // add null terminator

    printf("\n\nstring in lower case\n");

    while (arr[j] != '\0')
    {
        //upper case to lower case
        if (arr[j]>=65&&arr[j]<=90)
        {
            arr[j]=arr[j]+32;
        }
        printf("%c",arr[j]);
        j++;
    }

    printf("\n\nstring in upper case\n");
    while (arr[k])
    {
        //lower case to upper case
        if (arr[k]>=97&&arr[j]<=122)
        {
            arr[k]=arr[k]-32;
        }
        k++;
    }

    puts(arr);

    getch();
}


Notice line 35 is simpler this way. while (arr[k])
Last edited on
well you both are true ,, helped me a lot thanks :D
Topic archived. No new replies allowed.