Introduction to C ++ : Questions

Similar documents
An Incomplete C++ Primer. University of Wyoming MA 5310

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

Basics of I/O Streams and File I/O

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

C++ INTERVIEW QUESTIONS

The C Programming Language course syllabus associate level

Curriculum Map. Discipline: Computer Science Course: C++

10CS35: Data Structures Using C

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

1 Description of The Simpletron

Chapter One Introduction to Programming

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

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

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

El Dorado Union High School District Educational Services

Member Functions of the istream Class

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

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

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

Moving from CS 61A Scheme to CS 61B Java

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

Informatica e Sistemi in Tempo Reale

Illustration 1: Diagram of program function and data flow

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

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 3: Input/Output

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

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

The programming language C. sws1 1

Symbol Tables. Introduction

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Class 16: Function Parameters and Polymorphism

C++ Programming Language

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

Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Hash Tables. Computer Science E-119 Harvard Extension School Fall 2012 David G. Sullivan, Ph.D. Data Dictionary Revisited

C++ Input/Output: Streams

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.

Object Oriented Software Design II

University of Hull Department of Computer Science. Wrestling with Python Week 01 Playing with Python

C++FA 3.1 OPTIMIZING C++

VHDL Test Bench Tutorial

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

C++FA 5.1 PRACTICE MID-TERM EXAM

PES Institute of Technology-BSC QUESTION BANK

Lab Experience 17. Programming Language Translation

Lab 2: Swat ATM (Machine (Machine))

How To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint)

Pseudo code Tutorial and Exercises Teacher s Version

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall

Ubuntu. Ubuntu. C++ Overview. Ubuntu. History of C++ Major Features of C++

Passing 1D arrays to functions.

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

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

Glossary of Object Oriented Terms

So far we have considered only numeric processing, i.e. processing of numeric data represented

BCS2B02: OOP Concepts and Data Structures Using C++

Answers to Review Questions Chapter 7

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

Chapter 5 Functions. Introducing Functions

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

Prime Time: Homework Examples from ACE

1 Abstract Data Types Information Hiding

Top 72 Perl Interview Questions and Answers

Appendix K Introduction to Microsoft Visual C++ 6.0

Semantic Analysis: Types and Type Checking

Bachelors of Computer Application Programming Principle & Algorithm (BCA-S102T)

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

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

Computer Programming I

Sequential Program Execution

Arrays. number: Motivation. Prof. Stewart Weiss. Software Design Lecture Notes Arrays

TECHNOLOGY Computer Programming II Grade: 9-12 Standard 2: Technology and Society Interaction

I PUC - Computer Science. Practical s Syllabus. Contents

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

Chapter 7: Additional Topics

The While Loop. Objectives. Textbook. WHILE Loops

DATA STRUCTURES USING C

Laboratory Assignments of OBJECT ORIENTED METHODOLOGY & PROGRAMMING (USING C++) [IT 553]

How To Write Portable Programs In C

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

Introduction to Programming System Design. CSCI 455x (4 Units)

Topics. Introduction. Java History CS 146. Introduction to Programming and Algorithms Module 1. Module Objectives

Object Oriented Software Design

Subject Name: Object Oriented Programming in C++ Subject Code:

CORBA Programming with TAOX11. The C++11 CORBA Implementation

The little endl that couldn t

A brief introduction to C++ and Interfacing with Excel

arrays C Programming Language - Arrays

Lab 2 - CMPS 1043, Computer Science I Introduction to File Input/Output (I/O) Projects and Solutions (C++)

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

Course Name: ADVANCE COURSE IN SOFTWARE DEVELOPMENT (Specialization:.Net Technologies)

Computing Concepts with Java Essentials

Tutorial on C Language Programming

Object Oriented Software Design

Transcription:

Introduction to C ++ : Questions Thomas Branch 28th November 204. A Tutorial Introduction. Getting Started Aim: Make sure the program compiles and runs, learn to get the program to output text. [Debug] Type out the Hello World program, and get it to compile and run. [Easy] Change the program to output Hello Your Name over two lines. [Internet] Have your program output the text in speech marks ( ), with the newlines, without using endl. What is the difference from using endl? (Hint: escape sequences).2 Variables and Arithmetic Expressions Aim: Learn to store data and manipulate data in variables, make loops with while. Watch out for Infinite loops, when conditions are not satisfied. [Easy] Output the numbers from 0 to 0, in increments of 0.5. (0, 0.5,,.5,... ) [Internet] What do the operators: +=, -=, *= and /= do, why are they useful? Use them in the program you just wrote. [Internet/hard] What are ++ & -- for? If you have an int a = 0,b;, what is the difference between b = a++ and b = ++a?.3 The For Statement Aim: See how the for loop is similar to the while loop. [Easy] Calculate the factorial (!) of an int n. (! =, 3! = 6, 6! = 720, 8! = 6402373705728000.) What happens for larger integers? How can you fix it? n! = n (n )... 2 () [Medium] Write a program that outputs a triangle of number up an int n, for n = 5 : (Hint: You need two for loops.) [Debugging Practice] Output Pascal s triangle: 2 2 3 2 3 4 2 3 4 5 2 3 3 4 6 4 5 0 0 5

The formula for generating the numbers is: ( ) n = n C r r = n! (n r)!r! (2) (No Functions! (except main)).4 If Statements If statements allow your program to branch into two directions depending on a condition. [Easy] Write a program that prints the numbers from to 50, but when it is a multiple of 3 prints foo, multiple of 5 prints bar, or a multiple of 3 and 5 prints bash. [Medium/Hard] Write a program that calculates prime numbers (numbers that are only divisible by and itself). Can you optimise it to run faster?.5 Symbolic Constants Symbolic constants remove the need for magic numbers in programs. [Easy] Use a symbolic constant or two somewhere. (There is not much to them until you use them with pointers)..6 Input and Output Aim: Read input into programs from files and the keyboard. [Easy] Edit one of the previous programs to read input from the keyboard, so it no longer needs to be recompiled each time you want to change a value. [Easy] Write a file with a list of 0 numbers in, then get your program to read in the numbers and calculate the mean and variance. x = x = n n x i σ 2 = x 2 x 2 (3) i= where x is the mean, n is the number of points, and σ 2 is the variance. Now you can do data analysis with C ++. [Internet] If you have an ifstream fin, what does fin.good() do and how is it different from fin.eof()? Rewrite the previous program to take an arbitrarily long list of numbers. [Game] Have the computer pick a random integer, and ask you to guess what the number is. Have it give you clues, on whether the number you guessed is < or > than it..7 Arrays & The Vector Class Arrays store lots of data of the same type, but are inflexible in the amount of data stored. Vectors allow you to choose the size at runtime, and change the amount of data stored, as sometimes you cannot know how much data you will get. [Medium] Make an array of random numbers and then sort them. (If you want you can get random numbers from the cstdlib library and using rand()). [Medium] Produce Pascal s triangle (See.3) using vector s and summing the elements, rather than the formula. [Puzzle] Print all possible combinations with repetitions, of the characters a, k, H,!. There are 4 4 = 256 of them. Try to write it in a generalisable way, so it could be easily extended to any number of characters or length. (Not 4 for loops nested inside each other). A possible sample output: aaaa kaaa Haaa!aaa akaa kkaa Hkaa!kaa ahaa khaa HHaa!Haa a!aa k!aa H!aa!!aa aaka kaka Haka!aka akka kkka Hkka!kka ahka khka HHka!Hka a!ka k!ka H!ka!!ka aaha kaha HaHa!aHa akha kkha... (Hint: Start by counting in base 4 using \ and % (00, 0, 02, 03, 0,, 2, 3, 20,... )). 2

[Puzzle Part II] Now try to the 24 permutations. (Hint: This can be done in a similar way with vector::erase. To remove the element at index n from a vector vec, use vec.erase(vec.begin() + n);.8 Functions Aim: Use functions to make code reusable and see how functions can be recursive by calling themselves. [Easy] Write a function that works out the factorial of a number, then reproduce pascals triangle, using the formulae method. It should be much easier now. [Easy] Write a function that multiplies a number by a unsigned int, but you cannot use * or *= or loops. [Medium] Find (through experimental means) out how many times a function can call itself recursively. Why is there a limit to the maximum recursion depth? [Internet] This time use a static variable. Is there a difference?.9 Arguments Call by Reference Calling by reference gives you access to original variable, instead of a copy of it. [Easy] Make a vector of int s then write a function that reverse the order of the int s in the vector, passing by reference(&). Why might you not want to pass the vector by value? [Internet] Now try using your function for a vector of strings s, C ++ can be made using the string library. Why doesn t it work? Use function overloading so that it does. Function overloading is having two functions with the same name but with different input arguments. [Internet/Medium] Write a generalised version of your function using templates, so you have one template function that works for vector s of both char and int. Why is this better than having two overloaded functions (even though this is equivalent)..0 External Variables and Scope External variables allow you to access a variable anywhere in your program, although they exist, they are best avoided. Scope is where you have access to a variable. [Easy] Write a program that prints out a number stored in a variable. What happens when the variable declaration is wrapped in {}? Does this still occur with for and while loops? [Internet] There is a scope resolution operator :: that you can use to get things out of namespaces. Write a program that prints out a number stored in a variable, but without using namespace std;. Why might you need to use :: sometimes? [Internet] Write your own function and put it in a namespace. 2. Pointers and Arrays 2. Pointers and Addresses A Pointer is a variable that stores the address (location) of another variable. [Easy] Make some variables and print out their sizes and addresses. [Easy] Make an int, and two pointers to it. Print out its value, then change the value with one pointer, and print it out with the other. 2.2 Pointers and Function Arguments This is very similar to passing by reference, but where & gives you access to the argument directly, * gives you its pointer. [Easy] Rewrite the reverse function to pass the vector as a pointer. [Medium] Make a vector of pointers to int s, and then sort the addresses in the vector so what they point to is in ascending order. [Easy] Write a function to which you pass a pointer by reference. Change the value of what it points to, and check its changed. 3

2.3 Address Arithmetic This allows you to change [Easy] Write a function that prints out the int s in a vector given, the address of the first int and the size of the vector. [Experimental] If you + to an address how much does it change by? if you type cast(e.g. (char*)) your pointer to different types before +, is there any difference? 2.4 Pointers and Arrays Arrays are really just pointers to blocks of memory. [Internet] On the slide, how many char s are there in the array (its not 26). What happens when you print it out with cout? What happens when you tell it there are 26 char s in the array(or 3 char b[3] = { a, b, c }), and why, what s special about ""?(if your program doesn t behave strangely it could do, try setting the next thing in memory to a ) (Hint: null terminating character) 2.5 Dynamic Memory Allocation 2.6 Pointer Arrays; Pointers to Pointers 2.7 Multi-dimensional Arrays 2.8 Command line arguments [Easy] Write a program that outputs files to screen, that are given as a command line arguments. (The Unix utility cat, does this, it is used for concatenating files, cat file file2 > outfile joins two files together using pipes) 2.9 Pointers to Functions [Easy] Write an iterate function that takes a function f(x) and repeatedly applies it up to r times to a value x, e.g. when r = 5, iterate(f, 5, x) would return {x, f(x), f(f(x)), f(f(f(x))), f(f(f(f(x)))), f(f(f(f(f(x)))))}. That is iterate(f, 5, 2) where f(x) = x + would return a vector containing {2, 3, 4, 5, 6, 7}, or if the function f(x) = x 2 it would return {2, 4, 8, 6, 32, 64}. [Medium] Write an integrating function that takes a double function(double), a stepsize and two limits, and integrates between them. 2.0 Void Type Pointers [Easy] Change the integrating function such that arguments could be passed to the function to be integrated. 3. Structures 3. Basics of Structures Structures group types together into a new type [Easy] Write a structure for a complex number and a function that returns the complex conjugate. (For future reference: Complex numbers are avaliable as part of complex library) 3.2 Operator Overloading Operator overloading allows you to reuse the operators for new things. [Easy] Write a function to calculate the dot product of two vectors using the operator*. [Medium] Overload the operator<< so that your structure will be printed with cout and ofstream s. (Hint: The type of cout is ostream. You might want to look at the function prototypes used in the standard libraries.) 3.3 Self-Referential Structures Structures that have fields that point to other structures, can be made into a network, such as linked lists and trees. 4

[Easy] Make a singly linked list of 00 nodes that stores random numbers, and a function that prints the numbers in the list. [Easy] Write a function that prints the list in reverse. [Medium] Move the nodes round in the list so that the values the store are in order. (Remember to write functions to help with this) [Hard] Sort the list of numbers by putting them into a binary tree. 4. Header Files & Libraries 4. Header Files Code can be separated into different files using header files and included with #include "filename.h". [Easy] Write a function and put it in a header file. 4.2 Conditional Inclusion Using the preprocessor you can chose which parts of your code can be compiled, or to prevent redefinition errors. [Easy] Fix the previous header file so it can be included multiple times. [Easy] You can define things on the command line with -D definedthing. Use this to turn on a part of you code to print debug information. E.g. in the puzzle problem (.7) have it print the number associated with each permutation when it is compiled with -D DEBUG, and not when it is compiled without. 4.3 Compiling Multiple Files [Easy] Re-write the pascals triangle program, splitting the factorial and combinatorial function into two separate.cpp files, sharing a header (.h) file. [Internet/Medium] Write a bash script that compiles the files. (Hint: To run bash scripts you use sh bashscript.sh.) [Internet/Hard] Write a Makefile that does all the compiling for you, and only compiles the files that need compiling (i.e. ones that have changed). (Hint: To run makefiles you use make.) Not enough? Try some of the Project Euler (http://projecteuler.net/problems) problems. For more information about the C ++ and its libraries, see http://www.cplusplus.com/reference/. 5