Free Essay

Debugging of C++ Function

In:

Submitted By udit7576
Words 463
Pages 2
Debugging of a function Consider the find_max() function given below: /** Finds the largest value in array elements x[start] through x[last]. pre: first <= last. @param x Array whose largest value is found @param start First subscript in range @param last Last subscript in range @return The largest value of x[start] through x[last]
*/
1. int find_max(int x[], int start, int last) {
2. if (start > last)
3. throw invalid_argument("Empty range");
4. int max_so_far = 0;
5. for (int i = start; i < last; i++) {
6. if (x[i] > max_so_far)
7. max_so_far = i;
8. }
9. return max_so_far;
10.}
-------------------------------------------------

The function will take 3 arguments, an array, starting value and last value and calculates the maximum value and return from where the function has been called. This code does not work properly. In order to understand the working of the code, output statements should be added into the code. The output statements that will be needed in the above function should be inside for loop and after the lines 5, 7 and 9. After including the diagnostic statements, the code can be given as:

/** Finds the largest value in array elements x[start] through x[last]. pre: first <= last. @param x Array whose largest value is found @param start First subscript in range @param last Last subscript in range @return The largest value of x[start] through x[last]
*/
int find_max(int x[], int start, int last)
{
if (start > last) throw invalid_argument("Empty range"); int max_so_far = 0; for (int i = start; i < last; i++)
{
#ifdef TESTING cerr << "x[" << i << "] = " << x[i] << " current max value is " << max_so_far << endl;
#endif
if (x[i] > max_so_far){ max_so_far = i;
#ifdef TESTING cerr << "Value of max_so_far is " << max_so_far << endl;
#endif
} }
#ifdef TESTING cerr << "Returned value is " << max_so_far << endl;
#endif
return max_so_far;
}
-------------------------------------------------

The explanation of all the three output statements can be given as: First output statement can be given as:

#ifdef TESTING cerr << "x[" << i << "] = " << x[i] << " current max = " << max_so_far << endl; #endif This output statement will show the current value of the array that should be compared with the maximum value of the array.
-------------------------------------------------

Second output statement can be given as:
#ifdef TESTING cerr << "max_so_far = " << max_so_far << endl; #endif This output statement will show current value if it is larger than the maximum value.
-------------------------------------------------

Third output statement can be given as:
#ifdef TESTING cerr << "Returning " << max_so_far << endl; #endif This output statement will show the maximum value that will be returned.

Similar Documents

Premium Essay

C Program

...Introduction to C Program : Define basic terminologies Describe the steps in program planning & development Describe phases in writing a program Explain the steps in C program planning & development Basic terminologies Programming: planning, scheduling or performing a task or an event  Computer Programming: process of planning a sequence of steps for a computer to follow  Computer Program/Program: list of instructions to be performed by a computer or understood by the computer  Steps in Program Planning & Development 1. 2. 3. 4. 5. Identification of the problem Problem Analysis Setting up an Algorithm Coding Running, Testing & Debugging Steps in Program Planning & Development 1. Identification of the problem knowing what the problem is Steps in Program Planning & Development 2.Problem Analysis     Review the problem & understand carefully what you are asked to do Determine what is given(input) and what result/information must be produced(output) Assign names to each input and output Determine the manner of processing that must be done on the input data to come up with desired output Steps in Program Planning & Development 3. Setting up an Algorithm Algorithm: a step-by-step process that if followed performs a specific task. This can be described in 2 ways: 1. natural language 2. graphical forms/notations What Is an Algorithm?  An algorithm is nothing more than a finite list of instructions on how to perform a task...

Words: 653 - Pages: 3

Free Essay

C Programing

...CSED 142: INTRODUCTION TO C PROGRAMMING & UNIX (CSE 142) – HW #4 1. Write a C program to convert a number entered by user to its corresponding month and prints both on the screen, e.g., January for 1. If the number is outside the range of 1 to 12 print appropriate message. … int m; printf("Enter a number between 1 and 12:\n"); scanf("%d", &m); switch (m) { case 1: printf("January, %d\n", m); break; case 2: printf("February, %d\n", m); break; case 3: printf("March, %d\n", m); break; case 4: … … case 12: printf("December, %d\n", m); break; default: printf("please enter a number between 1 and 12.\n"); } … 2. Design a multiple choice test and prompt the user to enter the correct answer and print appropriate message to let them know whether the answer was correct or not: Which one of the following is not a type of error? a) Syntax error b) Debugging error c) Runtime error d) Logic error char c; printf("Which one of the following is not a type of error?\n\n"); printf("\ta) Syntax error\n"); printf("\tb) Debugging error\n"); printf("\tc) Runtime error\n"); printf("\td) Logic error\n"); c = getchar(); switch (c) { case 'a': printf("wrong!\n"); break; case 'b': printf("Correct!\n"); break; case 'c': printf("wrong!\n"); break; case 'd': printf("wrong!\n"); break; default: printf("please enter a-d.\n"); } 3. Show that the sum of the following infinite series converges to π (3.141592653589793).  (1) n n  0 2n ...

Words: 340 - Pages: 2

Free Essay

S.Comp

...8.0 PROGRAMMING 8.1.1 Definition Program : Programming Language: 8.1 Introduction to Programming Prepared by : Pn. Marzita Ismail (SC Unit) a series of instructions that directs a computer to perform tasks. A set of words, abbreviations, and symbol that enables a programmer to communicate instructions to a computer Eg: Java, C++, Fortran, Cobol, C 8.1.2 Types of Programming Language: 1) Low Level Programming Language • • Why Low Level? : Because it is designed closer to the hardware Machine Language (1st Generation) Assembly Language (2nd Generation) Made up of instructions written in binary code (0 and 1). • Written in mnemonics, more English-like code; codes shorter than The only language that is directly understood by the machine languages computer. Does not need any translator program. • Need to be translated by assembler into machine language before it can be executed by the computer. Machine dependent (written for particular • Machine dependent (written for particular computer and has computer and has to be changed for using on a Describe/what is/ explain/characteristic • different computer). Example of coding to be changed for using on a different computer). Advantages • • Execution speed is very fast. (It does not require any translation because machine language is directly understood by CPU) Translation free (Computer understands only the machine language) Program written in machine language are very lengthy Machine dependent (program...

Words: 1038 - Pages: 5

Premium Essay

Exercises

...corresponding to the option A, B, C, D given in the questions in the appropriate box. 1. What kind of software does Excel belongs to? A. Spreadsheet C. Web design and authoring tool B. Word processing D. Database 2. is a series of ordered commands. A. Program C. Code B. Software D. Process 3. is a process of finding and reducing the number of defects in a computer program. A. Coding C. Encoding B. Programming D. Debugging 4. Programs process data depending on the of the data. A. value C. type B. number D. name 5. are the labels on the computer's memory. A. Numbers C. Values B. Variables D. Codes 6. A computer game is a program in which one or more players make decisions through the control of game objects and resources, in pursuit of a goal. A. software C. assembly B. hardware D. debugging 7. Which of the following is NOT the three main parts to a Game Maker? A. Sprites C. Buttons B. Rooms D. Objects 8. In Game Maker, describe when actions are to be performed. A. Actions C. Classes B. Events D. Objects 9. In Game Maker, are what to do when an event occurs. A. Actions C. Classes B. Events D. Objects 10. Business-to-Consumer (B2C) involves products and services to individual consumers. A. Buying C. Wholesaling B. Retailing...

Words: 1087 - Pages: 5

Free Essay

Softwares

...Ctrl-K/Ctrl-Shift K Alt-Left/AltRight/Ctrl-Q Alt Up / Down Search word at insert point Find next/previous in file Find/Replace in file Find usages Find/replace in projects Find usages results Turn off search result highlights Rename Convert selection to uppercase Convert selection to lowercase Toggle case of selection Paste formatted Show Clipboard History Jump to quick search field Copy file path Go to type/file Go to JUnit test Go to source Go to declaration Go to line Toggle add/remove bookmark Next/previous bookmark Next/previous usage/compile error Select next/previous element Select in Projects/Files/Favorites Move caret to matching bracket Next/previous word match Go backward/forward/to last edit Next/previous marked occurrence Coding in C/C++ Alt-Shift-C Ctrl-F9 Coding in Java Alt-Insert Ctrl-Shift-I Alt-Shift-I Alt-Shift-F Alt-Shift Left/ Right/Up/Down Ctrl-Shift-R Ctrl-Shift-Up/D Ctrl/Alt-F12 Ctrl-/ Ctrl-E F9 F11 Shift-F11 Ctrl-Q Ctrl-Shift-U Ctrl-F6/Alt-F6 F6/Shift-F6 Ctrl-Tab (Ctrl-`) Shift-Escape Ctrl-F4/Ctrl-W Ctrl-Shift-F4 Shift-F10 Ctrl-PgUp / PgDown Ctrl-Alt-T Generate code Fix all class imports Fix selected class's import Format selection Shift lines left/right/up/down Rectangular Selection (Toggle) Copy lines up/down Inspect members/hierarchy Add/remove comment lines Delete current line Compile package/ file Build main project Clean & build main project Set request parameters Create Unit test Run Unit test on file/project...

Words: 951 - Pages: 4

Free Essay

Hard-Wired Control Design

...[pic] Computer Organization and Architecture Course design report Hare-wired Control Design 1. Objective a. To master the knowledge of Computer Organization and Arthitecture courses. To clearly understanding the working principles and interconnect of various modules of the computer system especially the hard-wired controller by making a comprehensive use of the knowledge. b. To learn the basic procecures and methods of using ISP technology to design and debug. To be familiar with the designing, simulating,and debugging tools for integrated development of software. And to experience the advantages of ISP technology from the traditional ones. c. To cultive the capability of independent work on science, and to obtain the experience of project design and assembling as well as debugging. 2.Equipment 1. TEC-4 system for COA experiments. 2. A dual trace oscilloscope. 3. A logical test pen. 4. An ispLSI1032 chip. 5. IspExpert of Lattice Co. Ltd. 3.Principles and Requirements The experiment is to design a hard-wired controller with an ispLSI1032 chip for the TEC-4 platform. The controller should perform five console instructions: KRD,KWE,KLD,KRR, nine machine instructions: ADD,SUB,MUL,AND,STA,LDA,JMP, JC,STP and the interrupts. Preparations: Timng Signal Generator: MF signal is generated by a crystal oscillator (frequency 1MHz), while producing T1, T2, T3, T4, W1, W2, W3, W4 timing signal, relationship as shown below. Where W1, W2...

Words: 2111 - Pages: 9

Free Essay

Ead Quiz Solution

..._____________________________________ Roll Number: ____________ Question(1) MCQs Select one option only. 1. repository of shared assemblies maintained by the .NET runtime is called a. assembly line b. Assembly contents c. Assembly manifest d. Global Assembly cache 2. Which key is used for step into in debugging a. F7 b. F12 c. F11 d. F10 3. Which command is used to create exe file using csc command a csc File.cs b csc /out:My.exe File.cs c none d both (a,b) 4. --------namespace is used for ado.net with data adapter a. System.io; b. System.SqlAdapter 3. System.Data 4. System.SqlDb 5. To convert reference type variable into simple type (value) is a. Unboxing b. Boxing Question(2) ( 5 Marks each) Short Answers: 1. Write differences between CLS and CLR  CLS specifies a set of rules that needs to be adhered or satisfied by all language compilers targeting CLR. It helps in cross language inheritance and cross language debugging. .Net Framework provides runtime environment called Common Language Runtime (CLR).It provides an environment to run all the .Net Programs. 2. Write a function that takes any number of strings and an integer. Write only prototype and call this function using named argument Public void myFunc(int num, params string[] args); myFunc(1,”Ali”,”Ahmad”); 3. What is return type of following methods? ExecuteNonQuery() | int | ExecuteScalar()...

Words: 757 - Pages: 4

Free Essay

Basic Configureation

...entry clear Reset functions connect Open a terminal connection crypto Encryption related commands. disable Turn off privileged commands disconnect Disconnect an existing network connection enable Turn on privileged commands exit Exit from the EXEC help Description of the interactive help system lock Lock the terminal login Log in as a particular user logout Exit from the EXEC name-connection Name an existing network connection ping Send echo messages rcommand Run command on remote switch resume Resume an active network connection set Set system parameter (not config) show Show running system information ssh Open a secure shell client connection systat Display information about terminal lines telnet Open a telnet connection terminal Set terminal line parameters traceroute Trace route to destination tunnel Open a tunnel connection where List active connections SwitchAA>enable Password: SwitchAA#? Exec commands: access-enable Create a temporary Access-List entry access-template Create a temporary Access-List entry archive manage archive files cd Change current directory clear Reset functions clock Manage the...

Words: 1231 - Pages: 5

Premium Essay

Electronic Library Card Catalog System

...Maquiling, Marres Contents 1. Overview…………………………………………………………………………………………………………………………...3 2. Goals and scope………………………………………………………………………………………………………….….….4 2.1 Project Goals…………………………………………………………………………………………………………4 2.2Project Scope…………………………………………………………………………………………..……….……5 2.2.1 Included………………………………………………………………………………………………………….….5 2.2.2 Excluded .................................................................................................................5 3. Organization……………………………………………………………………………………………………………………….6 3.1 Organizational Boundaries and Interfaces…………………………………………………………….…...6 3.1.1 Resource Owners……………………………………………………………………………………………….6 3.1.2 Receivers…………………………………………………………………………………………………….……..6 3.1.3 Cross Functions…………………………………………………………………………………………………..7 3.2 Project Organization…………………………………………………………………………………………………..8 3.2.1 Project Manager…………………………………………………………………………………………….….8 3.2.2 Project Team……………………………………………………………………………………………………..9 4. Schedule and Budget…………………………………………………………………………………………………………10 4.1 Work Breakdown Structure…………………………………………………………………….…………...11 4.2 Schedule and Milestone………………………………………………………………………….……………12 4.3 Budget.......................................................................................................................13 4.4 Development Process…………………………………………………………………………………………..14 4.5 Development Environment…………………………………………………………………………………..15 5. Risk Management…………………………………………………………………………………………………….………...

Words: 4136 - Pages: 17

Premium Essay

Nt1310 Unit 5 Lab Report

...once we tested the amplifier with biological signals. Unfortunately, our board did not function as expected, and we were unable to detect ECG signals. With a known functioning board, we were able to get good results on the oscilloscope, proving that we were able to set-up the t-leads, electrodes, and oscilloscope successfully. However, our board needed debugging. The hardware engineer discovered a mistake in the connections of the jumper wires on the top side of the board. He also fixed a few areas where excess solder was apparent. After these changes, our ECG amplifier board allowed us to display an ECG signal on the oscilloscope (see Figure 2). However, the signal flat-lined soon after, indicating that our board was not as reliable as expected. More debugging will be required for future use. IV. Discussion Our team completed all required tasks with some success. Due to the brief period of expected function, we know that our board’s components were placed correctly and the leads were configured correctly. Any errors are likely the cause of bad connections. To further improve the ECG amplifier, we would have to check these connections and, if needed, fix them. ABET B: an ability to design and conduct experiments, as well as to analyze and interpret data Our team was successful in building the circuit and in identifying when our oscilloscope readings matched the desired outcomes. ABET C: an ability to design a system, component, or process to meet desired needs within...

Words: 761 - Pages: 4

Free Essay

Module 6

...Multiple Choice 1 through 10 starting on page 267 1) B 2) D 3) A 4) C 5) B 6) B 7) C 8) B 9) A 10) A Algorithm Workbench 1 through 3 problems on page 269 1) Declare integer rand set rand = random (1, 100) Display rand End function 2) Display “Enter a number” Input number Set number = number /2 Display “The half of”, number, “is” Display “Press Enter to continue” ...

Words: 256 - Pages: 2

Premium Essay

Question Paper

...Answer : Dictator C. Split cache D. Stale cache 22) Which cache design has the less conflict or no conflict? A. Partially associative (Democle) B. associative C. Answer : Fully Associative(democle) D. None of the above 23) What are the necessary conditions for deadlock? A. Mutual Exclusion B. Hold and Wait C. No Preemption D. All of the above 24) _______ is a situation when the performance of a computer degrades or collapses A. Collapsing B. Answer : Thrashing C. Performance D. None of the...

Words: 969 - Pages: 4

Free Essay

Bash for Beginners

...Bash Guide for Beginners Machtelt Garrels Garrels BVBA Version 1.11 Last updated 20081227 Edition Bash Guide for Beginners Table of Contents Introduction.........................................................................................................................................................1 1. Why this guide?...................................................................................................................................1 2. Who should read this book? .................................................................................................................1 3. New versions, translations and availability.........................................................................................2 4. Revision History..................................................................................................................................2 5. Contributions.......................................................................................................................................3 6. Feedback..............................................................................................................................................3 7. Copyright information.........................................................................................................................3 8. What do you need? .......................................................................................................................

Words: 29161 - Pages: 117

Free Essay

Resume

...Professional Summary: * Extensive Experience in MS SQL Server 2005/2008 and 2000 Database Administration and PL/SQL developer in Business Analyst including Planning, Deployment / Implementation and configuration. * Extensive experience in writing Complex Stored procedures as well analyzing and debugging existing complex stored procedures. * Successfully led, executed and maintained projects with multiple databases. * Implementing all kinds of SQL Server Constraints (Primary, Foreign, Unique, Check etc).  * Generating complex Transact SQL (T-SQL) queries, Sub queries, Co-related sub queries, Dynamic SQL queries * Programming in SQL Server - Using the stored procedures, Triggers, User-defined functions and Views, Common table expressions (CTEs) * Proficient in creating T-SQL (DML, DDL, DCL and TCL), Indexes, Views, Temporally Tables, Table Variables, Complex Stored Procedures, System and User Defined Functions . * Strong experience in creating complex Replication, Index, Functions, DTS packages, triggers, cursors, tables, views and other SQL joins and statements. * Expertise in Client-Server Application Development using Oracle […] PL/SQL, SQL *PLUS, TOAD and SQL*LOADER. * Experience in understanding complicated performance issues and worked with DBA's to suggest valuable ways to fix the problem  * Hands on experience working with SSIS, for ETL process ensuring proper implementation of Event Handlers, Loggings, Checkpoints, Transactions...

Words: 1001 - Pages: 5

Free Essay

Program Testing and Debugging

...Program Testing and Debugging Mack Altman III Capella University Author Note This paper is being submitted on April 27, 2015, for Azad Ali’s IT-FP2240 Introduction to Programming course. Program Testing and Debugging Introduction The purpose of this document is to present a detailed description of the Mortgage Calculator. It will explain the application requirements, methods of handling errors within the application, and how to involve the client during the application assessment process. While the application is basic in nature, the application provides an example of work performed to establish the capabilities of its author to utilize error handling within an application. Application Requirements The only functional requirement of the application is to prompt the user to supply the user with their potential monthly mortgage payment. The payment should be determined by utilizing the mortgage amount, the down payment made, rate of interest on the proposed mortgage, and term of the mortgage in years. This information should be supplied by the user through prompts upon the execution of the application. In regards to non-functional requirements, the application requires the use of the stdio, math, and errno C libraries. Application Review Upon the initial execution of the application, all potential entries are initialized as float in case the user may provide a non-integer numerical value. Upon initial design, these were established as integers until the rate value was...

Words: 872 - Pages: 4