Assignment #5 Answers

Similar documents
Assignment #6 Answers


Introduction to C. CS2023 Winter 2004

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

ONE DIMENSIONAL ARRAYS

LESSON 4. The DATA TYPE char

Assignment #2 Answers

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

ARRAYS(II Unit Part II)

Lecture 12 CSE July Today we ll cover the things that you still don t know that you need to know in order to do the assignment.

Preprocessor Directives

C and C++ 2. Functions Preprocessor. Alan Mycroft

Slide Set 5. for ENCM 339 Fall Steve Norman, PhD, PEng. Electrical & Computer Engineering Schulich School of Engineering University of Calgary

C for C++ Programmers

Slide Set 6. for ENCM 339 Fall 2017 Section 01. Steve Norman, PhD, PEng

Chapter 8. More Control Statements

Assignment #4 Answers

8. Characters, Strings and Files

Control flow and string example. C and C++ Functions. Function type-system nasties. 2. Functions Preprocessor. Alastair R. Beresford.

Bil 104 Intiroduction To Scientific And Engineering Computing. Lecture 7

are all acceptable. With the right compiler flags, Java/C++ style comments are also acceptable.

Computer Programming & Problem Solving ( CPPS ) Turbo C Programming For The PC (Revised Edition ) By Robert Lafore

Personal SE. Functions, Arrays, Strings & Command Line Arguments

Jim Lambers ENERGY 211 / CME 211 Autumn Quarter Programming Project 2

CSCI 2132 Software Development. Lecture 8: Introduction to C

4. Structure of a C++ program

Chapter 8: Character & String. In this chapter, you ll learn about;

Computers Programming Course 10. Iulian Năstac

Chapter 8. Arrays, Addresses, and Pointers : Structured Programming Structured Programming 1

Chapter 8 Character Arrays and Strings

Problem Solving and 'C' Programming

Chapter 6: The C Preprocessor

Using Character Arrays. What is a String? Using Character Arrays. Using Strings Life is simpler with strings. #include <stdio.

SYSC 2006 C Winter String Processing in C. D.L. Bailey, Systems and Computer Engineering, Carleton University

gcc hello.c a.out Hello, world gcc -o hello hello.c hello Hello, world

String Class in C++ When the above code is compiled and executed, it produces result something as follows: cin and strings

Arithmetic Expressions in C

3. Functions. Modular programming is the dividing of the entire problem into small sub problems that can be solved by writing separate programs.

File I/O. Arash Rafiey. November 7, 2017

CS102: Variables and Expressions

Appendix G C/C++ Notes. C/C++ Coding Style Guidelines Ray Mitchell 475

Lecture 2: C Programming Basic

Intermediate Programming, Spring 2017*

2. Numbers In, Numbers Out

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG

CS1100 Introduction to Programming

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows

Write a C program using arrays and structure

Midterms Save the Dates!

Fundamentals of Programming Session 4

Understanding main() function Input/Output Streams

C++ Arrays. Arrays: The Basics. Areas for Discussion. Arrays: The Basics Strings and Arrays of Characters Array Parameters

Computers Programming Course 5. Iulian Năstac

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

QUIZ. 1. Explain the meaning of the angle brackets in the declaration of v below:

Computer Programming Unit v

C: Arrays, and strings. Department of Computer Science College of Engineering Boise State University. September 11, /16

Programming Style Guide v1.1

ET156 Introduction to C Programming

Chapter 13. Strings. Introduction

File Access. FILE * fopen(const char *name, const char * mode);

Basic C Programming. Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

printf( Please enter another number: ); scanf( %d, &num2);

QUIZ. Can you find 5 errors in this code?

M.CS201 Programming language

Chapter 9 Strings. With this array declaration: char s[10];

Assignment #3 Answers

Lab # 2. For today s lab:

COSC2031 Software Tools Introduction to C

mith College Computer Science CSC270 Spring 2016 Circuits and Systems Lecture Notes, Week 11 Dominique Thiébaut

QUIZ. What are 3 differences between C and C++ const variables?

Chapter 1 INTRODUCTION

Solutions to Assessment

CSE 333 Midterm Exam July 24, Name UW ID#

Creating a C++ Program

Grade Distribution. Exam 1 Exam 2. Exams 1 & 2. # of Students. Total: 17. Total: 17. Total: 17

AN OVERVIEW OF C. CSE 130: Introduction to Programming in C Stony Brook University

Lecture 6. Statements

Lecture 3 Tao Wang 1

Lecture 10: Potpourri: Enum / struct / union Advanced Unix #include function pointers

Array Initialization

C: How to Program. Week /Mar/05

C programming basics T3-1 -

CSC 270 Survey of Programming Languages. C-String Values

2. Numbers In, Numbers Out

Unit 4 Preprocessor Directives

Exercise 1.1 Hello world

Have examined process Creating program Have developed program Written in C Source code

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #54. Organizing Code in multiple files

CS201 Latest Solved MCQs

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

UEE1302 (1102) F10: Introduction to Computers and Programming

Final Exam 1 /12 2 /12 3 /10 4 /7 5 /4 6 /10 7 /8 8 /9 9 /8 10 /11 11 /8 12 /10 13 /9 14 /13 15 /10 16 /10 17 /12. Faculty of Computer Science

Iteration. Side effects

BSM540 Basics of C Language

A Fast Review of C Essentials Part I

C introduction: part 1

BSM540 Basics of C Language

CS102: Standard I/O. %<flag(s)><width><precision><size>conversion-code

Transcription:

Assignment #5 Answers Introductory C Programming UW Experimental College Assignment #5 ANSWERS Question 1. What's wrong with #define N 10;? The semicolon at the end of the line will become part of N's definition, which is hardly ever what you want. Question 2. Suppose you had the definition #define SIX 2*3. What value would the declaration int x = 12 / SIX; initialize x to? 18. (18? How could it be 18? It sure looks like it should be 2, doesn't it?) The preprocessor performs a simple textual substitution; it knows nothing about operator precedence, or even much about the syntax of C. After the preprocessor substitutes the value of the macro SIX, the declaration looks like int x = 12 / 2*3; Since multiplication and division ``group'' (or ``associate'') from left to right, this is interpreted as int x = (12 / 2) * 3; To guard against these ``surprises,'' it's a very good idea to parenthesize the values of macros which are not simple constants. In this case, a safer definition of the macro would have been #define SIX (2*3) This way, when the preprocessor performs its simple textual substitution, the resulting expression is automatically parenthesized so that the compiler gives you the result you expect. (Of course, this hypothetical SIX macro is useless in any case, but the point is that whenever a macro's value is an expression of any kind, it needs extra parentheses to avoid surprises.) Question 3. If the header file x.h contains an external prototype declaration for a function q(), where should x.h be included? http://www.eskimo.com/~scs/cclass/asgn.beg/ps5a.html (1 of 6)10/31/2005 2:33:07 PM

It should be included in each source file where q() is called, so that the compiler will see the prototype declaration and be able to generate correct code. It should also be included in the source file where q() is defined, so that the compiler will be able to notice, and complain about, any mismatches between the prototype declaration and the actual definition. (It's vital that the prototype which will be used where a function is called be accurate; an incorrect prototype is worse than useless.) Question 4. How many differences can you think of between i and J? The line int i = 10; declares a conventional run-time variable, named i, initially containing the value 10. It will be possible to change i's value at run time. i may appear in expressions (i.e., its value may be fetched), but since it is not constant, it could not be used where C requires a constant, such as in the dimension of an array declaration. The line #define J 10 on the other hand, defines a preprocessor macro named J having the value 10. For the rest of the current source file, anywhere you write a single J, the preprocessor will replace it with 10. An array declaration such as int a[j]; will be fine; it will be just as if you had written int a[10]; However, J exists only at compile time. It is not a run-time variable; if you tried to ``change its value'' at run time by writing J = 20; it would be just as if you had written 10 = 20; http://www.eskimo.com/~scs/cclass/asgn.beg/ps5a.html (2 of 6)10/31/2005 2:33:07 PM

and the compiler would complain. (One more little difference is that the line int i = 10; ends in a semicolon, while the line #define J 10 does not.) Exercise 2. Write a program to read its input and write it out, double-spaced. This is easy if we realize that all we have to do is read the input a character at a time, copying each input character through to the output, except that whenever we see a '\n' character, write a second one out, too. #include <stdio.h> int main() int c; while((c = getchar())!= EOF) putchar(c); if(c == '\n') putchar('\n'); return 0; The program won't be too interesting if you type text at it interactively. If you're using a Unix or MS- DOS system, you can run it on a file by typing doublespace < filename The < mechanism indicates that the program should be run with its ``standard input'' (i.e. the stream of characters read by getchar) connected to the file with the given filename, rather than to the keyboard. Exercise 3. Write a function which counts the number of times a character appears in a string. Here is the function. Notice that it is very similar to the mystrlen function in the notes, except that rather than counting all characters in the string, it only counts those matching the argument c. int countnchars(char string[], int ch) http://www.eskimo.com/~scs/cclass/asgn.beg/ps5a.html (3 of 6)10/31/2005 2:33:07 PM

int i; int count = 0; for(i = 0; string[i]!= '\0'; i++) if(string[i] == ch) count++; return count; Here is a tiny little main program, to test it out: #include <stdio.h> extern int countnchars(char string[], int ch); int main() char string[] = "Hello, world!"; char c = 'o'; printf("the letter %c appears in \"%s\" %d times.\n", c, string, countnchars(string, c)); return 0; Exercise 4. Write a short program to read two lines of text, and concatenate them using strcat. #include <stdio.h> #include <string.h> /* for strcpy and strcat */ #define MAXLINE 100 extern int getline(char [], int); int main() char string1[maxline], string2[maxline]; int len1, len2; char newstring[maxline*2]; printf("enter first string:\n"); http://www.eskimo.com/~scs/cclass/asgn.beg/ps5a.html (4 of 6)10/31/2005 2:33:07 PM

len1 = getline(string1, 100); printf("enter second string:\n"); len2 = getline(string2, 100); if(len1 == EOF len2 == EOF) exit(1); strcpy(newstring, string1); strcat(newstring, string2); printf("%s\n", newstring); return 0; Exercise 5. Write a function to find a substring in a larger string and replace it with a different substring. Here is one way. (Since the function doesn't return anything, I've defined it with a return type of void.) void replace(char string[], char from[], char to[]) int start, i1, i2; for(start = 0; string[start]!= '\0'; start++) i1 = 0; i2 = start; while(from[i1]!= '\0') if(from[i1]!= string[i2]) break; i1++; i2++; if(from[i1] == '\0') for(i1 = 0; to[i1]!= '\0'; i1++) string[start++] = to[i1]; return; http://www.eskimo.com/~scs/cclass/asgn.beg/ps5a.html (5 of 6)10/31/2005 2:33:07 PM

This code is very similar to the mystrstr function in the notes, chapter 10, section 10.4, p. 8. (Since strstr's job is to find one string within another, it's a natural for the first half of replace.) Extra credit: Think about what replace() should do if the from string appears multiple times in the input string. Our first implementation replaced only the first occurrence (if any) of the from string. It happens, though, that it's trivial to rewrite our first version to make it replace all occurrences--just omit the return after the first string has been replaced: void replace(char string[], char from[], char to[]) int start, i1, i2; for(start = 0; string[start]!= '\0'; start++) i1 = 0; i2 = start; while(from[i1]!= '\0') if(from[i1]!= string[i2]) break; i1++; i2++; if(from[i1] == '\0') for(i1 = 0; to[i1]!= '\0'; i1++) string[start++] = to[i1]; This page by Steve Summit // Copyright 1995-9 // mail feedback http://www.eskimo.com/~scs/cclass/asgn.beg/ps5a.html (6 of 6)10/31/2005 2:33:07 PM