midterm solutions - contains.c #include <stdio.h> int...

Info iconThis preview shows pages 1–4. Sign up to view the full content.

View Full Document Right Arrow Icon
contains.c #include <stdio.h> int contains(char * hay, char * needle) { int i, j; // for all positions of hay i = 0; while (hay[i]!=0) { // Check if at this position i needle matches j = 0; while (hay[i+j] != 0 & needle[j] != 0 && hay[i+j]==needle[j]) { // Match this character. Go to next one j++; } if (needle[j]==0) { // Found match return 1; } i++; } return 0; } int main(int argc, char **argv) { if (argc<3) { printf("Usage: conatins hay needle\n"); exit(1); } if (contains(argv[1], argv[2])) { printf("Yes\n"); } else { printf("No\n"); } } fib.c
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
#include <stdio.h> int fib(int k) { if (k==0) { return 0; } else if (k==1) { return 1; } return fib(k-1) + fib(k-2); } int main() { int n; printf("n= "); scanf("%d", &n); printf("The %dth Fibonacci number is %d\n", n, fib(n)); } isbalanced.c #include <stdio.h> #define MAX 100 char stack[MAX]; int top; int main(int argc, char ** argv) { char * str; int i; if (argc != 2) { printf("Usage: isbalanced string\n"); exit(1); } str = argv[1]; if (strlen(str) > MAX) { printf("String larger than %d\n", MAX); exit(1);
Background image of page 2
} top = 0; i = 0; // Scan string to see if it is balanced while (str[i]!=0) { if (str[i]=='(') { stack[top]='(';
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 4
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 02/18/2012 for the course CS 240 taught by Professor Rego during the Fall '08 term at Purdue University-West Lafayette.

Page1 / 7

midterm solutions - contains.c #include &lt;stdio.h&gt; int...

This preview shows document pages 1 - 4. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online