//C++로 시작하는 객체지향 프로그래밍 p.356 예제 8.5 - 대수학 : 두 행렬의 합
#include <iostream>
using namespace std;
const int N = 3;
void addMatrix(const double a[][N], const double b[][N], double c[][N]){
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
c[i][j] = a[i][j] + b[i][j];
}
void printResult(double a[][N], double b[][N], double c[][N]) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
cout << " " << a[i][j] << ' ';
}
if (i == N / 2)
cout << " = ";
else cout << " ";
}
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
cout << " " << b[i][j] << ' ';
if (i == N / 2)
cout << " = ";
else cout << " ";
}
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
cout << " " << c[i][j] << ' ';
if (i == N / 2)
cout << " = ";
else cout << " ";
cout << endl;
}
}
}
int main() {
int i, j;
double a[N][N], b[N][N], c[N][N];
cout << "Enter Matrix 1: ";
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
cin >> a[i][j];
}
cout << "Enter Matrix 2: ";
for (int i = 0; i < N; i++) {
for (int k = 0; k < N; k++)
cin >> b[i][k];
}
addMatrix(a, b, c);
printResult(a, b, c);
system("pause");
return 0;
}
7.07.2017
2차원 배열 - 틱택토(TicTacToe) 게임
//C++로 시작하는 객체지향 프로그래밍 p.363 예제 8.20
/* 틱택토 게임은 두 명이 번갈아가며 o나 x(이를 토근이라함)를 3x3 격자판에 써서,
같은 글자를 가로, 세로, 혹은 대각선상에 놓이도록 하는 게임이다. 한 사람이 ㅜ평, 수직 또는 대각선에 3개의 같은 토큰을 표시하면 게임이 끝나고 승자가 된다. 격자판이 토큰으로 모두 채워진 상태에ㅓ 승자가 없는 경우도 있다. 틱택토 게임을 하는 프로그램을 작성하여라. 프로그램에서는 우선 첫 번째 사람이 x토근을 입력하고, 두 번째 사람이 o토큰을 입력하도록 한다. 프로그램에 토큰이 입력될 때마다 프로그램은 콘솔 상의 보드에 입력 토큰을 출력해야 하고 게임의 상태(승리, 무승부, 게임 중)를 결정한다.*/
#include <iostream>
using namespace std;
void init_board(char board[][3]);
void display_board(char board[][3]);
int get_player_move(int player, char board[][3]);
int main() {
char board[3][3];
int quit = 0;
init_board(board); //보드 초기화
do {
display_board(board); // 보드를 화면에 출력한다.
quit = get_player_move(0, board); // 사용자의 입력
display_board(board); // 보드를 화면에 출력한다.
quit = get_player_move(1, board); //사용자의 입력
} while (quit == 0);
system("pause");
return 0;
}
//board 초기화
void init_board(char board[][3]) {
int x, y;
for (x = 0; x < 3; x++) {
for (y = 0; y < 3; y++)
board[x][y] = ' ';
}
}
void display_board(char board[][3]) {
int i, j;
for (i = 0; i < 3; i++) {
cout << "---|---|---" << endl;
for (j = 0; j < 3; j++) {
cout << " " << board[i][j] << " ";
} cout << endl;
} cout << "---|---|---" << endl;
}
int get_player_move(int player, char board[][3]) {
int x, y, done = 0;
while (done != 1) {
cout << "player " << player << ", (x, y) 좌표 (종료 -1, -1) :";
cin >> x >> y;
if (x == -1 && y == -1) return 1;
if (board[x][y] == ' ') break;
else cout << "잘못된 위치임" << endl;
}
if (player == 0) board[x][y] = 'X';
else board[x][y] = 'O';
return 0;
}
/* 틱택토 게임은 두 명이 번갈아가며 o나 x(이를 토근이라함)를 3x3 격자판에 써서,
같은 글자를 가로, 세로, 혹은 대각선상에 놓이도록 하는 게임이다. 한 사람이 ㅜ평, 수직 또는 대각선에 3개의 같은 토큰을 표시하면 게임이 끝나고 승자가 된다. 격자판이 토큰으로 모두 채워진 상태에ㅓ 승자가 없는 경우도 있다. 틱택토 게임을 하는 프로그램을 작성하여라. 프로그램에서는 우선 첫 번째 사람이 x토근을 입력하고, 두 번째 사람이 o토큰을 입력하도록 한다. 프로그램에 토큰이 입력될 때마다 프로그램은 콘솔 상의 보드에 입력 토큰을 출력해야 하고 게임의 상태(승리, 무승부, 게임 중)를 결정한다.*/
#include <iostream>
using namespace std;
void init_board(char board[][3]);
void display_board(char board[][3]);
int get_player_move(int player, char board[][3]);
int main() {
char board[3][3];
int quit = 0;
init_board(board); //보드 초기화
do {
display_board(board); // 보드를 화면에 출력한다.
quit = get_player_move(0, board); // 사용자의 입력
display_board(board); // 보드를 화면에 출력한다.
quit = get_player_move(1, board); //사용자의 입력
} while (quit == 0);
system("pause");
return 0;
}
//board 초기화
void init_board(char board[][3]) {
int x, y;
for (x = 0; x < 3; x++) {
for (y = 0; y < 3; y++)
board[x][y] = ' ';
}
}
void display_board(char board[][3]) {
int i, j;
for (i = 0; i < 3; i++) {
cout << "---|---|---" << endl;
for (j = 0; j < 3; j++) {
cout << " " << board[i][j] << " ";
} cout << endl;
} cout << "---|---|---" << endl;
}
int get_player_move(int player, char board[][3]) {
int x, y, done = 0;
while (done != 1) {
cout << "player " << player << ", (x, y) 좌표 (종료 -1, -1) :";
cin >> x >> y;
if (x == -1 && y == -1) return 1;
if (board[x][y] == ' ') break;
else cout << "잘못된 위치임" << endl;
}
if (player == 0) board[x][y] = 'X';
else board[x][y] = 'O';
return 0;
}
가장 큰 요소의 위치 - 2차원 배열
//C++로 시작하는 객체지향 프로그래밍 p.361 예제 8.17 - 가장 큰 요소의 위치
#include <iostream>
using namespace std;
const int ROW_SIZE = 3;
const int COLUMN_SIZE = 4;
void locateLargest(const double a[][4], int location[]) {
int row = 0, column = 0;
double maxvalue = a[0][0];
for (int i = 0; i < ROW_SIZE; i++) {
for(int j = 0; j < COLUMN_SIZE; j++)
if (maxvalue < a[i][j]) {
row = i;
column = j;
maxvalue = a[i][j];
}
}
location[0] = row;
location[1] = column;
}
int main() {
double array[3][4];
cout << "Enter the array: ";
for (int i = 0; i < ROW_SIZE; i++) {
for (int j = 0; j < COLUMN_SIZE; j++) {
cin >> array[i][j];
}
}
int loc[2];
locateLargest(array, loc);
cout << "The location of the largest element is " <<
array[loc[0]][loc[1]] << "at (" << loc[0] << ", " << loc[1] << ")" << endl;
system("pause");
return 0;
}
#include <iostream>
using namespace std;
const int ROW_SIZE = 3;
const int COLUMN_SIZE = 4;
void locateLargest(const double a[][4], int location[]) {
int row = 0, column = 0;
double maxvalue = a[0][0];
for (int i = 0; i < ROW_SIZE; i++) {
for(int j = 0; j < COLUMN_SIZE; j++)
if (maxvalue < a[i][j]) {
row = i;
column = j;
maxvalue = a[i][j];
}
}
location[0] = row;
location[1] = column;
}
int main() {
double array[3][4];
cout << "Enter the array: ";
for (int i = 0; i < ROW_SIZE; i++) {
for (int j = 0; j < COLUMN_SIZE; j++) {
cin >> array[i][j];
}
}
int loc[2];
locateLargest(array, loc);
cout << "The location of the largest element is " <<
array[loc[0]][loc[1]] << "at (" << loc[0] << ", " << loc[1] << ")" << endl;
system("pause");
return 0;
}
7.06.2017
2진수를 10진수로 변환(문자열 이용)
//C++로 시작하는 객체지향 프로그래밍 p.334 예제 7.41 - 2진수를 10진수로 변환
#include <iostream>
#include <string>
using namespace std;
int bin2Dec(const char binaryString[]){
int value = binaryString[0] - '0';
for( int i = 1; i < strlen(binaryString); i++){
value = value * 2 + binaryString[i] - '0';
}
return value;
}
int main(){
cout << "Enter a binary Number: ";
char binaryString[80];
cin >> binaryString;
cout << bin2Dec(binaryString) << endl;
system("pause");
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int bin2Dec(const char binaryString[]){
int value = binaryString[0] - '0';
for( int i = 1; i < strlen(binaryString); i++){
value = value * 2 + binaryString[i] - '0';
}
return value;
}
int main(){
cout << "Enter a binary Number: ";
char binaryString[80];
cin >> binaryString;
cout << bin2Dec(binaryString) << endl;
system("pause");
return 0;
}
가장 긴 공통 접두어
//C++로 시작하는 객체지향 프로그래밍 p.334 예제 7.32 - 가장 긴 공통 접두어
#include <iostream>
#include <string>
using namespace std;
void prefix(const char s1[], const char s2[], char commonPrefix[]){
int len = strlen(s1);
int i = 0;
for (i = 0; i < len; i++){
if (s1[i]==s2[i]) {
commonPrefix[i] = s1[i];
}else break;
}
commonPrefix[i] = '\0'; // Set a null terminator
}
int main(){
//Prompt the use to enter two strings
cout << "Enter a string s1: ";
char s1[80];
cin.getline(s1, 80);
//Prompt the user to enter two strings
cout << "Enter a string s2: ";
char s2[80];
cin.getline(s2, 80);
char s3[80];
prefix(s1,s2,s3);
if(strlen(s3) ==0)
cout << "No common prefix" << endl;
else cout << "The commom prefix is " << s3 << endl;
system("pause");
return 0;
}
#include <iostream>
#include <string>
using namespace std;
void prefix(const char s1[], const char s2[], char commonPrefix[]){
int len = strlen(s1);
int i = 0;
for (i = 0; i < len; i++){
if (s1[i]==s2[i]) {
commonPrefix[i] = s1[i];
}else break;
}
commonPrefix[i] = '\0'; // Set a null terminator
}
int main(){
//Prompt the use to enter two strings
cout << "Enter a string s1: ";
char s1[80];
cin.getline(s1, 80);
//Prompt the user to enter two strings
cout << "Enter a string s2: ";
char s2[80];
cin.getline(s2, 80);
char s3[80];
prefix(s1,s2,s3);
if(strlen(s3) ==0)
cout << "No common prefix" << endl;
else cout << "The commom prefix is " << s3 << endl;
system("pause");
return 0;
}
패턴 인식: 4개의 동일 연속 번호
//C++로 시작하는 객체지향 프로그래밍 p.332 예제 7.24 - 패턴 인식 : 4개의 동일 연속 번호
#include <iostream>
using namespace std;
bool isConsecutiveFour (const int values[], int size);
int main(){
const int SIZE = 80;
int numbers[SIZE];
cout << "Enter the numbers: ";
int size, j = 0, k= 0;
cin >> size;
for (int i = 0; i < size; i++){
cin >> numbers[i];
}
if (isConsecutiveFour(numbers, size))
cout << "The series has consecutive fours" << endl;
else cout << "The series has no consecutive fours" << endl;
system("pause");
return 0;
}
bool isConsecutiveFour (const int values[], int size){
for (int i = 0; i < size - 3; i++){
bool isEqual = true;
for (int j = i; j < i + 3; j++){
if (values[j] != values[j+1]) {
isEqual = false;
break;
}
}
if (isEqual) return true;
}
return false;
}
#include <iostream>
using namespace std;
bool isConsecutiveFour (const int values[], int size);
int main(){
const int SIZE = 80;
int numbers[SIZE];
cout << "Enter the numbers: ";
int size, j = 0, k= 0;
cin >> size;
for (int i = 0; i < size; i++){
cin >> numbers[i];
}
if (isConsecutiveFour(numbers, size))
cout << "The series has consecutive fours" << endl;
else cout << "The series has no consecutive fours" << endl;
system("pause");
return 0;
}
bool isConsecutiveFour (const int values[], int size){
for (int i = 0; i < size - 3; i++){
bool isEqual = true;
for (int j = i; j < i + 3; j++){
if (values[j] != values[j+1]) {
isEqual = false;
break;
}
}
if (isEqual) return true;
}
return false;
}
완전 동일 배열
//C++로 시작하는 객체지향 프로그래밍 p.330 예제 7.20 - 완전 동일 배열
#include <iostream>
using namespace std;
bool strictlyEqual(const int list1[], const int list2[], int size) {
for (int k = 0; k < size; k++){
if (list1[k] != list2[k])
return false;
return true;
}
}
int main() {
const int SIZE = 20;
int list1[SIZE];
cout << "Enter list1: ";
int size1;
cin >> size1;
for (int i = 0; i < size1; i++){
cin >> list1[i];
}
cout << "Enter list2: ";
int list2[SIZE];
int size2;
cin >> size2;
for (int j = 0; j < size2; j++){
cin >> list2[j];
}
if (size1 == size2 && strictlyEqual(list1, list2, size1))
cout << "Two lists are strictly identical" << endl;
else cout << "Two lists are not strictly identical" << endl;
system("pause");
return 0;
}
#include <iostream>
using namespace std;
bool strictlyEqual(const int list1[], const int list2[], int size) {
for (int k = 0; k < size; k++){
if (list1[k] != list2[k])
return false;
return true;
}
}
int main() {
const int SIZE = 20;
int list1[SIZE];
cout << "Enter list1: ";
int size1;
cin >> size1;
for (int i = 0; i < size1; i++){
cin >> list1[i];
}
cout << "Enter list2: ";
int list2[SIZE];
int size2;
cin >> size2;
for (int j = 0; j < size2; j++){
cin >> list2[j];
}
if (size1 == size2 && strictlyEqual(list1, list2, size1))
cout << "Two lists are strictly identical" << endl;
else cout << "Two lists are not strictly identical" << endl;
system("pause");
return 0;
}
7.05.2017
선택 정렬 수정(내림차순)
//C++로 시작하는 객체지향 프로그래밍 p.328 예제 7.16 - 선택 정렬 수정(내림차순)
/* 최댓값을 구해 그 값과 주어진 목록의 마지막 번째 수를 교환하기. 10개의 double 형 값을 배열로 입력하도록 함.*/
#include <iostream>
using namespace std;
void selectionSort(double list[], int size){
double max;
int indexOfMax;
for (int i = 0; i < size - 1; i++){
max = list[i];
indexOfMax = i;
for (int j = i + 1; j < size; j++)
if(max<list[j]) {
max = list[j];
indexOfMax = j;
}
list[indexOfMax] = list[i];
list[i] = max;
}
for (int i = 0; i < size; i++)
cout << list[i] << " ";
}
int main() {
const int SIZE = 10;
double numbers[SIZE];
for (int i = 0; i < SIZE; i++){
cout << "Enter a NUmber : ";
cin >> numbers[i];
}
selectionSort(numbers,SIZE);
system("pause");
return 0 ;
}
/* 최댓값을 구해 그 값과 주어진 목록의 마지막 번째 수를 교환하기. 10개의 double 형 값을 배열로 입력하도록 함.*/
#include <iostream>
using namespace std;
void selectionSort(double list[], int size){
double max;
int indexOfMax;
for (int i = 0; i < size - 1; i++){
max = list[i];
indexOfMax = i;
for (int j = i + 1; j < size; j++)
if(max<list[j]) {
max = list[j];
indexOfMax = j;
}
list[indexOfMax] = list[i];
list[i] = max;
}
for (int i = 0; i < size; i++)
cout << list[i] << " ";
}
int main() {
const int SIZE = 10;
double numbers[SIZE];
for (int i = 0; i < SIZE; i++){
cout << "Enter a NUmber : ";
cin >> numbers[i];
}
selectionSort(numbers,SIZE);
system("pause");
return 0 ;
}
선택 정렬 수정 - 답 안나옴
//C++로 시작하는 객체지향 프로그래밍 p.328 예제 7.16 - 선택 정렬 수정
/* 최댓값을 구해 그 값과 주어진 목록의 마지막 번째 수를 교환하기. 10개의 double 형 값을 배열로 입력하도록 함.*/
#include <iostream>
using namespace std;
int main() {
const int SIZE = 10;
double numbers[SIZE];
double min;
int indexOfMin;
for (int i = 0; i < SIZE; i++){
cout << "Enter a NUmber : ";
cin >> numbers[i];
}
for (int i = 0; i < SIZE - 1; i++) {
min = numbers[i];
indexOfMin=i;
for (int j = i + 1; j < SIZE; j++){
if (min > numbers[j]){
min = numbers[j];
indexOfMin=j;
}
numbers[indexOfMin] = numbers[i];
numbers[i] = min;
}
for (int k = 0; k < SIZE; k++)
cout << numbers[k] << " " ;
}
system("pause");
return 0 ;
}
/* 최댓값을 구해 그 값과 주어진 목록의 마지막 번째 수를 교환하기. 10개의 double 형 값을 배열로 입력하도록 함.*/
#include <iostream>
using namespace std;
int main() {
const int SIZE = 10;
double numbers[SIZE];
double min;
int indexOfMin;
for (int i = 0; i < SIZE; i++){
cout << "Enter a NUmber : ";
cin >> numbers[i];
}
for (int i = 0; i < SIZE - 1; i++) {
min = numbers[i];
indexOfMin=i;
for (int j = i + 1; j < SIZE; j++){
if (min > numbers[j]){
min = numbers[j];
indexOfMin=j;
}
numbers[indexOfMin] = numbers[i];
numbers[i] = min;
}
for (int k = 0; k < SIZE; k++)
cout << numbers[k] << " " ;
}
system("pause");
return 0 ;
}
Locker Puzzle
//C++로 시작하는 객체지향 프로그래밍 p.328 예제 7.15 - 로커퍼즐(Locker Puzzle)
/* 학교에 ㅔ100개의 로커와 100명의 학생이 있다. 모든 로커는 개학 첫 날에는 닫혀 있다.
학생이 교실로 들어가면서 S1이라는 첫 번째 학생은 모든 로커를 연다.
두 번째 학생 S2는 두 번째 로커 L2부터 시작하여 하나씩 건너뛰면서 로커를 닫는다.
학생 S3은 세 번째 로커 L3부터 시작하여 세 번째 로커마다 상태를 변경한다(열린 것은 닫고, 닫힌 것은 연다.).
학생 S4는 L4부터 시작하여 네 번째 로커마다 로커의 상태를 변경한다.
학생 S5는 L5부터 시작하여 다섯 번째 로커마다 로커의 상태를 변경한다.
이 작업은 학생 S100이 L100 로커를 변경할 때까지 계속된다.
모든 학생이 교실을 통과하고 나간 다음, 어떤 로커가 열려 있을까?
모든 열려 있는 로커 번호를 출력하는 프로그램을 작성하여라. 처음에 모든 로커는 닫혀 있다.*/
#include <iostream>
using namespace std;
const int NUMBER_OF_LOCKER = 100;
bool lockers[NUMBER_OF_LOCKER]; //라커의 상태를 갖는 변수
int main() {
for(int i = 0; i < NUMBER_OF_LOCKER; i++) {
lockers[i] = false; // 모든 라커가 닫혀 있는 상태
}
//학생마다 라커 상태를 변경시킨다.
for (int j = 1; j <= NUMBER_OF_LOCKER; j++){ //j = 학생 번호
//라커 수
for (int i = j - 1; i < NUMBER_OF_LOCKER; i += j){ // i = 라커 번호
lockers[i] = !lockers[i];
}
}
//어떤 라커가 열려있는지 찾는다
for(int i = 0; i < NUMBER_OF_LOCKER; i++) {
if (lockers[i])
cout << "Locker " << (i + 1) << "is open" << endl;
}
system("pause");
return 0 ;
}
/* 학교에 ㅔ100개의 로커와 100명의 학생이 있다. 모든 로커는 개학 첫 날에는 닫혀 있다.
학생이 교실로 들어가면서 S1이라는 첫 번째 학생은 모든 로커를 연다.
두 번째 학생 S2는 두 번째 로커 L2부터 시작하여 하나씩 건너뛰면서 로커를 닫는다.
학생 S3은 세 번째 로커 L3부터 시작하여 세 번째 로커마다 상태를 변경한다(열린 것은 닫고, 닫힌 것은 연다.).
학생 S4는 L4부터 시작하여 네 번째 로커마다 로커의 상태를 변경한다.
학생 S5는 L5부터 시작하여 다섯 번째 로커마다 로커의 상태를 변경한다.
이 작업은 학생 S100이 L100 로커를 변경할 때까지 계속된다.
모든 학생이 교실을 통과하고 나간 다음, 어떤 로커가 열려 있을까?
모든 열려 있는 로커 번호를 출력하는 프로그램을 작성하여라. 처음에 모든 로커는 닫혀 있다.*/
#include <iostream>
using namespace std;
const int NUMBER_OF_LOCKER = 100;
bool lockers[NUMBER_OF_LOCKER]; //라커의 상태를 갖는 변수
int main() {
for(int i = 0; i < NUMBER_OF_LOCKER; i++) {
lockers[i] = false; // 모든 라커가 닫혀 있는 상태
}
//학생마다 라커 상태를 변경시킨다.
for (int j = 1; j <= NUMBER_OF_LOCKER; j++){ //j = 학생 번호
//라커 수
for (int i = j - 1; i < NUMBER_OF_LOCKER; i += j){ // i = 라커 번호
lockers[i] = !lockers[i];
}
}
//어떤 라커가 열려있는지 찾는다
for(int i = 0; i < NUMBER_OF_LOCKER; i++) {
if (lockers[i])
cout << "Locker " << (i + 1) << "is open" << endl;
}
system("pause");
return 0 ;
}
배열의 평균값을 반환하는 두 개의 오버로딩 함수를 작성하기
//C++로 시작하는 객체지향 프로그래밍 p.326 예제 7.8
//Q. (배열 평균) 배열의 평균값을 반환하는 두 개의 오버로딩 함수를 작성하기, 10개의 double형 값을 입력하도록 함.
#include <iostream>
using namespace std;
const int SIZE = 100;
double array[SIZE];
int average(const int array[], int size){
int sum = 0;
for (int i = 0; i < size;i++)
sum += array[i];
return sum/size;
}
double average(const double array[], int size){
double sum = 0;
for (int i = 0; i < size; i++)
sum += array[i];
return sum/size;
}
int main() {
cout << "Enter 10 double values: ";
double list[10];
for (int i = 0;i < 10; i++)
cin >> list[i];
cout << "Average is " << average (list, 10) << endl;
system("pause");
return 0 ;
}
int max(const int array[], int size){
int maxOfNum;
maxOfNum = array[0];
for (int i = 0; i < size; i++) {
if (maxOfNum < array[i])
maxOfNum = array[i];
}
return maxOfNum;
}
하면 max값 역시 구할 수 있음
//Q. (배열 평균) 배열의 평균값을 반환하는 두 개의 오버로딩 함수를 작성하기, 10개의 double형 값을 입력하도록 함.
#include <iostream>
using namespace std;
const int SIZE = 100;
double array[SIZE];
int average(const int array[], int size){
int sum = 0;
for (int i = 0; i < size;i++)
sum += array[i];
return sum/size;
}
double average(const double array[], int size){
double sum = 0;
for (int i = 0; i < size; i++)
sum += array[i];
return sum/size;
}
int main() {
cout << "Enter 10 double values: ";
double list[10];
for (int i = 0;i < 10; i++)
cin >> list[i];
cout << "Average is " << average (list, 10) << endl;
system("pause");
return 0 ;
}
int maxOfNum;
maxOfNum = array[0];
for (int i = 0; i < size; i++) {
if (maxOfNum < array[i])
maxOfNum = array[i];
}
return maxOfNum;
}
하면 max값 역시 구할 수 있음
평균보다 크거나 작은 수의 개수 계산하기
//C++로 시작하는 객체지향 프로그래밍 p.326 예제 7.4 - 점수 분석
#include <iostream>
using namespace std;
int main(){
const int SIZE = 100;
double numbers[SIZE];
int sum = 0, count = 0;
do {
cout << "Enter a number : ";
cin >> numbers[count];
if(numbers[count]>= 0)
sum += numbers[count];
} while (numbers[count++] >= 0);
double average = sum / (count-1);
int numOfAbove = 0, numOfBelow =0;
for(int i = 0; i<count -1; i++){
if (numbers[i]>=average)
numOfAbove++;
else numOfBelow++;
}
cout << "평균은 " << average;
cout <<"평균과 같거나 큰 점수의 수는 : " << numOfAbove;
cout << "평균보다 작은 수의 개수의 수는 : " << numOfBelow;
system("pause");
return 0;
}
#include <iostream>
using namespace std;
int main(){
const int SIZE = 100;
double numbers[SIZE];
int sum = 0, count = 0;
do {
cout << "Enter a number : ";
cin >> numbers[count];
if(numbers[count]>= 0)
sum += numbers[count];
} while (numbers[count++] >= 0);
double average = sum / (count-1);
int numOfAbove = 0, numOfBelow =0;
for(int i = 0; i<count -1; i++){
if (numbers[i]>=average)
numOfAbove++;
else numOfBelow++;
}
cout << "평균은 " << average;
cout <<"평균과 같거나 큰 점수의 수는 : " << numOfAbove;
cout << "평균보다 작은 수의 개수의 수는 : " << numOfBelow;
system("pause");
return 0;
}
7.04.2017
배열 이용하여 회문 문자인지 확인하기
//배열 이용하여 회문 문자인지 확인하기
#include <iostream>
using namespace std;
int main(){
char str[] = "Have a nice day";
int length;
int i = 0;
bool flag;
for (; str[i] != '\0'; i++);
length = i;
cout << "Count of number : " << length << endl;
for (int j = i ; j >=0 ; j--){
if (str[j]==str[length-j])
flag = true;
else{flag = false;
break;
}
}
if(flag)
cout << str << " :회문문자이다" << endl;
else cout << str << " :회문 문자가 아니다" << endl;
system("pause");
return 0;
}
#include <iostream>
using namespace std;
int main(){
char str[] = "Have a nice day";
int length;
int i = 0;
bool flag;
for (; str[i] != '\0'; i++);
length = i;
cout << "Count of number : " << length << endl;
for (int j = i ; j >=0 ; j--){
if (str[j]==str[length-j])
flag = true;
else{flag = false;
break;
}
}
if(flag)
cout << str << " :회문문자이다" << endl;
else cout << str << " :회문 문자가 아니다" << endl;
system("pause");
return 0;
}
배열 이용하여 문자열 역순으로 출력하기
//배열 이용하여 문자열 역순으로 출력하기
#include <iostream>
using namespace std;
int main(){
char str[] = "Have a nice day";
int length;
int i = 0;
for (; str[i] != '\0'; i++);
length = i;
cout << "Number Counter : " << length << endl;
for (int j = i ; j >=0 ; j--)
cout << str[j];
system("pause");
return 0;
}
#include <iostream>
using namespace std;
int main(){
char str[] = "Have a nice day";
int length;
int i = 0;
for (; str[i] != '\0'; i++);
length = i;
cout << "Number Counter : " << length << endl;
for (int j = i ; j >=0 ; j--)
cout << str[j];
system("pause");
return 0;
}
배열로 숫자의 발생 빈도 계산하기
// C++로 시작하는 객체지향 프로그래밍 p.326 예제 7.3
//배열 이용하여 숫자의 발생 빈도 계산하기, 입력 숫자의 개수는 최대 100개이며 0이 입력되면 입력은 끝내는 것으로 함.
#include <iostream>
#include <cmath>
#include <ctime>
using namespace std;
int main(){
int counts[100];
int number; // number read from a file
//Initialize counts
for (int i = 0; i < 100; i++){
counts[i] = 0;
}
cout << "Enter the numbers between 1 and 100 ending with 0: " << endl;
//Read all numbers
cin >> number;
while (number != 0) {
counts[number -1]++;
cin >> number;
}
//Display result
for (int i = 0; i < 100; i++) {
if (counts[i] > 0 )
cout << (i + 1) << "occurs " << counts[i]
<< ((counts[i] == 1) ? " time" : " times") << endl;
}
system("pause");
return 0;
}
//배열 이용하여 숫자의 발생 빈도 계산하기, 입력 숫자의 개수는 최대 100개이며 0이 입력되면 입력은 끝내는 것으로 함.
#include <iostream>
#include <cmath>
#include <ctime>
using namespace std;
int main(){
int counts[100];
int number; // number read from a file
//Initialize counts
for (int i = 0; i < 100; i++){
counts[i] = 0;
}
cout << "Enter the numbers between 1 and 100 ending with 0: " << endl;
//Read all numbers
cin >> number;
while (number != 0) {
counts[number -1]++;
cin >> number;
}
//Display result
for (int i = 0; i < 100; i++) {
if (counts[i] > 0 )
cout << (i + 1) << "occurs " << counts[i]
<< ((counts[i] == 1) ? " time" : " times") << endl;
}
system("pause");
return 0;
}
배열 이용하여 최솟값 요소의 인덱스 찾기
// C++로 시작하는 객체지향 프로그래밍 p.327 예제 7.10
//배열 이용하여 최소값 요소의 인덱스 구하기
#include <iostream>
using namespace std;
const int SIZE = 10;
double num[SIZE];
int min(double list[], int size)
{
int position = 0;
double min = list[0];
for (int i = 1; i<size; i++){
if (min>list[i])
min =list[i];
position = i;
}
return position;
}
int main(){
cout << "Enter 10 numbers : ";
for (int i = 0; i < 10; i++){
cin >> num[i];
}
cout << "The minimum number is " << min(num, SIZE) << endl;
system("pause");
return 0;
}
//배열 이용하여 최소값 요소의 인덱스 구하기
#include <iostream>
using namespace std;
const int SIZE = 10;
double num[SIZE];
int min(double list[], int size)
{
int position = 0;
double min = list[0];
for (int i = 1; i<size; i++){
if (min>list[i])
min =list[i];
position = i;
}
return position;
}
int main(){
cout << "Enter 10 numbers : ";
for (int i = 0; i < 10; i++){
cin >> num[i];
}
cout << "The minimum number is " << min(num, SIZE) << endl;
system("pause");
return 0;
}
배열 이용하여 최솟값 찾기
// C++로 시작하는 객체지향 프로그래밍 p.327 예제 7.9
//배열 이용하여 최소값 구하기
#include <iostream>
using namespace std;
const int SIZE = 10;
double num[SIZE];
int min(double list[], int size)
{
double min = list[0];
for (int i = 1; i<size; i++)
if (min>list[i])
min =list[i];
return min;
}
int main(){
cout << "Enter 10 numbers : ";
for (int i = 0; i < 10; i++){
cin >> num[i];
}
cout << "The minimum number is " << min(num, SIZE) << endl;
system("pause");
return 0;
}
//배열 이용하여 최소값 구하기
#include <iostream>
using namespace std;
const int SIZE = 10;
double num[SIZE];
int min(double list[], int size)
{
double min = list[0];
for (int i = 1; i<size; i++)
if (min>list[i])
min =list[i];
return min;
}
int main(){
cout << "Enter 10 numbers : ";
for (int i = 0; i < 10; i++){
cin >> num[i];
}
cout << "The minimum number is " << min(num, SIZE) << endl;
system("pause");
return 0;
}
숫자 개수 반환
// C++로 시작하는 객체지향 프로그래밍 p.282 예제 6.28
Q. 정수의 숫자 개수를 반환하는 함수를 작성하여라. 예를 들어, getSize(45)는 2를 반환하고, getSize(3434)는 4를 , getSize(4)는 1을 반환한다.
#include <iostream>
using namespace std;
int getSize(int n){
int count = 0;
while(n != 0){
n /= 10;
count++;
}
return count;
}
int main(){
int x;
cout << "Enter an integer :";
cin >> x;
cout << "The number of digits in " << x << " is " << getSize(x) << endl;
system("pause");
return 0;
}
Q. 정수의 숫자 개수를 반환하는 함수를 작성하여라. 예를 들어, getSize(45)는 2를 반환하고, getSize(3434)는 4를 , getSize(4)는 1을 반환한다.
#include <iostream>
using namespace std;
int getSize(int n){
int count = 0;
while(n != 0){
n /= 10;
count++;
}
return count;
}
int main(){
int x;
cout << "Enter an integer :";
cin >> x;
cout << "The number of digits in " << x << " is " << getSize(x) << endl;
system("pause");
return 0;
}
수들의 합
#include <iostream>
using namespace std;
int sum(){
int result;
for (int i = 0;i < 100;i++)
result += i;
return result;
}
int evenSum(){
int result1;
for (int j = 0;j < 100;j++){
if (j%2 != 0)
result1 += j;
}
return result1;
}
int oddSum(){
int result2;
for (int k = 0;k < 100;k++){
if (k % 2 == 0)
result2 += k;
}
return result2;
}
int main(){
cout << "Sum is : " << sum() << endl;
cout << "Even Sum is : " << evenSum() << endl;
cout << "Odd Sum is : " << oddSum() << endl;
system("pause");
return 0;
}
using namespace std;
int sum(){
int result;
for (int i = 0;i < 100;i++)
result += i;
return result;
}
int evenSum(){
int result1;
for (int j = 0;j < 100;j++){
if (j%2 != 0)
result1 += j;
}
return result1;
}
int oddSum(){
int result2;
for (int k = 0;k < 100;k++){
if (k % 2 == 0)
result2 += k;
}
return result2;
}
int main(){
cout << "Sum is : " << sum() << endl;
cout << "Even Sum is : " << evenSum() << endl;
cout << "Odd Sum is : " << oddSum() << endl;
system("pause");
return 0;
}
급수 합계
//C++로 시작하는 객체지향 프로그래밍 p.277 예제 6.12
#include <iostream>
using namespace std;
double m(double n){
double sum = 0;
for (int j = 1; j <=n; j++){
sum += (j/j+1);
}
return sum;
}
int main(){
cout << "i\t\m(i)" << endl;
for (int i = 1; i <=20; i++)
cout << i << "\t\t" << m(i) << endl;
system("pause");
return 0;
}
====================================================
(수정본)
//C++로 시작하는 기초컴퓨터프로그래밍 p.277 예제 6.12
#include <iostream>
using namespace std;
double m(int n){
double sum = 0;
for (int j = 1; j <=n; j++){
sum += j * 1.0/ (j+1);
}
return sum;
}
int main(){
cout << "i\t\m(i)" << endl;
for (int i = 1; i <=20; i++)
cout << i << "\t\t" << m(i) << endl;
system("pause");
return 0;
}
#include <iostream>
using namespace std;
double m(double n){
double sum = 0;
for (int j = 1; j <=n; j++){
sum += (j/j+1);
}
return sum;
}
int main(){
cout << "i\t\m(i)" << endl;
for (int i = 1; i <=20; i++)
cout << i << "\t\t" << m(i) << endl;
system("pause");
return 0;
}
====================================================
(수정본)
//C++로 시작하는 기초컴퓨터프로그래밍 p.277 예제 6.12
#include <iostream>
using namespace std;
double m(int n){
double sum = 0;
for (int j = 1; j <=n; j++){
sum += j * 1.0/ (j+1);
}
return sum;
}
int main(){
cout << "i\t\m(i)" << endl;
for (int i = 1; i <=20; i++)
cout << i << "\t\t" << m(i) << endl;
system("pause");
return 0;
}
피드 구독하기:
글 (Atom)
