Sei sulla pagina 1di 20

lkSebelas Maret University

College of Engineering, Electrical Engineering Department

Labwork Manual:
EL0107-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: 7/10/2019
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 printf() 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 : String and Array


In this lab, students will learn how to build a matrix using array. Student will learn also
about string in C programming.

Lab 8 : Input and Output


In this lab, the scanf() instruction is introduced. Reading from/ writing to external files
through fscanf() / fprintf() is also introduced.

Lab 9 : Pointer in C
In in this lab, students will learn how to build a pointers and other.

Lab 10 : Engineering Problem


In this lab, students will try to make their own C++ program in engineering system.

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 printf() 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:

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 for 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;
}

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

Exercise 03:
1
Calculate the sum of series fraction numbers ( ), for n<100!
n2
N 1 1 1 1

n
n1
2
1
4

9
 ...  2 ...?
N

#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 01:
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>
x2  x for(x  0)
 using namespace std;
y   ex for(10  x  0) int main()
 1
 x 5 {
for(x  10) int x;

 int count = 0;
double sum = 0;
#include <iostream> double average;
using namespace std;
int main() // prompt the user:
{ double y; cout << "Enter six grades separated by a single
Int x; space, then press <Enter>: ";
while( count < 6)
cout << " Enter the value of x"; {
cin >> x; cin >> x;
sum = sum + x;
if (x >= 0 ) count++;
y= x*x + sqrt(x); }
else if ( x > -10 && x < 0 ) cout << endl;
y= 1 - exp (x);
else average = sum/6;
y= fabs ( x + 5 ); 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

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

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

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

2i1-i2+0i3=5

-i1+3i2-i3=0

0i1-i2+2i3=-5
R1-R5=1 Ohm, V1,V2=5 volt

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 and String


Objective: In this lab, students will learn how to build a matrix using array. Student will learn
also about string in C programming.

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.

Exercise 02:

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

Write a C program to read your name string from terminal!

#include <iostream>
using namespace std;
int main()
{
char name[20];
cout<<"Enter name: ";
cin>>name;
cout<<"Your name is "<<name;
return 0;
}

Exercise 03:
Combining two strings!

#include <cstring>
#include <iostream>
using namespace std;
int main()
{
char s1[10] = "Hello";
char s2[10] = "World";
strncat(s1,s2, 3);
cout<<"Concatenation using strncat: "<<s1<<endl;
return 0;
}

Task 02:
Explore more about string operations (copying, etc...)!

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

Lab (08): Input and Output


Objective: In this lab, the scanf() instruction is introduced. Reading from/ writing to external
files through fscanf() / fprintf() is also introduced.

Standard Input-Output functions:

Exercise 01:
Write the following program, then compile and execute. Try to modify the program.
//Lab08:Input and Output
# include <iostream>
using namespace std ;
int main ()
{
char pilihan ;
cout << " Main Menu " ; cout << endl << endl ;
cout << " 1. Operasi Penjumlahan " ; cout << endl ;
cout << " 2. Operasi Pengurangan " ; cout << endl ;
cout << " 3. Operasi Perkalian " ; cout << endl ;
cout << " 4. Operasi Pembagian " ; cout << endl << endl ;
cout << " Masukkan Pilihan Anda : " ;
cin >> pilihan ;
switch ( pilihan ) {
case '1' :
float satu,dua,jumlah ;
cout << endl ;
cout << " Operasi Penjumlahan " ; cout << endl << endl ;
cout << " Masukkan Nilai Pertama = " ;
cin >> satu ;
cout << " Masukkan Nilai Kedua = " ;
cin >> dua ;
jumlah = satu + dua ;
cout << " Hasil Penjumlahan Dua Buah Bilangan Tersebut Adalah " << jumlah ;
cout << endl << endl ;
break ;

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

case '2' :
float tiga,empat,kurang ;
cout << endl ;
cout << " Operasi Pengurangan " ; cout << endl << endl ;
cout << " Masukkan Nilai Pertama = " ;
cin >> tiga ;
cout << " Masukkan Nilai Kedua = " ;
cin >> empat ;
kurang = tiga - empat ;
cout << " Hasil Pengurangan Dua Buah Bilangan Tersebut Adalah " << kurang ;
cout << endl << endl ;
break ;
case '3' :
float lima,enam,kali ;
cout << endl ;
cout << " Operasi Perkalian " ; cout << endl << endl ;
cout << " Masukkan Nilai Pertama = " ;
cin >> lima ;
cout << " Masukkan Nilai Kedua = " ;
cin >> enam ;
kali = lima * enam ;
cout << " Hasil Perkalian Dua Buah Bilangan Tersebut Adalah " << kali ;
cout << endl << endl ;
break ;
case '4' :
float tujuh,delapan,bagi ;
cout << endl ;
cout << " Operasi Pembagian " ; cout << endl << endl ;
cout << " Masukkan Nilai Pertama = " ;
cin >> tujuh ;
cout << " Masukkan Nilai Kedua = " ;
cin >> delapan ;
bagi = tujuh / delapan ;
cout << " Hasil Pembagian Dua Buah Bilangan Tersebut Adalah " << bagi ;
cout << endl << endl ;
break ;
default :
cout << " Anda Salah Pilihan " ;
cout << endl ;
}
return 0 ;
}

Exercise 02:
1. Change the previous program to read from an input file. Do the following:
17
L0107-19 – Basic Programming and Lab, Sebelas Maret University

- Add in the declaration section: FILE *in;


- Add after the declaration part: in=fopen("inputfile.txt","r");
- Change each scanf("…",&..); instruction to fscanf(in,"…",&..);
The file should include the input values, and should be located in the same folder of your
program

#include <stdio.h>
#include <stdlib.h>
void main (void)
{
/* declaration */
int a;
float x;
double y;
FILE *in;
in=fopen("inputfile.txt","r");

printf("Enter a (interger)=");
fscanf(in,"%d",&a);
printf("a=%d\n", a);

printf("Enter x (float)=");
fscanf(in,"%f",&x);
printf("x=%f\n", x);

printf("Enter y (double)=");
fscanf(in, "%lf",&y);
printf("y=%lf\n", y);
}

2- Now change the program such that it writes the output to an external file called outputfile.txt
by doing the following:
- Change the file pointer declaration to: FILE *in, *out;
- Add after the declaration part: out=fopen("outputfile.txt","w");
- Change each printf("…",..); instruction to fprintf(out,"…",..);

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

Lab (09): Pointer


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

Exercise 01:
This program give simple example of pointer in C!

//Lab09:Pointer
#include <iostream>
using namespace std;

int main()
{
int Var = 5;
int *VarPoint; // It is said that VarPoint is of type ' int * ' which stores an address.

VarPoint = &Var;// & unary operator returns the address of the variable.
// In General the statement : VarPoint = Var; is an error.
// Because VarPoint is of type ' int * ' but Var is of type ' int ' and these are not convertable to
each other.

cout << "The VALUE which is pointed by VarPoint is : " << *VarPoint << endl;
// * unary operator returns the value of an address. See the difference in these 2 statements.
cout << "The ADDRESS which is pointed by VarPoint is : " << VarPoint << endl;
cout << "The address of VarPoint itself is : " << &VarPoint << endl << endl;

cout << "Enter a new value for VarPoint : ";


cin >> *VarPoint;
cout << "The value of Val has become : ";
cout << Var << endl;

return 0;
}

Exercise 02:
Access array elements using pointers!
19
L0107-19 – Basic Programming and Lab, Sebelas Maret University

#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;
}

Record/Structure:

#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;
}

20

Potrebbero piacerti anche