CMPT 130 Sample Final Solution

Similar documents
Senem Kumova Metin & Ilker Korkmaz 1

7th Marathon of Parallel Programming WSCAD-SSC/SBAC-PAD-2012

Stacks. Linear data structures

Module 816. File Management in C. M. Campbell 1993 Deakin University

Introduction to Java

Lecture 11 Doubly Linked Lists & Array of Linked Lists. Doubly Linked Lists

Illustration 1: Diagram of program function and data flow

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

Memory management. Announcements. Safe user input. Function pointers. Uses of function pointers. Function pointer example

The C Programming Language course syllabus associate level

1. Relational database accesses data in a sequential form. (Figures 7.1, 7.2)

Introduction to Lex. General Description Input file Output file How matching is done Regular expressions Local names Using Lex

C Programming. Charudatt Kadolkar. IIT Guwahati. C Programming p.1/34

1 Abstract Data Types Information Hiding

System Calls and Standard I/O

Number Representation

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Sources: On the Web: Slides will be available on:

Unit Write iterative and recursive C functions to find the greatest common divisor of two integers. [6]

Molecular Dynamics Simulations with Applications in Soft Matter Handout 7 Memory Diagram of a Struct

Answers to Review Questions Chapter 7

Informatica e Sistemi in Tempo Reale

MAX = 5 Current = 0 'This will declare an array with 5 elements. Inserting a Value onto the Stack (Push)

Embedded Programming in C/C++: Lesson-1: Programming Elements and Programming in C

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

Passing 1D arrays to functions.

10CS35: Data Structures Using C

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Chapter 2: Elements of Java

Output: struct treenode{ int data; struct treenode *left, *right; } struct treenode *tree_ptr;

/* File: blkcopy.c. size_t n

FEEG Applied Programming 5 - Tutorial Session

DNA Data and Program Representation. Alexandre David

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

C Interview Questions

Arrays in Java. Working with Arrays

Short Notes on Dynamic Memory Allocation, Pointer and Data Structure

Stack Allocation. Run-Time Data Structures. Static Structures

Chapter 13 Storage classes

C++FA 5.1 PRACTICE MID-TERM EXAM

J a v a Quiz (Unit 3, Test 0 Practice)

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

The Advantages of Dan Grossman CSE303 Spring 2005, Lecture 25

C Programming. for Embedded Microcontrollers. Warwick A. Smith. Postbus 11. Elektor International Media BV. 6114ZG Susteren The Netherlands

An Introduction to Assembly Programming with the ARM 32-bit Processor Family

Example 1/24. Example

Quiz 4 Solutions EECS 211: FUNDAMENTALS OF COMPUTER PROGRAMMING II. 1 Q u i z 4 S o l u t i o n s

COMPUTER SCIENCE. Paper 1 (THEORY)

(hours worked,rateofpay, and regular and over time pay) for a list of employees. We have

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

Data Structure with C

The programming language C. sws1 1

Pseudo code Tutorial and Exercises Teacher s Version

What Is Recursion? Recursion. Binary search example postponed to end of lecture

COMP 250 Fall 2012 lecture 2 binary representations Sept. 11, 2012

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

CP Lab 2: Writing programs for simple arithmetic problems

Object-Oriented Programming in Java

3. Convert a number from one number system to another

Tail call elimination. Michel Schinz

Client-server Sockets

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

A single register, called the accumulator, stores the. operand before the operation, and stores the result. Add y # add y from memory to the acc

Functions Recursion. C++ functions. Declare/prototype. Define. Call. int myfunction (int ); int myfunction (int x){ int y = x*x; return y; }

How To Write Portable Programs In C

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Tutorial on C Language Programming

As previously noted, a byte can contain a numeric value in the range Computers don't understand Latin, Cyrillic, Hindi, Arabic character sets!

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

arrays C Programming Language - Arrays

The Tower of Hanoi. Recursion Solution. Recursive Function. Time Complexity. Recursive Thinking. Why Recursion? n! = n* (n-1)!

The University of Alabama in Huntsville Electrical and Computer Engineering CPE Test #4 November 20, True or False (2 points each)

Introduction to Data Structures

Lecture 22: C Programming 4 Embedded Systems

Introduction to Programming (in C++) Loops. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

Example. Introduction to Programming (in C++) Loops. The while statement. Write the numbers 1 N. Assume the following specification:

CSC4510 AUTOMATA 2.1 Finite Automata: Examples and D efinitions Definitions

Data Structures. Algorithm Performance and Big O Analysis

Regression Verification: Status Report

ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters

The following themes form the major topics of this chapter: The terms and concepts related to trees (Section 5.2).

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Computer Science 2nd Year Solved Exercise. Programs 3/4/2013. Aumir Shabbir Pakistan School & College Muscat. Important. Chapter # 3.

Object Oriented Software Design II

Software security. Buffer overflow attacks SQL injections. Lecture 11 EIT060 Computer Security

File Handling. What is a file?

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Example of a Java program

Coding Rules. Encoding the type of a function into the name (so-called Hungarian notation) is forbidden - it only confuses the programmer.

Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6)

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Basics of I/O Streams and File I/O

Introduction to Python

Displaying a Numerical Value on HyperTerminal (or equ.)

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

HOMEWORK # 2 SOLUTIO

VB.NET Programming Fundamentals

System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :

Transcription:

CMPT 130 Sample Final Solution Last name exactly as it appears on your student card First name exactly as it appears on your student card Student Number SFU Email This is a 180 minute test. It is closed book: no calculators, computers, notes, books, etc. are allowed. Question Your mark Out of What's Printed 20 Multiple Choice 5 Memory 7 Fragments 9 Structures 10 Perfect Numbers 8 Binary to Decimal 8 Total Page 1 of 10

Question 1: What s Printed? Show what would be printed by each of the statements shown below. int i; for(i = 0; i < 4; ++i) printf("%d ", i+1); The next 7 questions are related to each other int arr1[] = 2,4,6,8,10; int* p = arr1; int s = 0; int* q; printf("\n%d\n", sizeof(arr1)); 1,2,3,4 20 printf("%d\n", sizeof(p)); 4 printf("%d\n", sizeof(*p)); 4 printf("%d\n", *p); 2 printf("%d\n", arr1[3]); 8 for(q = arr1; q < arr1 + 5; s += *q++); printf("%d\n", q-p); 5 printf("%d\n", s); 30 long long yy = 0; int x = 412; printf("%d\n%d\n", yy, x); 0 0 int hex = 163; printf("%x\n", hex); a3 Page 2 of 10

The next 8 questions are related to each other char str1[15] = "hades"; char str2[15] = "haddock"; printf("%d\n", sizeof(str1)); 15 printf("%d\n", strlen(str1)); 5 putchar(str1[3]); e printf("\n%d\n", str1[6]); 0 fputs(str2, stdout); if(strncmp(str1, str2, 3) == 0) printf("\nsame\n"); else printf("different\n"); printf(strcat(str1, ", pluto")); haddock same hades, pluto printf("\n%d\n",str1[2] - str1[1]); 3 if(7 < 5 3 && 3!= 4) printf("true\n"); else printf("false\n"); int start = 0; int end = 0; while(start < 100) start++; if(start % 2 == 1) continue; if(start == 8) break; end++; printf("%d\n", end); true 3 Page 3 of 10

Question 2: Multiple Choice Which of the following are likely to result in a stack overflow? 1. A recursive function with no base case 2. An infinite loop that does not contain variable declarations 3. Allocating space in automatic memory for many large structures 4. Allocating space in dynamic memory for many large structures a. 1 and 3 b. 1, 2 and 3 c. 1 only d. 1, 2, 3 and 4 Which of the following correctly allocates spaces in dynamic memory for an array of 100 doubles? a. double* p = malloc(100, sizeof(double)); b. double* p = malloc(100 * sizeof(double)); c. double* p = malloc(100 * sizeof(int)); d. double* p = calloc(100 * sizeof(double)); a Which of the following placeholders would be appropriate for displaying right justified, positive floating point numbers less than one million to three decimal places. Assume that a column of such numbers is to be displayed so that they line up. a. "%-6.3f" b. "%6.3f" c. "%-10.3f" d. "%10.3f" What is printed by the call to f shown below? printf("f(5) = %d", f(5)); a. f(5) = 5 b. f(5) = 32 c. nothing, f does not compile d. f(5) = 10 int f(int x) if(x > 1) return 2 * f(x - 1); else if(x == 1) return 2; else return x; Which of the following is the best description of the error in the statements shown below: b d b int arr[] = 1,2,3,4; arr = int[10]; a. The variable arr is declared twice b. An array cannot be initialized with a bracketed list of values c. An array variable must be specified with a constant or a literal d. A previously declared array variable cannot be assigned another array d Page 4 of 10

Question 3: Memory 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 #include "stdio.h" #include "stdlib.h" int num = 33; int glob = 42; static int fill = 113; int bar(int* aa, int bb); int main() int i; int num = 10; int x = 100; int* arr = calloc(num, sizeof(int)); for(i = 0; i < num; ++i) int x; x = i * 2; arr[i] = x; printf("%d\n", bar(&num, x)); printf("%d\n", bar(&num, x)); printf("%d, %d\n", bar(&x, x), num); free(arr); return 0; int bar(int* a, int b) static int count = 0; ++(*a); b++; count++; return count; For each variable state the line numbers corresponding to its scope. Example line 05 glob 05 to 38 line 06 fill 06-38 line 08 aa 08 line 13 num 13-29 line 14 x 14-16, 22-29 line 18 x 18-20 State the variables' storage locations. Select static, automatic or dynamic. line 05 glob line 15 arr static line 15 - data assigned to arr line 33 count line 31 b automatic static automatic dynamic What is printed by the last print statement (line 25)? 3, 10 Is the linkage of fill (line 06) internal or external? internal or external. internal (because of static) Page 5 of 10

Question 4: Fragments Complete the program fragment shown to the right by writing a while loop that repeatedly prompts the user to guess a number. The loop should terminate when the guess is equal to the answer. Sample Output Guess the number! 12 Guess the number! 6 Guess the number! 19 Guess the number! 4 Guess the number! 17 Congratulations! Complete the program fragment shown to the right by writing a for loop that prints all of the integers between start and end, with each integer printed on a separate line. If start is greater than end nothing should be printed. Sample Output Enter the start value: -2 Enter the end value: 3-2 -1 +0 +1 +2 +3 Complete the program fragment shown to the right by writing an if statement that checks to see if the three variables are all equal to each other, all are different, or if just two are equal. Sample Output (3 different executions) Enter three numbers: 2 3 4 they are all different Enter three numbers: 5 6 5 they are all the same Enter three numbers: 4 3 4 only two are the same int answer = rand()%20; int guess = 0; while(answer!= guess) printf("guess the number! "); scanf("%d", &guess); printf("congratulations!\n"); int i, start, end; printf("enter the start value: "); scanf("%d", &start); printf("enter the end value: "); scanf("%d", &end); for(i = start; i <= end; ++i) printf("%+2d\n", i); int x, y, z; printf("enter three numbers: "); scanf("%d%d%d", &x, &y,&z); if(x == y && x == z) printf("they are all the same\n"); else if(x!= y && x!= z && y!= z) printf("they are all different\n"); else printf("only two are the same\n"); Page 6 of 10

Question 5: Structures 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 #include "stdio.h" #include "stdlib.h" #define FNAME_LEN 20 #define NAME_LEN 10 #define MAX_AC 10 typedef struct char name[name_len]; float balance; account; account foo(account* pacc, int size); int main() char fname[fname_len]; account bank[max_ac]; FILE* fp; int readresult = 2; int size = 0; account smacc; account test = "bob", 1100.00; account* pacc = &test; printf("enter a file name: "); gets(fname); if((fp = fopen(fname, "r")) == NULL) printf("error 1"); exit(1); readresult = fscanf(fp, "%s%f", bank[size].name, &bank[size].balance); if(readresult!= 2) printf("error 2"); exit(1); while(readresult == 2) size++; readresult = fscanf(fp, "%s%f", bank[size].name, &bank[size].balance); printf("%s\n", test.name); printf("%.2f\n", pacc->balance); printf("%s\n", bank[0].name); printf("%c\n", bank->name[0]); account foo(account* pacc, int size) int i; account result = pacc[0]; for(i = 1; i < size; ++i) if(pacc[i].balance < result.balance) result = pacc[i]; return result; smacc = foo(bank, size); printf("name = %s, balance = %.0f\n", smacc.name, smacc.balance); return 0; Page 7 of 10

The questions on this page (except the two multiple choice questions) relate to the program shown on page 7. Show what is printed by the program for each of the three input files shown below. Note that there is no file called loans3.txt! contents of loans1.txt Bruce 8954.12 Diana 212.89 Clark 32.58 Peter 12.47 Dinah 257.00 Bob Sue Kate contents of loans2.txt no file called loans3.txt exists Enter a file name: loans1.txt bob 1100.00 Bruce B name = Peter, balance = 12 Enter a file name: loans2.txt error 2 Enter a file name: loans3.txt error 1 Which of the following statements will open a file called vip.txt without over-writing its data, and allow data to be added to the end of the file, and allow the contents of the file to be read? a. FILE* fp = fopen(fname, "w+"); b. FILE* fp = fopen(fname, "w"); c. FILE* fp = fopen(fname, "a+"); d. FILE* fp = fopen(fname, "w"); Which of the following function calls would write a double array of size 100 (called arr) to a binary file which is pointed to by the file pointer fp? a. fwrite(arr, sizeof(double), 100, fp); b. for(i=0; i < 100; ++i) fwrite(arr[i], sizeof(double), 100, fp); c. for(i=0; i < 100; ++i) fprintf(fp, "%f", arr[i]); d. fread(arr, sizeof(double), 100, fp); c a Page 8 of 10

Question 6: Perfect Number A perfect number is a positive number that is equal to the sum of its proper positive divisors (a proper divisor is a positive divisor of a number, excluding the number itself). For example 6 is a perfect number, since its divisors are 3, 2 and 1. Write a function with a single integer parameter that returns 1 if its parameter is a perfect number and 0 if it is not. Examples int isperfect = perfect(6); // isperfect = 1 isperfect = perfect(8); // isperfect = 0 int perfect(int x) int sum = 0; for(int i = 1; i < x; ++i) if(x % i == 0) sum += i; if(sum == x) return 1; else return 0; Page 9 of 10

Question 7: Binary to Decimal Write a function that takes a string representation of a binary number and returns the decimal equivalent. Your function should have a single character array parameter and should return an integer. Examples int bin = binarytodecimal("11111"); // bin = 31 bin = binarytodecimal("101010"); // bin = 42 bin = binarytodecimal("-100"); // bin = -4 int binarytodecimal(char bin[]) int result = 0; int power = 1; char ch; for(int i = strlen(bin)-1; i >= 0; i--) if(bin[i] == '1') result += power; power = power * 2; return result; Page 10 of 10