{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

midterm solutions

# midterm solutions - contains.c#include int...

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

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

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

View Full Document
#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);
} top = 0; i = 0; // Scan string to see if it is balanced while (str[i]!=0) { if (str[i]=='(') { stack[top]='('; top++; } else if (str[i]=='{') { stack[top]='{'; top++; } else if (str[i]==')') { // Make sure that the ')' is matched with a '(' if (top<=0 || stack[top-1]!='(') {

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

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### Page1 / 7

midterm solutions - contains.c#include int...

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

View Full Document
Ask a homework question - tutors are online