C++ 2 Ganjil 2018-2019
C++ 2 Ganjil 2018-2019
Fundamental Types
Boolean Type
…
int main()
{
bool flag = false;
cout<<“flag= “ <<flag<<endl;
flag = true;
cout<<“flag= “ <<flag<<endl;
…
Character Types
Character Types
…
int main ()
{
char c=‘A’;
cout<<“c = “<< c << “, int(c) = “ << int (c) <<endl;
char c=‘a’;
cout<<“c = “<< c << “, int(c) = “ << int (c) <<endl;
char c=‘\t’;
cout<<“c = “<< c << “, int(c) = “ << int (c) <<endl;
char c=‘!’;
cout<<“c = “<< c << “, int(c) = “ << int (c) <<endl;
…
• char :1
• short :2
• int :4
• unsigned short :2
• unsigned int :4
• float :4
• double :8
Integer Types
Types Conversion
…
int main()
{
char c = 'A';
cout<<"char c =" << c <<endl;
short k = c;
cout<<"short k =" << k<<endl;
int m = k;
cout<<"int m =" << m <<endl;
float x = m;
cout<<"float x =" << x <<endl;
double y = x;
cout<<"double y =" << y <<endl;
cout<<endl;
double a = 1234.5678;
cout<<"double a =" << a <<endl;
int b = a;
cout<<"int b =" << b <<endl;
…
Types Conversion
Arithmetic
Arithmetic
• Arithmetic calculations
– *
• Multiplication
– /
• Division
• Integer division truncates remainder
– 7 / 5 evaluates to 1
– %
Square Root
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int nilai;
cout<<"Masukkan sebuah nilai: ";
cin >> nilai;
int hasil = sqrt(nilai);
cout<< "Hasil akar pangkat dua dari nilai tersebut = " << hasil << endl;
system ("pause");
return 0;
More on Arithmetic
• Pangkat
– a2 → pow (a,2)
Exercise
• Preincrement
– Variable changed before used in expression
• Operator before variable (++c or --c)
• Postincrement
– Incremented changed after expression
• Operator after variable (c++, c--)
• If c = 5, then
– cout << ++c;
• c is changed to 6, then printed out
int main()
{
int m, n;
m =44;
n = ++m;
cout<< "m = " << m << " n = " << n <<endl;
m =44;
n = m++;
cout<< "m = " << m << " n = " << n <<endl;
system("pause");
return 0;
}
Scope
…
int main ()
{
x=11; //error
int x;
{
x=22; //ok
y=33; //error
int y;
x=44; //ok
y=55; //ok
}
x=66; //ok
y=77; //error
…
}