COLLEGE OF ELECTRICAL & MECHANICAL ENGINEERING NUST Fundamentals Of .

Transcription

COLLEGE OF ELECTRICAL &MECHANICAL ENGINEERING NUSTFundamentals of ProgrammingCS-114Lab Manual

Lab & Project RubricsTraitExceptional[10-8]Program compiles withzero error and zerowarnings.Acceptable[7-5]Program has few syntaxerror but logically correct.Amateur[4-3]Program has fewsyntax error but noteven logically correct.Unsatisfactory[2-0]Application does notcompile or compiles butcrashes.FunctionalityAnd efficiency30%The program works andmeets all of thespecifications and isextremely efficientwithout sacrificingreadability andunderstanding.The code is fairly efficientwithout sacrificing readabilityand understanding and alsomeets almost all of itsspecifications but not all.The code isunnecessarily long andinefficient and meetsonly few of itsspecificationsThe code is huge anddoes not meet anyspecificationsOutput5%The program producescorrect results anddisplay them correctly inan organized way.The program works andproduces the correct resultsand displays them correctlyThe program producescorrect results but doesnot display themcorrectlyThe program is producingincorrect results.InputAll the inputs entered byuser are properlyvalidated, in case ofwrong input entered byuser the programdisplays to the user toenter the correct input.In case of wrong input theprograms continuesexecution.Some of the inputs arevalidated leaving theothers.No input validation.The code was deliveredwithin the deadline.The code was deliveredwithin the deadlineThe code was deliveredfew hours passed thedeadline.The code was more than 2days overdue.Compilation15%Validation*20%Delivery30%

NUST COLLEGE OF ELECTRICAL & MECHANICALENGINEERINGLAB #01:Name:IntroductionReg #:Lab Objective:Introduction to programmingLab Description:C Program StructureLet us look at a simple code that would print the words Hello World.#include iostream using namespace std;// main() is where program execution begins.int main() {cout "Hello World"; // prints Hello Worldreturn 0;}Let us look at the various parts of the above program The C language defines several headers, which contain information that is eithernecessary or useful to your program. For this program, the header iostream isneeded. The line using namespace std; tells the compiler to use the std namespace.Namespaces are a relatively recent addition to C . The next line '// main() is where program execution begins.' is a single-line commentavailable in C . Single-line comments begin with // and stop at the end of the line. The line int main() is the main function where program execution begins.

The next line cout "Hello World"; causes the message "Hello World" to bedisplayed on the screen. The next line return 0; terminates main( )function and causes it to return the value 0to the calling process. In C , the semicolon is a statement terminator. That is, each individual statementmust be ended with a semicolon. It indicates the end of one logical entity. Program comments are explanatory statements that you can include in the C code.These comments help anyone reading the source code. All programming languagesallow for some form of comments. C supports single-line and multi-line comments.All characters available inside any comment are ignored by C compiler. C comments start with /* and end with */. A comment can also start with //, extendingto the end of the line.TASK1:Run the following program and check the output#include iostream using namespace std;int main(){cout "hello world" endl; //prints hello world and endl means end the linesystem("pause"); //to stop output windowreturn 0;}TASK2:Write a C program to print the following lines:You are 10 years old.You are too young to play the game.TASK3:Write five C statements to print the asterisk pattern as shown below.***************

NUST COLLEGE OF ELECTRICAL & MECHANICALENGINEERINGLAB #02:Name:Reg #:Lab Objective:Learning Lab Description:Data Types:A variable provides us with named storage that ourprograms can manipulate. Each variable in C has aspecific type, which determines the size and layout ofthe variable's memory, this type is known as data typeof that variable.The name of a variable can be composed of letters,digits, and the underscore character. It must beginwith either a letter or an underscore. Upper andlowercase letters are distinct because C is casesensitive.Figure 1: Basic Data TypesVariable Declaration in C

A variable declaration provides assurance to thecompiler that there is one variable existing with thegiven type and name so that compiler proceed forfurther compilation.int a;char b;float c;Variable Initialization in C A variable can be initialized at the time of declaration or even afterthat. Basically initialization means storing some actual meaningfuldata inside the variable.int a 2;char b ’x’;float c 2.907;ConstantsConstants refer to fixed values that the program maynot alter during its execution. These fixed values arealso called literals.Defining ConstantsThere are two simple ways in C to define constants:Using #define preprocessorUsing const keyword#define LENGTH 10#define WIDTH 5const int LENGTH 10;const int WIDTH 5;Legal Identifiers:Regardless of which style you adopt, be consistent and make your variable names as sensible aspossible. Here are some specific rules that must be followed with all identifiers. The first character must be one of the letters a through z, A through Z, or an underscorecharacter ( ).

After the first character you may use the letters a through z or A through Z, the digits 0 through9, or underscores. Uppercase and lowercase characters are distinct. This means ItemsOrdered is not the same asitemsordered.Escape Sequence:cout "\t";Fundamental Arithmetic Operators:LABTask-1:Type and save the following programs in Visual Studio. Run these programs and observe theiroutput.

Task2:Take two integers as input from the user apply athematic operations on them( ,-,*,/) as printthem on screen.Task3:Write the output of the following codeTask 4:Write a C program to calculate the distance between the two points.Note: x1, y1, x2, y2 are all double values.Formula:Output:

Task 5:1. Calculate the Area of a Circle (area PI * r2)2. Calculate the Area of a Rectangle (area length * width)3. Calculate the Area of a Triangle (area base * height * .5)Task 6:Total Purchase A customer in a store is purchasing five items. The prices of the five items are:Price of item 1 12.95Price of item 2 24.95Price of item 3 6.95Price of item 4 14.95Price of item 5 3.95Write a program that holds the prices of the five items in five variables. Display each itemsprice, the subtotal of the sale, the amount of sales tax, and the total. Assume the sales tax is6%.Bonus Task:Break Number:Write a program that inputs a five-digit integer, separates the integer into its individualdigits and prints the digits separated from one another by three spaces each.Home Tasks:Task 1:Exchange Write a program that reads in two variables and swaps the value of these variables.For example if a variable ‘var1’ contains 10 and variable ‘var2’ contains 20, after the swapoperation the variable ‘var1’ contains 20 (value of var2) and variable ‘var2’ contains 10 (valueof var1).Task 2:

Make Upper Write a program that prompts the user to enter an alphabet in small caps (a, b,c, z) and display the entered alphabet into its upper caps (A, B, C, Z).(hint ASCII)“When you are not practicing, remember, someone somewhere ispracticing, and when you meet him he will win”

NUST COLLEGE OF ELECTRICAL & MECHANICALENGINEERINGLAB #03:Name:Reg #:Lab Objective:Expressions, type casting, coercion, formatting, random numbers.Lab Description:Implicit conversion (coercion)Implicit conversions are automatically performed when a value is copied to a compatibletype. For exampleShort a 2000;Int b;b a;When an operator works with two values of different data types, the lower-ranking value ispromoted to the type of the higher-ranking value.When the final value of an expression is assigned to a variable, it will be converted to thedata type of that variable.Type castingC is a strong-typed language. Many conversions, specially those that imply a differentinterpretation of the value, require an explicit conversion, known in C as type-casting. There existtwo main syntaxes for generic type-casting: functional and c-like:double x 10.3;int y;y int (x); // functional notationy (int) x; // c-like cast notationExpressions:Multiplication, mode and division have higher precedence than addition and subtraction.Associativity: left to right.Random Function:

Cout rand();Library used cstdlib Formatting:LAB:Task 1:Assume that the following variables are defined:int age;double pay;char section;Write a single cin statement that will read input into each of these variables.Task 2:Complete the following table by writing the value of each expression in the Value columnaccording C language rules.Task 3:Assume a program has the following variable definitions:

int units;float mass;double weight;weight mass * units;Which automatic data type conversion will take place?A. mass is demoted to an int, units remains an int, and the result of mass * units is an int.B. units is promoted to a float, mass remains a float, and the result of mass * units is a float.C. units is promoted to a float, mass remains a float, and the result of mass * units is adouble.Task 4:Assume a program has the following variable definitions:int a, b 2;float c 4.2;and the following statement: a b * c;What value will be stored in a?A. 8.4B. 8C. 0D. None of the aboveTask 5:Assume that qty and salesReps are both integers. Use a type cast expression to rewrite thefollowing statement so it will no longer perform integer division.unitsEach qty / salesReps;Task 6:Math Tutor: (hint rand())Write a program that can be used as a math tutor for a young student. The program shoulddisplay two random numbers to be added, such as247 129--------The program should then pause while the student works on the problem. When the studentis ready to check the answer, he or she can press a key and the program will display thecorrect solution:247 129

-------376Home Tasks:Task 1:Each of the following programs has some errors. Locate as many as you can.Program-1using namespace std;void main (){double number1, number2, sum;cout "Enter a number: ";Cin number1;cout "Enter another number: ";cin number2;number1 number2 sum;cout "The sum of the two numbers is " sum}Program-2#include iostream using namespace std;void main(){int number1, number2;float quotient;cout "Enter two numbers and I will divide\n";cout "the first by the second for you.\n";cin number1, number2;quotient float static cast (number1) / number2;cout quotient

}Task 2:Average of Values to get the average of a series of values, you add the values up and thendivide the sum by the number of values. Write a program that stores the following values infive different variables: 28, 32, 37, 24, and 33. The program should first calculate the sum ofthese five variables and store the result in a separate variable named sum. Then, theprogram should divide the sum variable by 5 to get the average. Display the average on thescreen.

NUST COLLEGE OF ELECTRICAL & MECHANICALENGINEERINGLAB #04: If statementName:Reg #:Lab Objective:Learn how to use if in programming.Lab Description:UseTo specify the conditions under which a statement or groupof statements should be executed.if (testExpression){// statements}The if statement evaluates the test expression insideparenthesis. If test expression is evaluated to true,statements inside the body of if is executed. If testexpression is evaluated to false, statements inside thebody of if is skipped.How if statement works?

Flowchart of if Statementif.elseThe if else executes the codes inside the bodyof if statement if the test expression is true and skips thecodes inside the body of else.If the test expression isfalse, it executes the codes inside the body

of else statement and skips the codes inside the bodyof if.How if.else statement works?Flowchart of if.elseC Nested if.elseThe if.else statement executes two different codes depending upon whether thetest expression is true or false. Sometimes, a choice has to be made from more than2 possibilities.

The nested if.else statement allows you to check for multiple test expressionsand execute different codes for more than two conditions.Syntax of Nested if.elseif (testExpression1){// statements to be executed}else if(testExpression2){// statements to be executed}else if (testExpression 3){// statements to be executedtrue}.else{// statements to be executed}if testExpression1 is trueif testExpression1 is false and testExpression2 is trueif testExpression1 and testExpression2 is false and testExpression3 isif all test expressions are falseNested If:In C we can use if statement in theanother else block. or we can also include ifblock in the another if block.Syntax : C Nested Ifif( boolean expression 1){// Executes when the boolean expression 1 is trueif(boolean expression 2){// Executes when the boolean expression 2 is true}}

Example : Nested IfWe can nest else if else in the similar way as youhave nested if statement.Example : Nested If-else#include iostream using namespace std;int main (){int marks 55;if( marks 80) {cout "U are 1st class !!";}else {if( marks 60) {cout "U are 2nd class !!";}else {if( marks 40) {cout "U are 3rd class !!";

}else {cout "U are fail !!";}}}return 0;}Task1:Write a program to print positive number entered by the user.If the user enters negative number print number entered is positive otherwise print number isnegative.Task2:Program to check whether an integer is positive, negative or zero.Task3:Input : MarkProcess : If mark greater than and equal to 75, score will be AIf mark less than 75 and greater than and equal to 60, score will be BIf mark less than 60 and greater than and equal to 45, score will be CIf mark less than 30, score will be DOutput : Print the grade of your score.Task4:Find Largest Number Using Nested if.else statement.Check whether the number entered by the user is positive or not. If it is positive then calculatehow many digits the number have.

NUST COLLEGE OF ELECTRICAL & MECHANICALENGINEERINGLAB #05: INTRODUCTION TO FOR LOOPS, SWITCH CASEName:Reg #:Lab Objective:To practice for loops and switch cases and to get better understanding ofhow to use them.Lab Description:A for loop is a repetition control structure that allows you toefficiently write a loop that needs to execute a specificnumber of times.Syntax:The syntax of a for loop in C is for ( init; condition; increment ){statement(s);}Figure 2: the loop’s logic.

Exampleint main (){}Output:Other Forms of the Update Expression :You are not limited to using increment statements in the update expression. Here is a loop thatdisplays all the even numbers from 2 through 100 by adding 2 to its counter:

And here is a loop that counts backward from 10 down to 0:Defining a Variable in the for Loop’s Initialization Expression:Not only may the counter variable be initialized in the initialization expression, it may be definedthere as well. The following code shows an example.Using Multiple Statements in the Initialization and Update Expressions:It is possible to execute more than one statement in the initialization expression and the updateexpression. When using multiple statements in either of these expressions, simply separate thestatements with commas. For exampleOmitting the for Loop’s Expressions:The initialization expression may be omitted from inside the for loop’s parentheses if it has alreadybeen performed or no initialization is needed. Here is an exampleNested Loops:A loop that is inside another loop is called a nested loop. A clock is a good example of somethingthat works like a nested loop. The second hand, minute hand, and hour hand all spin around the faceof the clock. Each time the hour hand increments, the minute hand increments 60 times. Each timethe minute hand increments, the second hand increments 60 times. Here is a program segment witha for loop that partially simulates a digital clock. It displays the seconds from 0 to 59:Example

Output:Switch caseswitch.case is a branching statement used to perform action based on available choices,instead of making decisions based on conditions. Using switch.case you can write moreclean and optimal code than if.else statement. switch.case only works with integer,character and enumeration constants.Lab Tasks: Task1: C program to Print Table of any Number.The concept of generating table of any number is multiply particular number from 1 to m * 10

Task2: Find power of any number using for loop. Task3: Sum of Natural Numbers using loop. Task4:C program to find sum of digits of a number.Sum of digits means add all the digits of any number, for example we take any number like358. Its sum of all digit is 3 5 8 16. Using given code we can easily write c program. Task 5: Program to Generate Factorial a Certain NumberFactorial of any number is the product of an integer and all the integers below it for examplefactorial of 4 is 4! 4 * 3 * 2 * 1 24 Task7: Write a C program that will print the following pattern.**************************** Write a C program print total number of days in a month using switch case. Write a C program to check whether an alphabet is vowel or consonant usingswitch case.Think? What will be the output of the C program?#include stdio.h int main(){for(5;2;2){cout "Hello";}return 0;}

What will be the output of the C program, if input is 6?#include stdio.h int main(){int i;for(i 0; i 9; i 3){cout "for ";}return 0;} What will be the output of the C program.#include stdio.h int main(){for(;;){cout ”10”;}return 0;} What will be the output of the C program?int main(){int fun 5;cout "C for loop ";int x 5;for(x 0;x fun;x )

{cout x;}return 0;}

NUST COLLEGE OF ELECTRICAL & MECHANICALENGINEERINGLAB #06: While & Do While LoopsName:Reg #:Lab Objective:To have better understanding regarding loops.Lab Description:A loop is part of a program that repeats. The while loophas two important parts: (1) an expression that istested for a true or false value, and (2) a statement orblock that is repeated as long as the expression is true.The while Loop Is a Pretest Loop ,which means it testsits expression before each iteration whereas the dowhile loop is a posttest loop, which means its expressionis tested after each iteration.Infinite Loops:If a loop does not have a way of stopping, it iscalled an infinite loop. An infinite loop continues torepeat until the program is interrupted. Here is anexample of an infinite loop:

We can make this loop finite by adding a line asshown belowExamples: The following example averages a series of three test scores fora student. After the average is displayed, it asks the user if he or she wantsto average another set of test scores. The program repeats as long as theuser enters Y for yes.ExampleOUTPUT

Lab Tasks: Task1: program to print all natural numbers from 1 to n using while loop Task2: program to print natural numbers in reverse from n to 1 using while loop Task3: program to print all even numbers between i to n using while loop. Task4: Program to Generate Fibonacci Sequence up to a Certain Number. The Fibonaccisequence is a series of numbers where a number is found by adding up the twonumbers before it. Starting with 0 and 1, the sequence goes 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, andso forth. Task 5: Take i and n two inputs from user and print n i of the number. Task6: Write a method with a while loop that computes the sum of first n positive integers:sum 1 2 3 n. Task7: Write a do-while loop that asks the user to enter two numbers. The numbers shouldbe added and the sum displayed. The user should be asked if he or she wishes to performthe operation again. If so, the loop should repeat; otherwise it should terminate. Task8: Convert the following while loop to a do-while loop:int x 1;while (x 0){cout "enter a number: ";cin x;}Think? What will the following program segments display?

What’s wrong with the following while loop?

NUST COLLEGE OF ELECTRICAL & MECHANICALENGINEERINGLAB #07: FUNCTIONSName:Reg #:Lab Objective:To have better understanding regarding functions and .Lab Description:A function is a collection of statements that performs aspecific task. So far you have experienced functions asyou have created a function named main in everyprogram you’ve written. Functions are commonly usedto break a problem down into small manageable pieces.This approach is sometimes called divide and conquerbecause a large problem is divided into several smallerproblems that are easily solved.This benefit of using functions is known as code reusebecause you are writing the code to perform a task onceand then reusing it each time you need to perform thetaskDefining and Calling Functions:A function call is a statement that causes a function toexecute. A function definition contains the statementsthat make up the function. When creating a function,you must write its definition. All function definitionshave the following parts:1. Return type: A function can send a value to thepart of the program that executed it. The return

type is the data type of the value that is sentfrom the function.2. Name: You should give each function adescriptive name. In general, the same rules thatapply to variable names also apply to functionnames.3. Parameter list: The program can send data into afunction. The parameter list is a list of variablesthat hold the values being passed to the function.4. Body: The body of a function is the set ofstatements that perform the function’s operation.They are enclosed in a set of braces.Void Functions:It isn’t necessary for all functions to return a value,however. Some functions simply perform one ormore statements, which follows terminate. Theseare called void functions. The display Messagefunction, which follows, is an example.Calling a Function:A function is executed when it is called. Functionmain is called automatically when a program starts,but all other functions must be executed byfunction call statements. When a function is called,the program branches to that function andexecutes the statements in its bodyFunction Header void displayMessage()

Function Call displayMessage();Functions may also be called in a hierarchical, or layered, fashion.Function prototype:A function prototype eliminates the need to place afunction definition before all calls to the function.You must place either the function definition oreither/the function prototype ahead of all calls tothe function. Otherwise the program will notcompile.

Sending Data into a Function:When a function is called, the program may sendvalues into the function. Values that are sent into afunction are called arguments. In the followingstatement the function pow is being called and twoarguments, 2.0 and 4.0, are passed to it:result pow(2.0, 4.0);By using parameters, you can design your ownfunctions that accept data this way. A parameter isa special variable that holds a value being passedinto a function. Here is the definition of a functionthat uses a parameter:void displayValue(int num){ cout "The value is " num endl; }The return Statement and Returning a Value from a Function :The return statement causes a function to end immediately. Afunction may send a value back to the part of the program thatcalled the function this is known as returning a value. Here is anexample of a function that returns an int value:However, we could have eliminated the result variable and returnedthe expression num1 num2, as shown in the following code:A function can also return a Boolean value instead of integer ordouble or character. The following example shows that.

Examples: The following example demonstrates a function with a parameter.ExampleOUTPUTI am passing several values to displayValue.The value is 5The value is 10The value is 2The value is 16

Lab Tasks: Task1: Write a function named times Ten . The function should have an integerparameter named number. When times Ten is called, it should display theproduct of number times ten. (Note: just write the function. Do not write acomplete program.) Task2: Write a function asks the user to enter the radius of the circle and then returnsthat number as a double. Write another function that takes this radius as input andreturns the area of circle. Task3: Write a function accepts an integer argument and tests it to be even or odd. Thefunction returns true if the argument is even or false if the argument is odd. The returnvalue should be bool. In main take a integer input from user and pass it to the function. Task4: Write a program with a function that takes two int parameters, adds themtogether, then returns the sum. The program should ask the user for two numbers,then call the function with the numbers as arguments, and tell the user the sum. Task 5: Write a value returning function that receives three integers and returns thelargest of the three. Assume the integers are not equal to one another. Task6: Write a program in C to swap two numbers using function. Task7: Write a function which converts an uppercase letter 'A'{'Z' to the correspondinglowercase letter. If the parameter is not a letter it must be returned unchanged. Write amain program which calls the function. Task8: Write a program will ask the user to enter the width and length of a rectangleand then display the rectangle’s area. The program calls the following functions:1. getLength – This function should ask the user to enter the rectangle’s lengthand then return that value as a double.2. getWidth – This function should ask the user to enter the rectangle’s width andthen return that value as a double .3. getArea – This function should accept the rectangle’s length and width asarguments and return the rectangle’s area. The area is calculated by multiplyingthe length by the width.4. displayData – This function should accept the rectangle’s length, width, andarea as arguments and display them in an appropriate message on the screen.INITIAL array:Think? What is the output of the following program?

Indicate which of the following is the function prototype, the function header,and the function call:void showNum(double num)void showNum(double);showNum(45.67); The following program skeleton asks for the number of hours you’ve worked andyour hourly pay rate. It then calculates and displays your wages. The functionshowDollars, which you are to write, formats the output of the wages. How many return values may a function have?

NUST COLLEGE OF ELECTRICAL & MECHANICALENGINEERINGLAB #08: ArraysName:Reg #:Lab Objective: To be able to declare an array.To be able to perform fundamental operations on a two-dimensional array.To be able to pass two-dimensional arrays as parameters.To be able to view a two-dimensional array as an array of arrays.Lab Description:An array is a series of elements of the same type placedin contiguous memory locations that can be individuallyreferenced by adding an index to a unique identifier.That means that, for example, five values oftype int can be declared as an array without having todeclare 5 different variables (each with its ownidentifier). Instead, using an array, the five int valuesare stored in contiguous memory locations, and all fivecan be accessed using the same identifier, with theproper index.For example, an array containing 5 integer values oftype int called foo could be represented as:where each blank panel represents an element of thearray. In this case, these are values of type int. Theseelements are numbered from 0 to 4, being 0 the first

and 4 the last; In C , the first element in an array isalways numbered with a zero (not a one), no matter itslength.Initializing arrays:By default, regular arrays of local scope (for example,those declared within a function) are left uninitialized.This means that none of its elements are set to anyparticular value; their contents are undetermined at thepoint the array is declared.But the elements in an array can be explicitly initializedto specific values when it is declared, by enclosing thoseinitial values in braces {}. For example:int foo [5] { 16, 2, 77, 40, 12071 };This statement declares an array that can berepresented like this:The number of values between braces {} shall not begreater than the number of elements in the array. Forexample, in the example above, foo was declaredhaving 5 elements (as specified by the number enclosedin square brackets, []), and the braces {} containedexactly 5 values, one for each element. If declared withless, the remaining elements are set to their defaultvalues (which for fundamental types, means they arefilled with zeroes). For example:int bar [5] { 10, 20, 30 };Will create an array like this:The initializer can even have no values, just the braces:int baz [5] { };This creates an array of five int values, each initialized

withavalueofzero:Accessing the values of an array:The values of any of the elements in an array can beaccessed just like the value of a regular variable of thesame type. The syntax is:name[index]Following the previous examples in which foo had 5elements and each of those elements was of type int,the name which can be used to refer to each element isthe following:For example, the following statement stores the value75 in the third element of foo:foo [2] 75;and, for example, the following copies the value of thethird element of foo to a variable called x

These comments help anyone reading the source code. All programming languages allow for some form of comments. C supports single-line and multi-line comments. All characters available inside any comment are ignored by C compiler. C comments start with /* and end with */. A comment can also start with //, extending to the end of the line.