1

My program is to find out if in the input any char is immediate repeated.For example

input::

5

RRRRR

expected output::

4

as R repeated 4 times

but given output is 2

I have tried with 2 different program.But output seems to be same.

First tried program

#include<stdio.h>
int main()
{
    char input[51];

    int n, i, count=0;

    scanf("%d",&n);

    for(i=0;i<n;i++)
    {
        scanf("%c",&input[i]);
    }

    for(i=1;i<n;i++)
    {
        if(input[i]==input[i-1])
            count++;
    }

    printf("%d\n",count);
}

2nd tried Program

#include<stdio.h>
int main()
{
    char a, b;

    int n, i, count=0;

    scanf("%d",&n);
    scanf("%c",&a);

    for(i=1;i<n;i++)
    {
        scanf("%c",&b);
        if(a==b)
            count++;
        else
            a=b;
    }

    printf("%d\n",count);
}

Here n is the number of char to be entered.So can anyone help me to findout where i am going wrong?

Community
  • 1
  • 1
mahin hossen
  • 175
  • 9
  • 3
    `scanf("%c",&b);` -->`scanf(" %c",&b);` note space before `%c`. – kiran Biradar Dec 06 '18 at 15:50
  • I suspect [one of many, many, *many* duplicates is here](https://stackoverflow.com/questions/20306659/the-program-doesnt-stop-on-scanfc-ch-line-why) – WhozCraig Dec 06 '18 at 15:51
  • Possible duplicate of [The program doesn't stop on scanf("%c", &ch) line, why?](https://stackoverflow.com/questions/20306659/the-program-doesnt-stop-on-scanfc-ch-line-why) – mschuurmans Dec 06 '18 at 15:54
  • thanks @kiranBiradar i did it and it seems worked out,.Can u tell me why it worked?when i **scanf("%c",&b); -->scanf(" %c",&b);** did this? – mahin hossen Dec 06 '18 at 16:00

1 Answers1

1

I got it, whenever we use scanf and at last of input, we use "ENTER".but the "%c" in second scanf takes it as input.so in upper problem my program should be 1st program

#include<stdio.h>
int main()
{
    char input[51];

    int n, i, count=0;

    scanf("%d",&n);

    for(i=0;i<n;i++)
    {
        scanf(" %c",&input[i]);
    }

    for(i=1;i<n;i++)
    {
        if(input[i]==input[i-1])
            count++;
    }

    printf("%d\n",count);
}

2nd Program

#include<stdio.h>
int main()
{
    char a, b;

    int n, i, count=0;

    scanf("%d",&n);
    scanf(" %c",&a);

    for(i=1;i<n;i++)
    {
        scanf(" %c",&b);
        if(a==b)
        {
            count++;
        }
        else
            a=b;
    }

    printf("%d\n",count);
}

In above all program notice %c is placed with a heading space.

mahin hossen
  • 175
  • 9