Wprowadzenie do C++ ...
Szablon
Tak zwykle będziemy zaczynać program
#include <iostream>
using namespace std;
main() {
system("pause");
return 0;
}
Program 1
Pytamy o imię i witamy się
#include <iostream>
using namespace std;
main() {
string imie;
cout << "Podaj imie" << endl;
cin >> imie;
cout << "Witaj " << imie << endl;
system("pause");
return 0;
}
Program 2
Instrukcja warunkowa - if
#include <iostream>
using namespace std;
main() {
int wiek;
cout << "Ile masz lat?" << endl;
cin >> wiek;
if(wiek>18) {
cout << "Jestes juz pelnoletni." << endl;
} else {
cout << "Jestes jeszcze bardzo mlody." << endl;
}
system("pause");
return 0;
}
Program 3
Pętla for
#include <iostream>
using namespace std;
main() {
for(int i=1;i<=10;i++) {
cout << i << endl;
}
system("pause");
return 0;
}
Program 4
Liczba pierwsza
#include <iostream>
using namespace std;
main() {
int liczba;
cin >> liczba;
int k=0;
for(int i=2;i<liczba;i++) {
if(liczba%2==0) {
cout << "Liczba zlozona" << endl;
k=1;
break;
}
}
if(k==0) {
cout << "Liczba pierwsza" << endl;
}
system("pause");
return 0;
}
Program 5
Funkcja
#include <iostream>
using namespace std;
int suma(int a, int b, int c) {
return a+b+c;
}
main() {
cout << suma(4,6,7) << endl;
cout << suma(10,20,30) << endl;
system("pause");
return 0;
}
Program 6
NWD(największy wspólny dzielnik) - algorytm Euklidesa
#include <iostream>
using namespace std;
main() {
int a,b;
cin >> a >> b;
for(;;) {
if(a!=b) {
if(a>b) { a=a-b; }
else
{ b=b-a; }
} else {
break;
}
}
cout << a << endl;
system("pause");
return 0;
}
lub jako funkcja - łącznie z algorytmem MWW(najmniejsza wspólna wielokrotność - wspólny mianownik)
#include <iostream>
using namespace std;
int nwd(int a,int b) {
for(;;)
{
if(b!=a) {
if(a>b){ a=a-b; }
else { b=b-a; }
} else { break; }
}
return a;
}
int nww(int a,int b) {
return (a*b) / nwd(a,b);
}
main() {
cout << nwd(12,64) << endl;
cout << nww(3,4) << endl;
system("pause");
return 0;
}
Typy danych
| Nazwa typu | Liczba bajtów | Zakres wartości |
| bool | 1 | false lub true |
| char | 1 | od -128 do 127 |
| unsigned char | 1 | od 0 do 255 |
| wchar_t | 2 | od 0 do 65 535 |
| short | 2 | od -32 768 do 32 767 |
| unsigned short | 2 | od 0 do 65 535 |
| int | 4 | od -2 147 483 648 do 2 147 483 647 |
| unsigned int | 4 | od 0 do 4 294 967 295 |
| long | 4 | od -2 147 483 648 do 2 147 483 647 |
| unsigned long | 4 | od 0 do 4 294 967 295 |
| long long | 8 | od -9 223 372 036 854 775 808 do 9 223 372 036 854 775 807 |
| unsigned long long | 8 | od 0 do 18 446 744 073 709 551 615 |
| float | 4 | 3.4E +/- 38 (7 cyfr) |
| double | 8 | 1.7E +/- 308 (15 cyfr) |
| long double | 8 | 1.7E +/- 308 (15 cyfr) |