How to find if all brackets are balanced (C) [closed] - c

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
So I have an array full of brackets, for example :
1) (()())())((())(())
2) ()((()()))
Any open bracket ( '(' ) should also be closed by another one (')')
So for example 1) ->
(()())())((())(()) -> (....)..)((..)(..) -> ())(()() -> .)(.. , so the answer is no because from here we can see that not all of the brackets are balanced
For example 2) ->
()((()())) -> .((..)) -> (()) -> (..) -> () -> .. , so here the answer is yes because all brackets are balanced. In this case, I would also like to print the positions of all couples of brackets that are balanced, for example :
1,2 & 5,6 & 7,8 & 3,10 & 4,9
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

In your case, it's as simple using a counter. Increment for (, and decrement for ). It shouldn't go under 0, and should be 0 in the end if balanced.
You may consider using a stack, if you're creating some syntax parser like the compilers and interpreters do.
EDIT: you need to use a stack to print out the pairs. You need to implement a stack by hand in C, so the following is reference code in C++.
std::stack<int> s;
switch(string[i]) {
case '(':
s.push(i);
break;
case ')':
if(!s.empty()) {
printf("%d, %d\n", s.top(), i);
s.pop();
} else {
// Fail here
}
break;
}
if(!s.empty()) // Fail here

Count opening and closing brackets:
const char* it;
int open_n = 0, close_n = 0;
/* Assume array is zero terminated.
* Otherwise condition: 'it != &array[ArraySize]' instead '*it' */
for(it = &array[0]; *it ; ++it) {
switch( *it ) {
case '(': open_n += 1; break;
case ')': if( open_n ) { close_n += 1; break; }
else { return false; /* ErrorCloseWithoutOpen */ }
default: break;
}
}
return open_n ? false : true;

Related

For Loop Without Init,Condition, Increment [duplicate]

This question already has answers here:
Endless loop in C/C++ [closed]
(12 answers)
Closed 4 years ago.
Hey guys i stumble upon a code online which was written in C language and while reading the codes i saw the for loop did not have initialization,condition nor the increment. The loop looked like this.
for (;;)
{
bool main_flag = false;
while (main_flag == false)
{
displayMainMenu();
switch (main_input)
{
case 1: addCar(head, tail); main_flag = true; break;
case 2: removeCar(head, tail); main_flag = true; break;
case 3: display(head, tail); main_flag = true; break;
case 4: printf("Terminating..."); return 0;
default: printf("\nINVALID INPUT!\nTRYAGAIN !\n");
}
}
}
Anyone able to explain to me what kind of for loop is that and how does it work? thanks alot
It is exactly doing what it implies: There is no condition to stop the loop, hence it is actually an endless loop.
So
for(;;) {}
is essentially the same as
while(true) {}
The only way to get out of the loop is to use a break or a return.

break statement doesn't work in a loop [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I saw a tutorial that explaining how to use the "break" statement in a loop
but every time i'm trying to use it i'm getting a compilation error saying:
"break statement not within loop or switch
break;"
This is my code:
if (finalFirstChar > 6 || finalFirstChar < 1)
{
printf("You didn't entered a proper number! \n");
break;
}
FWIW, if is a condition (selection statement, to be exact), and break works in a loop (iteration statement)/switch-case statement.
As per C11, chapter ยง6.8.6.3
A break statement shall appear only in or as a switch body or loop body.
In any case, you don't need a break in a if statement body.
OK:
while (cond1) {
if (cond2) break; /* or continue; */
if (cond3) return [something];
}
for (init; cond4; after) {
if (cond5) break; /* or continue; */
if (cond6) return [something];
}
do {
if (cond7) break; /* or continue; */
if (cond8) return [something];
} while (cond9);
if (cond10) return [something];
NOT OK:
if (cond11) { /* not in any while/do/for loop, or case switch */
break; /* or continue; */
}

Equal to operator "==" is behaving like assignment operator "=" [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am facing a very strange problem.
- I have an if condition:
if((IN_SYNC == sync_flag) || (cycle_number == spi_slot_number))
Before the condition, the variable "spi_slot_number" is '7' and after the if condition it was turned to '0' (which is the value of "cycle_number") !!!
Does any one knows how can such thing happen ?!
Important notes:
1- My code is in C language.
2- I checked the stack before and after the condition to make sure no stack corruption happening.
3- My program is one thread program, so no interrupts or other threads can interrupt.
4- If I commented the if condition , every thing goes fine.
5- I don't know how to generate the assembly code ...
As said by others, you haven't shared enough code to actually identify where your problem is. One thought that occurred to me however is the IN_SYNC identifier. It's a standard coding convention to put macros in all caps, and if it is a macro, it's possible that it's doing the dirty deed. Check for definition of IN_SYNC.
One other thing -- your if test has two tests, separated by an || operator. Try breaking the two tests apart to see which one is causing your side effect. Something like this:
printf("%d \n", spi_slot_number);
if (IN_SYNC == sync_flag) {
/* do nothing */
}
printf("after IN_SYNC test %d \n", spi_slot_number);
if (cycle_number == spi_slot_number) {
/* do nothing */
}
printf("after cycle_number test %d \n", spi_slot_number);
What happens if you do comparision on temporal copy of spi_slot_number? Does it work as expected?
void GetData(slot_id_T spi_slot_number, uint8_t* data_received,
uint16_t data_length, uint8_t data_is_valid_flag)
{
uint8_t cycle_number;
slot_id_T copy = spi_slot_number; // <- ADDED
cycle_number = GetCycleNumber() + 1;
if(cycle_number > LAST_CYCLE)
{
cycle_number = 0;
}
printf("%d \n", spi_slot_number);
if((IN_SYNC == sync_flag) || (cycle_number == copy)) // <- CHANGE
{
printf("%d \n", spi_slot_number);
switch(data_is_valid_flag)
{
case DATA_IS_VALID:
SendData(spi_slot_number, p_buffer, data_length);
break;
case DATA_IS_NOT_VALID:
IndicateDataNotValid(spi_slot_number, p_buffer, data_length);
break;
default:
/* Do Nothing */
break;
}
}
}

adding of alternative node which contain interger value in give linked list? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Hi i wrote a code to add alternative node which contain integer value in single linked list.My code get crash please help me to fix it.
example lets take there are 6 node in singly linked list 3 5 8 6 4 9
then o/p should be 3+8+4 and 5+6+9 and my approach is wrong i guess please help me to fix it .In below code i am returning only one alternative value i.e 3+8+4 ?
void add(struct st **ptr)
{
struct st *curr,*prev;
curr=*ptr;
while(curr->next!=NULL)
{
if(curr->next->next->data!=NULL) //checking alternative node is present or
//or not and to avoid crash
{
sum= curr->data + curr->next->next->data;
}
else
{
sum= curr->data;
}
curr= curr->next;
}
prev=*ptr;
while(prev->next !=null)
{
prev=prev->next;
if(prev->next->next->data!=NULL)
{
sum=prev->data+prev->next->next->data;
}
else
{
sum=prev->data;
}
}
return sum;
}
First of all, It is not possible to return twice from a function. You can use call by reference as an alternative to it. Before the function call you can create two variables for two sums, initialize them to zero and send them as reference.
int sum_even = 0; //sum of elements at even position
int sum_odd = 0; //sum of elements at odd position
add(&start, &sum_even, &sum_odd); // call by reference
//sum_even and sum_odd will have the respective sums
Now for problem on linked lists it is advisable that you sit with pen and paper and try to trace each line of code you write. Testing boundary conditions is essential.
I have written a possible solution for your problem.
void add(struct st **ptr, int *sum_even, int *sum_odd)
{
struct st *even, *odd;
even = *ptr;
if(even->next) odd = even->next;
else odd = NULL;
while(even != NULL)
{
*sum_even += even->data;
if(even->next == NULL) break;
even = even->next->next;
}
while(odd != NULL)
{
*sum_odd += odd->data;
if(odd->next == NULL) break;
odd = odd->next->next;
}
}
if(curr->next->next->data!=NULL)
Here you should also check curr->next->next is not NULL.
Also, your if condition is also not correct. You should check for next!=NULL than data.
So update your ifs to
if(curr->next->!=NULL && curr->next->next->data!=NULL)
Also, try to use gdb or some other debugger to debug and see why your program is crashing and what are the problems.

Case/Break and '{' in my function [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm working on my latest new function. Any explanations would be great since I'm new to programming. I couldn't figure out how to fix this because the errors I got are:
18 syntax error before '{' token
20 case label not within a switch statement
21 (same as above)
22 (same as above)
23 `default' label not within a switch statement
29 [Warning] `return' with a value, in function returning void
32 [Warning] assignment makes pointer from integer without a cast
34 [Warning] `return' with a value, in function returning void
void moveCar(char board[], char vehicle, char direction, int distance)
{
int i;
int position, newPosition;
int offset;
for (i = 0; i < size; i++) //the main loop for the vehicles and user's input
{
if(isalpha(vehicle))//vehicles for all letters but 'x'
{
if(board[i] == vehicle)//vehicles on board
{
swtich(direction)
{
case 'r': offset = 1; break;
case 'l': offset = -1; break;
case 'u': offset = -8; break;
case 'd': offset = 8; break;
default: printf("invalid direction"); break;
newPosition = position + offset;
if(newPosition != '.')
{
printf("invalid move.");
return 0;
}
board = '.';
board[newPosition] = vehicle;
return 1;
}
}
}
}
It looks like you have a typo of Switch as Swtich, the compiler won't recognize it, and the case statements will fail to compile.
Additionally you close your switch statement too early. If you want those commands to execute only in default move them before the break. If you want them to execute for every case move them outside of the switch statement entirely

Resources