EE0107-19 Basic Programming and Lab: Sebelas Maret University

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

Sebelas Maret University

College of Engineering, Electrical Engineering Department

Labwork Manual:
EE0107-19 Basic Programming and Lab

#include <iostream>
Using namespace std;
int main ()
{
cout<<"Welcome to C++
Programming\n"<<endl;
return 0;
}

Student Name :
ID Number :
Class :

Update: 20/9/2020
L0107-19 – Basic Programming and Lab, Sebelas Maret University

Labwork Outline
Lab 1 : Introduction
This first lab offers an introduction for writing and executing C++ programs using
CodeBlocks. This lab also introduces cout instruction and software life cycle.

Lab 2 : Variables and Data Types


In this lab, students will learn how to define variable types and values, and how to print
them. Students will also learn more about conversion specifications. students will
explore basic and compound mathematical operations, their precedence, and conversion
issues.

Lab 3 : Control Structure


In this lab, students explore basic decision making (IF… structure, IF…ELSE…
structure and SWITCH structure)

Lab 4 : Looping
In this lab, students explore basic looping commands through using( FOR loop.
DO…While… etc)

Lab 5 : Simple Engineering Problem


In this lab, students will examine the applications of C++ programming in engineering
system (or simple engineering problem)

Lab 6 : Functions
Students explore how to create their own function.

Lab 7 : Array
In this lab, students will learn how to build a matrix using array.

Lab 8 : String
In this lab, student will learn about string and string manipulation in C++
programming..

Lab 09 : Input and Output Files


In this lab, student will study reading from and writing to external files..

Lab 10 : Pointer, Record, Etc


In in this lab, students will learn how to use pointers, record and other.

2
L0107-19 – Basic Programming and Lab, Sebelas Maret University

Lab (01): Introduction


Objective: This first lab offers an introduction for writing and executing C++ programs using
CodeBlocks. This lab also introduces cout instruction and software life cycle.

A. Code Blocks Installation


You may use any type of software to write and compile your C++ program. Here, we will use
Code Blocks, which is an open source platform. You may download it from:
http://sourceforge.net/projects/codeblocks/files/Binaries/17.12/Windows/codeblocks-
17.12mingw-setup.exe. Verify that GNU GCC Compiler is selected as default compiler (Click:
Settings > Compiler > Reset Defaults).

Fig. 1 Code Blocks Window

B. Writing Simple C++ Program


Guideline to make new project in Code Blocks:
1- Start the Code Blocks
2- Make a new project, by selecting File ⇒ New ⇒ Project... ⇒ Console Application ⇒ Go.
In the “Console Application” wizard click “Next” ⇒ Select “C++”, write the project
name (e.g, “lab1”) and choose your project directory. Click “next” and then click Finish.
3- You may start writing C++ code from the available template.
Under the "Management", choose "Projects" tab, expand your project directory and
double click "main.cpp" (see Figure 2).
4- Build the program by selecting “Build” menu, ⇒ Build.
5- Run the program, select "Build" menu ⇒ Run. If successful (no error), Figure 3 should
appear in your screen.

3
L0107-19 – Basic Programming and Lab, Sebelas Maret University

Fig. 2 Creating a project and writing simple C++ code

Fig. 3 Program output

6- If you have an error try to fix and debug it. Don’t worry if you have an error, it is usual
during programming.

7- You may modify your code, such as following and then re-build and re-run it.

//Lab01:Instroduction
#include <iostream>
using namespace std;
int main()
{
cout << "Hi My Name is XXX!" << endl;
cout << "I'm a C++ Programmer Now" << endl;
return 0;
}

Fig. 4 Modifying the code

4
L0107-19 – Basic Programming and Lab, Sebelas Maret University

Lab (02): Variables and Data Types


Objective: In this lab, students will learn how to define variable types and values, and how to
print them. Students will also learn more about conversion specifications. Students will explore
basic and compound mathematical operations, their precedence, and conversion issues.

Variables in C:
Name Description Size* Range*
signed: -128 to 127
char Character or small integer. 1byte unsigned: 0 to 255
Boolean value. It can take one of two
bool values: true or false. 1byte true or false
short signed: -32768 to 32767
int (short) Short Integer. 2bytes Unsigned 0 to 65535
long signed: -2147483648 to 2147483647
int (long) Long integer. 4bytes unsigned: 0 to 4294967295
float Floating point number. 4bytes +/- 3.4e +/- 38 (~7 digits)
Double precision floating point
double number. 8bytes +/- 1.7e +/- 308 (~15 digits)
long Long double precision floating point
double number. 8bytes +/- 1.7e +/- 308 (~15 digits)
String 4bytes

Exercise 01: Working with Variables


Write the following program, run and then analyze it.
// Lab 02a: operating with variables
#include <iostream>
using namespace std;

int main ()
{
// declaring variables:
int a, b;
int result;

// Initialization:
a = 5;
b = 2;

// process:
a = a + 1;
result = a - b;

// print out the result:


cout << "Result= "<< result<<endl;

// terminate the program:


return 0;
}
Exercise 02: (different variable data types)
Write the following program, run and then analyze it.

5
L0107-19 – Basic Programming and Lab, Sebelas Maret University

//Lab02b:Instroduction
#include <iostream>
using namespace std;
int main()
{
/* Declaration */
int i;
bool hasil;
float x;
double y;
char q;
string z;
/* Initialization */
i=325;
x=345.65;
y=5.010210210678;
q='Nama';
z="Nama";
/* Printing to screen */
cout<<endl<<"i="<<i;
hasil = i > 320;
cout<<endl<<"hasil="<<hasil;
//boolean menghasilkan output 1 true atau 0 false
cout<<endl<<"x="<<x;
cout<<endl<<"y="<<y;
cout<<endl<<"q="<<q;
cout<<endl<<"z="<<z;
}

Exercise 03:
This program uses some basic and compound mathematical operations.

#include <iostream>
#include <iomanip> //to use setprecision
//#include <stdio.h>
using namespace std;
int main(){
int a=10,b=3,c,d,e,f,g;
float y,z;
/* Basic operations */
c=a+b;
d=a-b;
e=a*b;
f=a/b;
g=a%b;
cout<<"C="<<c<<"\t"<<"D="<<d<<"\n"<<"E="<<e<<"\
t"<<"F="<<f<<"\n"<<"G="<<g<<"\n"<<endl;
/* Compound Operations */
c+=a;
d-=b;
e*=a;
f/=b;
g++;
cout<<"C="<<c<<"\t"<<"D="<<d<<"\n"<<"E="<<e<<"\
t"<<"F="<<f<<"\n"<<"G="<<g<<"\n"<<endl;
/* Integer/float: is the result correct? */
y=b/2.3;
cout<<"Y="<<y<<"\n"<<endl;
/* Operator Precedence: what is the order of the operations? */
z=b/2.3;
cout<<setprecision(4)<<"Z="<<z<<endl;
}

6
L0107-19 – Basic Programming and Lab, Sebelas Maret University

Lab (03): Control Structure


Objective: In this lab, students explore basic decision making (IF… structure, IF…ELSE…
structure and SWITCH structure).

Exercise 01:
Learn how to make IF statement in C++.
//Lab 3a: IF statement
#include <iostream>
using namespace std;
int main()
{
string nim,mynim="I0719001";
cout << "Enter NIM!" << endl;
cin>> nim;
if (nim==mynim)
{cout<<"This is your own NIM"<<endl;}
return 0;
}

Exercise 02:
Learn how to make IF… ELSE statement in C++.
//Lab 3b: IF... ELSE statement
#include <iostream>
using namespace std;
int main()
{
string nim,mynim="I0719001";
cout << "Enter NIM!" << endl;
cin>> nim;
if (nim==mynim)
{cout<<"This is your own NIM"<<endl;}
else {
{cout<<"This is not your NIM"<<endl;}
}
return 0;
}

Task 01:
Make a C++ program to detect odd and even number!

7
L0107-19 – Basic Programming and Lab, Sebelas Maret University

Exercise 03:
Learn how to make nested IF statement in C++.

// Lab 3c: C++ program to illustrate nested-if statement


#include <iostream>
using namespace std;
int main()
{
int i = 10;
if (i == 10)
{
// First if statement
if (i < 15)
cout<<"i is smaller than 15\n";
// Nested - if statement
if (i < 12)
cout<<"i is smaller than 12 too\n";
else
cout<<"i is greater than 15";
}
return 0;
}

Exercise 04:
Learn how to make SWITCH statement in C++.

// Following is a simple C++ program


// to demonstrate syntax of switch.
#include <iostream>
using namespace std;

int main() {
int x;
cout << "Enter your choice:" << endl;
cin>> x;
switch (x)
{
case 1:
cout << "Choice is 1";
break;
case 2:
cout << "Choice is 2";
break;
case 3:
cout << "Choice is 3";
break;
default:
cout << "Choice other than 1, 2 and 3";
break;
}
return 0;
}

8
L0107-19 – Basic Programming and Lab, Sebelas Maret University

Lab (04): Looping Structure


Objective: In this lab, students explore basic decision making and looping commands (FOR
loop, WHILE loop).

Exercise 01:
Simple FOR loop:

// Lab 4a: Demonstrate for loop


#include <iostream>
using namespace std;
int main() {
int x;
cout << "Enter number of repetition:" << endl;
cin>> x;
// C++ program to illustrate for loop
for (int i = 1; i <= x; i++)
{cout << "Hello World\n";}
return 0;
}

Exercise 02:
Simple WHILE loop:

// C++ program to illustrate WHILE loop


#include <iostream>
using namespace std;
int main()
{
// initialization expression
int i = 1;
// test expression
while (i < 6)
{
cout << "Hello World\n";
// update expression
i++;
}
return 0;
}

Task 01:
Make nested loop for exercise 1!

9
L0107-19 – Basic Programming and Lab, Sebelas Maret University

Exercise 03: (Introduce “goto” function, combine control and loop structure, etc)
1
Calculate the sum of series fraction numbers ( ), for n<100!
n2
N
1 1 1 1
2
1 ... ...?
n 1 n 4 9 N2

#include <iostream>
#include <iomanip>
#include <cmath>
#define PI 2.0*asin(1.0)
using namespace std;

int main()
{
int n ;
double x , term, sum , exact_sum;
sum = 0.0 ;
exact_sum = PI*PI/6.0 ;
lower: cout<<"Enter number of terms N = ";
cin>>n;

if( n > 100 )


{
cout<<("Please Enter a Lower Number\n\n");
goto lower ;
}
cout<<("N \t Nth Term \t Sum\n");

for ( x = 1.0 ; x <= n ; x++ )


{
term = 1.0/(x*x);
sum += term ;

cout<<x<<"\t"<<setw(10)<<term<<"\t"<<setw(8)<<sum<<"\n"
;
}
cout<<"\n\nFor N = infinity, Sum = "<<exact_sum<<endl;
}

Task 02:
Modify the above program using if-else statement and do while looping!

10
L0107-19 – Basic Programming and Lab, Sebelas Maret University

Lab (05): Simple Engineering Problem


Objective: In this lab, students will examine the applications of C++ programming in
engineering system.

Pre-lab: each student or group of student are asked to bring a simple engineering problem then
write the program in the class.

Exercise 1: Exercise 2:

write a C++ program to evaluate the function Read and average 6 integers using while loop, print the
written below. result.
#include <iostream>
2
x x for ( x 0) using namespace std;
x
int main()
y 1 e for ( 10 x 0) {
int x;
x 5 for ( x 10)
int count = 0;
double sum = 0;
#include <iostream> double average;
using namespace std;
int main() // prompt the user:
{ double x,y; cout << "Enter six grades separated by a single
space, then press <Enter>: ";
cout << " Enter the value of x"; while( count < 6)
cin >> x; {
cin >> x;
if (x >= 0 ) sum = sum + x;
y= x*x + sqrt(x); count++;
else if ( x > -10 && x < 0 ) }
y= 1 - exp (x); cout << endl;
else
y= fabs ( x + 5 ); average = sum/6;
cout << "The average is " << average << endl;
cout << " y = " <<y<<endl;
return 0;
return 0; }
}

11
L0107-19 – Basic Programming and Lab, Sebelas Maret University

Problem Example 03: Electrical Circuit Analysis

Mesh analyzis:

(R1+R2)i1-R2i2+0i3=V1

-R2i1+(R2+R3+R4)i2-R4i3=0

0i1-R4i2+(R4+R5)i3=-V2

R1-R5=1 Ohm, V1,V2=5 volt

2i1-i2+0i3=5

-i1+3i2-i3=0

0i1-i2+2i3=-5

I1, i2, 13=….. ?

12
L0107-19 – Basic Programming and Lab, Sebelas Maret University

Lab (06): Function


Objective: In this lab, students explore how to create their own function.

Exercise 01:
Make a program to calculate factorial (n!) and binomial coefficient, defined by:

#include <iostream>
using namespace std;

int main()
{
int factorial(int);
int p,n,k, result1,result2;
// computing factorial ( max number 12!)
cout<<"Enter number to be factorial(ex: 8 for 8!): ";
cin>>p;
result1=factorial(p);
cout<<p<<"!="<<result1<<endl;
// Binomial calculation
cout<<"Enter number for (n) of binomial cooficient: ";
cin>>n;
cout<<"Enter number for (k) of binomial cooficient: ";
cin>>k;
result2=factorial(n)/(factorial(k)*factorial(n-k));
cout<<result2<<endl;
}
int factorial(int n)
{
int i,r=n;
for (i=n;i>1;i--)
{
r=r*(i-1);
}
return r;
}

Task 01:
Create a your own C++ program that contain at least one user-defined function!

13
L0107-19 – Basic Programming and Lab, Sebelas Maret University

Lab (07): Array


Objective: In this lab, students will learn how to build a matrix using array.

Exercise 01:
Make a program to create a 3x3 matrix by using an array!

#include <iostream>
using namespace std;
int main()
{
int i,j;
int a[3][3]= {1,2,3,10,20,30,100} ;
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
cout<<a[i][j]<<"\t";
}
cout<<"\n";
}
}

Task 01:
Create a your own C program that mutiply two matrix (C=AxB)! The dimension of the matrices
is up to you. Example: calculate C=AxB, for the following matrices.

14
L0107-19 – Basic Programming and Lab, Sebelas Maret University

Lab (08): String


Objective: In this lab, student will learn about string and string manipulation in C++
programming.

Exercise 01: Write a C++ program to read your name string from terminal! We may use getline
(read whole line) or use cin (read only one word).

#include <string>
#include <iostream>
using namespace std;
int main()
{
string name1,name2;
cout<<"Enter name: ";
getline (cin, name1);
cout<<"Your name is "<<name1;

cout<<"\nEnter name again: ";


cin>>name2;
cout<<"Your name is "<<name2;
return 0;
}

Exercise 02: String manipulation (copy, combine, edit, searching, …)

//Lab 08b: string manipulation


#include <string>
#include <iostream> Task 01: Explore more about
using namespace std; string operations (swap, etc...)!
int main()
{ Read sourcer from Internet.
string s1= "Hello";
string s2= "World";
string s3,s4;
//Add space after string Task 02: Make a program to
s1+=' ';
//Combine two string read an UNS student ID number
s3=s1+s2; then display the admission year
cout<<"s3=s1+s2: "<<s3<<endl;
//Copy s1 to s4 of the student. (For example if
s4+=s1;
cout<<"s4=s1: "<<s4<<endl; the ID is I0719001 then the
//Modify character and make uppercase
s1[4]='y'; admission year is 2019)
s1[1] = toupper (s1[1]);
cout<<"\nNew s1: "<<s1;
int position = s3.find (' ');
cout<<"\nposition: "<<position<<endl;
return 0;
}

15
L0107-19 – Basic Programming and Lab, Sebelas Maret University

Lab (09): Input and Output Files

Objective: In this lab, student will study reading from and writing to external files.

Exercise 01:
Write a program that converts degrees Celsius (TC) to degree Fahrenheit (TF) (Recall that TF =
(9/5) TC + 32). The program reads TC from input file “input.txt” and writes TF to the file
“output.txt”. Note: before running your program, add the input file first!

// C++ Lab 8 Exercise 1


#include <iostream>
#include <fstream>

using namespace std;


int main()
{
double TC,TF;
ifstream inputfile;
inputfile.open ("input.txt");
ofstream outputfile;
outputfile.open ("output.txt");

while(!inputfile.eof()){
inputfile>> TC;
TF = (9/5.0)*TC+32;
outputfile<<TC << "\t" <<TF<<endl;
}

cout<<"Finish reading and writting a


file...\n\n\a\a\a";
return 0;
}

Task 01:
If the file (input.txt) contains the following data. The first column is voltage and the second column is the electric
current.

3.0 2.1
1.5 1.1
2.6 4.1

Write program that reads the voltages and currents then calculates the electric power (P) based on the equation:
P=v*i
Write your output to the file (output.txt) with voltage in the first, current in the second and power on the third
column. Your output file should look like:

Voltage Current Power


3.0 2.1 (result)
1.5 1.1 (result)
2.6 4.1 (result)

16
L0107-19 – Basic Programming and Lab, Sebelas Maret University

Lab (10): Pointer, Record, etc


Objective: In in this lab, students will learn how to use a pointers, record and other.

Exercise 01: This program give simple example of pointer in C++! Pointers store address of
variables or a memory location.

#include <iostream>
using namespace std;
int main () {
int var = 20; // Variable declaration.
int *ip; // pointer variable
ip = &var; // store address of var in pointer

// print value inside the variable


cout << "Value of var variable: "<<var<<endl;
// print address of variable var
cout << "Address of var variable:
"<<&var<<endl<<endl;
(Credit: https://simplesnippets.tech/)

// print value inside the pointer ip


cout << "Value inside pointer ip: "<<ip<<endl;
// print value of variable using pointer ip
cout << "Variable value using Pointer: "<<*ip;

return 0;
}

Exercise 02: Access array elements using pointers!

#include <iostream>
using namespace std;
int main()
{
int data[5], i;
cout<<"Enter elements: ";

for(i = 0; i < 5; ++i){


cin>>data[i];
}
cout<<"You entered: \n";
for(i = 0; i < 5; ++i){
cout<< *(data + i)<<"\n";
}
return 0;
}

17
L0107-19 – Basic Programming and Lab, Sebelas Maret University

Exercise 03: Record/Structure. A record is a collection of variables, possibly of different data


types.

#include <iostream>
using namespace std;

struct datamahasiswa
{
char nama[50];
char asal[50];
int tahun;
};
struct datamahasiswa s[5];

int main()
{
int i;
for (i=0;i<5;i++)
{
cout<<"\nMasukkan informasi Mahasiswa ke-:"<<i;
cout<<"\nMasukkan nama: ";
cin>>s[i].nama;
cout<<"Enter asal: ";
cin>>s[i].asal;
cout<<"Enter tahun: ";
cin>>s[i].tahun;
}
cout<<"\nNama 1: "<<s[0].nama;
cout<<"\nNama 2: "<<s[3].nama<<endl;

return 0;
}

Task 01: Use record to read and save data from a file containing list of student ID and their final
exam scores. Allow user to display score from a selected student.

18

You might also like