Stekker Stekker - 1 year ago 48
C Question

Iteration (filtering out specific letters) using getchar in C

I'm new to C and I had written the following code:

for(i=0; i<25; ++i) {
if (ch == 'A' || ch == 'B'|| ch == 'C'|| ch == 'D'|| ch == 'a'|| ch == 'b'|| ch == 'c'|| ch == 'd'){

I expect my code to filter out the letters "a,b,c and d" AND show them as an output if and only if there is an A that can be paired with B (same for B) and C that can be paired with D. (output in uppercase)

I used for loop for this so that it would get the letters each time it enters the loop.

I do not want my code to include arrays.

An example input and expected output:


output: ACBD

It writes the first A because it's able to pair it with B but not the second A. Also it writes the C and D because they were able to be paired.

Answer Source

Some simple pseudo-code that shows a possible algorithm:


current_A = 0;

for(each character in the string)
    if (character == 'A')
        current_B = 0;
        for (each character2 in the string)
            if (character2 == 'B')
                if (current_A == current_B)
                    // Found matching A and B

If you should not start over from the beginning of the string when searching for a matching 'B' then just start from the position where you found the 'A'.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download