Thứ Tư, Tháng Hai 12, 2025
spot_img
HomeStudyC++ exercises with solutions (sample code)

C++ exercises with solutions (sample code)

C++ code There are many things you need to learn and should practice hard. These C++ exercises The answers below will help you use this programming language more easily.

Although the basic code and syntax in C and C++ programming languages ​​are the same. However, as a mid-level programming language, C++ has advantages in programming low-level and higher-level applications.

Highlights of C++ programs

  • C++ is a simple language. Programs are divided into logical units and sections. It also supports rich libraries and many different data types.
  • C++ is not platform independent like programs created on Linux which may not run on windows.
  • With C++ language, you can develop large-scale applications as well as system programming.
  • It comes with a built-in library of data structure algorithms, including third-party libraries for rapid application development.
  • In C++, there is no additional processing overhead like garbage collection, dynamic data entry, etc.
  • Supports pointers so users can directly operate on storage addresses.

Besides Python and Java exercises, TipsMake.com also summarizes for you some basic C++ exercises to practice more in the process of learning C++ programming language.

This list of C++ exercises is divided into 9 parts, each part has 3 to 5 exercises, with increasing levels of difficulty. Initially, you will “warm up” with very basic C++ exercises, such as simulating hand multiplication, printing money amounts, checking a set of 3 numbers to see if they are sides of a triangle, calculating the perimeter, area of ​​that triangle.

Gradually there will be more difficult tasks such as creating and managing student lists, documents, printing or performing other tasks as required by the assignment. Even draw graphs of trigonometric functions.

List of C++ exercises

C++ exercise number 1

Question 1: Simulate hand multiplication

Program to print to the screen simulating the manual multiplication of 2 positive integers with 3 digits entered from the keyboard. For example, with two input numbers 763 and 589, the following must be printed to the screen:

C++ exercise number 1

Sample code:

#include
#include
void
main ()
{
  int a, b;
  char dv, chuc, tram;
  clrscr ();
  printf ("Nhap so bi nhan co 3 chu so a=");
  scanf ("%d", &a);
  printf ("Nhap so nhan co 3 chu so b=");
  scanf ("%d", &b);
  dv = b % 10;
  chuc = b % 100 / 10;
  tram = b / 100;
  printf ("\nMo phong phep nhan tay\n\n");
  printf ("%20d\n", a);
  printf ("%15c%5d\n", 'x', b);
  printf ("%20s\n", "-------");
  printf ("%20d\n", a * dv);
  printf ("%19d\n", a * chuc);
  printf ("%18d\n", a * tram);
  printf ("%20s\n", "-------");
  printf ("%20ld\n", long (a) * b);
  getch ();

}

Question 2: Enter the amount, print the number of bills and denomination

A person needs to withdraw an amount T from the bank and wants the least total number of bills. Indicates that there are denominations of 100, 20, 5 and 1. Enter from the keyboard the amount of money T and print out the number of bills of each denomination and the total number of bills received.

Sample code:

#include 
#include 
void
main ()
{
  int t, t100, t20, t5;
  clrscr ();
  printf ("Nhap so tien t=");
  scanf ("%d", &t);
  t100 = t / 100;
  t -= 100 * t100;
  t20 = t / 20;
  t -= 20 * t20;
  t5 = t / 5;
  t -= 5 * t5;
  printf ("So to cac loai menh gia la :\n");
  printf ("Loai 100 : %d to\n", t100);
  printf ("Loai 20 : %d to\n", t20);
  printf ("Loai 5 : %d to\n", t5);
  printf ("Loai 1 : %d to\n", t);
  printf ("Tong so to cac loai la : %d\n", t + t5 + t20 + t100);
  getch ();
}

Question 3: Change the number to Roman numerals

Program to enter a positive integer less than 1000 and convert it to the corresponding Roman number, printing the result to the screen.

Sample code:

#include 
#include 

void
main()
{
	int n, dv, ch, tr;
	clrscr();
	cout > n;
	cout 

Question 4: Print how to read numbers

Print to the screen how to read a positive integer less than 1000000. For example, the number 726503 reads: seventy-two thousand, six thousand, five hundred and three.

Sample code:

#include 
#include 

void main()
{
	char doc[9][5] = { "mot", "hai", "ba", "bon", "nam", "sau", "bay", "tam", "chin" };
	int van, ngan, tram, chuc, donvi, chv, dv;
	long so;
	clrscr();

	cout > so;
	cout  1)
			cout 

Question 5: Solve quadratic equations

Program to solve the equation ax2 + bx + c = 0, real coefficients a, b, c are entered from the keyboard.

Sample code:

#include 
#include 
#include 

void main()
{
	float a, b, c, d;
	clrscr();
	printf("Nhap cac he so a, b, c : ");
	scanf("%f%f%f", &a, &b, &c);
	if (a)
	{
		d = b *b - 4 *a * c;
		if (d  0)
		{
			printf("Hai nghiem phan biet :\n");
			printf("x1=%4.2f", 0.5 *(-b - sqrt(d)) / a);
			printf(" x2=%4.2f", 0.5 *(-b + sqrt(d)) / a);
		}
	}
	else if (b) printf("Mot nghiem x=%4.2f", -c / b);
	else if (c) printf("Vo nghiem !");
	else printf("Vo so nghiem !");
	getch();
}

C++ exercise number 2

Question 1: Check if the 3 numbers are triangle sides, if so, what type of triangle, calculate the perimeter and area

Enter 3 real numbers a, b, c and check if those 3 numbers are 3 sides of a triangle? If it is a 3-sided triangle, indicate which of the following types of triangles it is: equilateral, isosceles, right, isosceles, regular and calculate the perimeter and area of ​​that triangle. Print the results to the screen.

Sample code:

#include 
#include 
#include 

void main()

{
	float a, b, c, p, s;
	int deu, vuong, can;
	clrscr();
	printf("Nhap cac so thuc a, b, c : ");
	scanf("%f%f%f", &a, &b, &c);

	if (a + b > c && a + c > b && b + c > a)
	{
		printf("La ba canh mot tam giac ");
		deu = (a == b) && (b == c);
		vuong = (a *a + b *b == c *c) || (a *a + c *c == b *b) || (b *b + c *c == a *a);
		can = (a == b) || (a == c) || (b == c);

		if (deu) printf(" deu\n");
		else if (vuong && can) printf(" vuong can\n");
		else if (vuong) printf(" vuong\n");
		else if (can) printf(" can\n");
		else printf(" thuong\n");
		p = (a + b + c) / 2;
		printf("Chu vi = %4.2f, Dien tich = %4.2f", 2 *p, sqrt(p *(p - a) *(p - b) *(p - c)));
	}
	else printf("Khong phai la ba canh mot tam giac\n");
	getch();
}

Question 2: Calculate the number of years you need to save

A person needs to have an amount of money T, accumulated by saving an initial amount of money S with an annual interest rate of P% according to the progressive method (each year's interest is added to the principal). . Please enter the real numbers T, S, P and determine the number of years to save.

Sample code:

#include 
#include 

void main()

{
	float s, t, p;
	int n;
	clrscr();

	printf("Nhap so tien ban dau : ");
	scanf("%f", &s);
	printf("Nhap so tien can co : ");
	scanf("%f", &t);
	printf("Nhap lai suat %% nam : ");
	scanf("%f", &p);

	for (p = 0.01 *p, n = 0; s 

Question 3: Print the calculated PI number with the given error

Program to calculate PI number with given error eps entered from the keyboard. Knowing that PI is calculated according to the formula: PI = 4 – 4/3 + 4/5 – 4/7 +… calculate the sum of terms with a value not less than eps. Print out the calculated PI number and the Turbo C++ PI number with 10 decimal places for comparison.

Sample code:

#include 
#include 
#include ;//chua hang so pi la M_PI

void main()
{
	float pi, t, n, eps, dau;
	clrscr();
	printf("Nhap sai so eps=");
	scanf("%f", &eps);

	pi = 0;
	t = 4;
	n = dau = 1;

	do
	{
		pi += dau * t;
		n = n + 2;
		dau = -dau;
		t = 4 / n;
	} while (t >= eps);
	printf("\nSo PI tinh duoc voi sai so %12.10f, PI=%12.10f\n", eps, pi);
	printf("\nSo PI cua Turbo C++, PI=%12.10f\n", M_PI);
	getch();
}

Question 4: Find and print perfect numbers

Find and print to the screen all perfect numbers that do not exceed the given number n entered from the keyboard. A perfect number is a number that is equal to the sum of its divisors, regardless of the divisor being the number itself. For example, 6 is a perfect number because 6=1+2+3.

Xem thêm  How to create poster effects for photos in Photoshop

Sample code:

#include 
#include 

void main()
{
	int n, i, j, s, ts;
	clrscr();
	printf("Nhap n=");
	scanf("%d", &n);
	printf("Cac so hoan hao khong vuot qua %d la :", n);

	for (ts = 0, i = 2; i 

Question 5: Find and print prime numbers less than n

Find and print to the screen all prime numbers not exceeding the given number n entered from the keyboard. A prime number is a number that has only divisors 1 and the number itself.

Sample code:

#include 
#include 

void main()
{
	int n, i, j, d;
	clrscr();
	printf("Nhap gia tri N : ");
	scanf("%d", &n);
	printf("Cac so nguyen to khong vuot qua %d la :\n", n);

	for (d = 0, i = 2; i 

C++ exercise number 3

Question 1: Check the perfect square number

Write a function to check whether a number is a perfect square or not (a perfect square is a number equal to the square of a certain integer); a function that checks whether a number is a Pythagorean number or not (Pythagorean number is a perfect square number and equal to the sum of 2 other perfect square numbers). In the main function, enter a positive integer and use the above functions to check if it is a perfect square number? Pythagorean numbers?

Sample code:

#include 
#include 
#include 

int socp(int);
int soptg(int);

void main()

{
	clrscr();
	int n;
	printf("Nhap so nguyen duong n=");
	scanf("%d", &n);
	if (socp(n)) printf("\n%d la so chinh phuong", n);
	else printf("\n%d khong phai so chinh phuong", n);
	if (soptg(n)) printf("\n%d la so Pitago", n);
	else printf("\n%d khong phai so Pitago", n);
	getch();
}

int socp(int n)
{
	int t = sqrt(n);
	if (n == t *t) return 1;
	else return 0;
}

int soptg(int n)
{
	int i;
	if (!socp(n)) return 0;
	else
	{
		for (i = 1; i 

Question 2: Solve first-order inequalities

Program to solve the inequality ax+b>0 as required: Write a function to input coefficients a, b; a function that solves inequalities. The main function uses written functions and can be run multiple times to solve different inequalities.

Sample code:

#include 
#include 
#include 

void nhap(float &, float &);
void giaibpt(float, float);
void main()

{
	float a, b;
	char c;
	do {
		clrscr();
		nhap(a, b);
		giaibpt(a, b);
		fflush(stdin);
		cout > c;
	} while ((c == 'c') || (c == 'C'));
}

void nhap(float &a, float &b)
{
	cout > a >> b;
}

void giaibpt(float a, float b)
{
	if (a > 0) cout "  0) cout 

Question 3: Write a recursive function to find the greatest common divisor

Write a recursive function to find the greatest common divisor of 2 natural numbers; a function to find the least common multiple of 2 natural numbers. The main function uses written functions and can be run multiple times to find the greatest common divisor and least common multiple of different pairs of positive integers. Requires checking that the input data must be positive integers.

Sample code:

#include 
#include 
#include 

int usc(int, int);
int bsc(int, int);
void main()

{
	int a, b, d, p;
	char c;
	do {
		clrscr();
		do { 	cout > a >> b;
		} while ((a > c;
	} while ((c == 'c') || (c == 'C'));
}

int usc(int a, int b)
{
	if (a *b == 0) return a + b;
	else if (a > b) return usc(a - b, b);
	else return usc(a, b - a);
}

int bsc(int a, int b)
{
	return a *b / usc(a, b);
}

Question 4: Calculate the factorial of the positive integer n

Write a recursive function that calculates the factorial of a positive integer n. The main function uses this function and can be run multiple times to calculate many different numbers n entered from the keyboard. Requires checking that the input data must be a positive integer. Formula to calculate the factorial of n: n!=1.3…n if n is odd and n!=2.4…n if n is even.

Sample code:

#include 
#include 
#include 

long gtc(long);
void main()
{
	long n;
	char c;
	do {
		clrscr();
		do { 	cout > n;
		} while (n > c;
	} while ((c == 'c') || (c == 'C'));
}

long gtc(long n)
{
	if ((n == 0) || (n == 1)) return 1;
	else return n* gtc(n - 2);
}

Question 5: Write a recursive function to solve the Hanoi Tower problem

Write a recursive function to solve the Hanoi tower problem: Need to move n tower floors from location A to location B using location C as an intermediary. Requirements: Only move 1 floor at a time, only use locations A, B, C to place tower floors, do not place large floors on top of small floors. The main function uses this function and can be run multiple times to calculate many different numbers n entered from the keyboard.

Sample code:

#include 
#include 
#include 

int d;
void chuyen(int, char, char, char);
void main()
{
	int n;
	char c;
	do {
		clrscr();
		d = 0;
		do { 	cout > n;
		} while ((n  9));
		chuyen(n, 'A', 'B', 'C');
		cout > c;
	} while ((c == 'c') || (c == 'C'));
}

void chuyen(int n, char a, char b, char c)
{
	if (n == 1) cout 

C++ exercise number 4

Question 1: Print array elements as required

Enter an array of n real numbers, find and print the smallest and largest element, calculate and print the average of the elements in the array. Print out the elements that are smaller and larger than the average.

Sample code:

#include 
#include 
#define max 100

void main()
{
	int i, j, n;
	float a[max], tbc, pmax, pmin;
	clrscr();
	cout > n;
	cout > a[i];
	}

	pmax = pmin = tbc = a[0];
	for (i = 1; i  a[i]) pmin = a[i];
	}

	tbc = tbc / n;
	cout  TBC:\n";
	for (i = 0; i  tbc) cout 

Question 2: Enter, sort, and print arrays

Write an array input function, an array sorting function, and a function that prints array elements to the screen. The main function uses these functions to input an n-element array, printing the array before and after sorting.

Sample code:

#include 
#include 
#define max 100

void nhap(int[], int);
void sapxep(int[], int);
void xuat(int[], int);

void main()
{
	int a[max], n;
	clrscr();
	cout > n;
	nhap(a, n);
	cout > a[i];
	}
}

void xuat(int a[], int n)
{
	int i, j;
	for (i = 0; i  a[j])
			{
				tg = a[i];
				a[i] = a[j];
				a[j] = tg;
			}
}

Question 3: Enter, print array, count segments according to criteria

Write a function to input an array, a function to print the elements of the array to the screen, a function to count the number of increments, a function to find the longest increment in the array. The main function uses these functions to enter an n-element array, print the array, print the number of increments and the longest increment in the array.

Sample code:

#include 
#include 
#define max 100

void nhap(int[], int);
void xuat(int[], int);
int sodoantang(int[], int);
void timdoantangmax(int[], int, int &, int &);

void main()
{
	int a[max], i, d, c, n;
	clrscr();
	cout > n;
	nhap(a, n);
	cout > a[i];
	}
}

void xuat(int a[], int n)
{
	int i;
	for (i = 0; i  0) d = 1;
	else d = 0;
	for (i = 0; i  c - d)
		{
			d = t;
			c = p;
		}

		if (p 

Question 4: Enter, print, and calculate the product of 2 matrices

Write a function that imports the elements of a 2-dimensional matrix, a function that prints the matrix in rows and columns, and a function that multiplies 2 matrices. The main function uses these functions to enter matrix A of size MxN and matrix B of size NxP. Print out matrices A, B and matrix C as the product of matrices A and B.

Sample code:

#include 
#include 

int a[10][10], b[10][10], c[10][10];
void nhap(char, int, int);
void xuat(char, int, int);
void nhan(int, int, int);

void main()
{
	int m, n, p;
	clrscr();
	cout > m;
	cout > n;
	cout > p;
	cout > t;
			switch (k)
			{
				case 'a':
					a[i][j] = t;
					break;
				case 'b':
					b[i][j] = t;
			}
		}
	}
}

void xuat(char k, int p, int q)
{
	int i, j;
	for (i = 0; i 

Question 5: Enter and print the square matrix and calculate the determinant

Write a function to enter the elements of an n-level square matrix, a function to print the matrix in a row-column structure, and a function to calculate the determinant of an n-level matrix. The main function uses these functions to enter an n-level square matrix, print the matrix, calculate and print the determinant of that matrix.

Xem thêm  GROUP BY clause in SQL Server

Sample code:

#include 
#include 

float a[10][10];
int n;
void nhap();
void xuat();
void doicot(int, int);
void truhang(int, int);
float dinhthuc();

void main()
{
	clrscr();
	cout > n;
	cout > t;
			a[i][j] = t;
		}
	}
}

void xuat()
{
	int i, j;
	for (i = 0; i 

C++ exercise number 5

Question 1: Check the symmetry of a string

Write a function to check the symmetry of a string of characters. In the main function, enter a string of characters from the keyboard and indicate whether the string is symmetric. Ask the program to run multiple times.

Sample code:

#include 
#include 
#include 

int doixung(char[]);

void main()
{
	char c, s[80];
	do {
		clrscr();
		printf("\nNhap xau ki tu : \n");
		fflush(stdin);
		gets(s);
		if (doixung(s)) printf("Xau doi xung !");
		else printf("Xau khong doi xung !");
		printf("\nTiep tuc ? (c/k):");
		fflush(stdin);
		c = getchar();
	} while ((c == 'c') || (c == 'C'));
}

int doixung(char s[])
{
	int i, n, d;
	n = strlen(s);
	d = 1;
	if (n > 0)
		for (i = 0;
			(i 

Question 2: Statistics on the number of times a character appears in the string

Write a function to calculate the frequency of each character in a string of characters. The main function inputs a string of characters from the keyboard and prints the frequency of each character. Ask the program to run multiple times.

Sample code:

#include 
#include 
#include 

int ts[128];
void thongke(char[]);

void main()
{
	char c, s[80];
	int i;
	do {
		clrscr();
		printf("\nNhap xau ki tu : \n");
		fflush(stdin);
		gets(s);
		thongke(s);
		printf("Tan so cac ky tu trong xau la :\n");
		for (i = 0; i 

Question 3: Standardize the character string

Write a function to normalize a string of characters: convert a string of characters into a string so that there are no two consecutive spaces in the string, a function to find the number of words in a string of characters, a function to find the longest word in a string of characters . The main function uses these functions to enter a string of characters from the keyboard, print the string before and after normalization, the number of words in the string and the longest word in that string.

Sample code:

#include 
#include 
#include 

void chuanhoa(char[]);
int sotu(char[]);
char *timtumax(char[]);

void main()
{
	char s[80];
	clrscr();
	printf("\nNhap xau ki tu : \n");
	gets(s);
	printf("\nXau ban dau:\n");
	puts(s);
	chuanhoa(s);
	printf("\nXau da chuan hoa:\n");
	puts(s);
	printf("\nSo tu cua xau : %d\n", sotu(s));
	printf("\nTu dai nhat trong xau : %s", timtumax(s));
}

void chuanhoa(char s[])
{
	int i, k, n;
	do {
		n = strlen(s);
		for (i = 0;
			(i  0) && (s[0] - 32)) d = 1;
	else d = 0;
	for (i = 0; i  c - d)
		{
			d = t;
			c = p;
		}

		t = p + 1;
	} while (t 

Question 4: Enter the character string array and sort it in ascending order

Write a function to input a character string array, a function to sort the array in ascending order. The main function uses these functions to enter a list of student names and print out the list in alphabetical order by name.

Sample code:

#include 
#include 
#include 

char ds[100][10];
void nhap(int);
void sapxep(int);
void inds(int n);

void main()
{
	int n;
	clrscr();
	printf("\nNhap so luong sinh vien n=");
	scanf("%d", &n);
	nhap(n);
	printf("\nDanh sach theo thu tu nhap:\n");
	inds(n);
	sapxep(n);
	printf("\nDanh sach theo van ABC:\n");
	inds(n);
	getch();
}

void nhap(int n)
{
	int i;
	printf("Nhap ten %d sinh vien:\n", n);
	for (i = 0; i  0)
			{
				strcpy(tg, ds[i]);
				strcpy(ds[i], ds[j]);
				strcpy(ds[j], tg);
			}
}

C++ exercise number 6

Question 1: Manage candidates' scores by array

Use a structured array to store the candidate's full name, registration number, test scores in math, physics, chemistry and total score. Programming necessary data entry, and benchmarking. Print out the list of candidates with scores for subjects and total scores; List of successful candidates (total score>=standard score).

Sample code:

#include 
#include 
#include 
#define max 50

void main()
{
	struct
	{
		char ht[30];
		char sbd[10];
		float dt, dl, dh, td;
	}

	a[max];
	float dc;
	int i, j, n;
	clrscr();
	cout > n;
	cout > a[i].dt;
		cout > a[i].dl;
		cout > a[i].dh;
		a[i].td = a[i].dt + a[i].dl + a[i].dh;
	}

	cout > dc;
	cout = dc)
		{
			j++;
			printf("%-4d%-20s%-10s%-10.1f%-10.1f%-10.1f%-10.1f\n",
				j, a[i].ht, a[i].sbd, a[i].dt, a[i].dl, a[i].dh, a[i].td);
		}

	cout 

Question 2: Manage documents, print lists as required

Create a linked list containing information technology documents, each document includes: code, document name, page number, year of publication. Please print out a list of all documents and a list of documents published since 1998. Please print in columns, with column numbers included.

Sample code:

#include 
#include 
#include 
#include 

struct tailieu
{
	char ma[10];
	char ten[30];
	int sotrang, namxb;
	tailieu * next;
};

tailieu* nhap();
void xoa(tailieu*);

void main()
	{
		tailieu *p, *q, *head;
		int i;
		clrscr();
		head = nhap();;
		printf("\nGo Enter Tiep tuc ...");
		getch();
		clrscr();
		printf("\nDanh sach tai lieu :\n\n");
		printf("%-4s%-10s%-30s%-10s%-10s\n", "Stt", "Ma", "Ten tai lieu", "So tr", "Nam XB");
		p = head;
		i = 0;
		while (p != NULL)
		{
			printf("%-4d%-10s%-30s%-10d%-10d\n", ++i, p->ma, p->ten, p->sotrang, p->namxb);
			p = p->next;
		}

		printf("\nGo Enter Tiep tuc ...");
		getch();
		clrscr();
		printf("\nDanh sach tai lieu xuat ban tu nam 1998 :\n\n");
		printf("%-4s%-10s%-30s%-10s%-10s\n", "Stt", "Ma", "Ten tai lieu", "So tr", "Nam XB");
		p = head;
		i = 0;
		while (p != NULL)
		{
			if (p->namxb >= 1998) printf("%-4d%-10s%-30s%-10d%-10d\n", #ERROR!
				p = p->next;
			}
		}

		void xoa(tailieu *p)
		{
			tailieu * q;
			while (p != NULL)
			{
				q = p;
				p = p->next;
				delete q;
			}
		}

		tailieu* nhap()
		{
			tailieu *p, *q, *h;
			char s[10];
			h = NULL;
			printf("Nhap du lieu cua cac tai lieu, ket thuc go Enter :\n");
			printf("Tai lieu thu 1 :\n");
			printf("Ma so : ");
			gets(s);
			if (strcmp(s, ""))
			{
				p = new tailieu;
				strcpy(p->ma, s);
				printf("Ten tai lieu : ");
				gets(p->ten);
				printf("So trang : ");
				cin >> p->sotrang;
				printf("Nam xuat ban : ");
				cin >> p->namxb;
				p->next = NULL;
				h = p;
				q = p;
				printf("Tai lieu tiep theo :\n");
				printf("Ma so : ");
				gets(s);
				while (strcmp(s, ""))
				{
					p = new tailieu;
					strcpy(p->ma, s);
					printf("Ten tai lieu : ");
					gets(p->ten);
					printf("So trang : ");
					cin >> p->sotrang;
					printf("Nam xuat ban : ");
					cin >> p->namxb;
					p->next = NULL;
					q->next = p;
					q = p;
					printf("Tai lieu tiep theo :\n");
					printf("Ma so : ");
					gets(s);
				}
			}

			return h;
		}

Question 3: Manage electricity payments

Use a structured array to store the householder's name, last month's electricity number, this month's electricity number, and the amount to be paid. Program to enter necessary data, electricity bill based on electricity number in the month s=electricity number last month – electricity number this month. Unit price: The first 100 numbers are priced at 550, the next 50 numbers are priced at 900, the next 50 numbers are priced at 1210, the next 50 numbers are priced at 1340, the next 50 numbers are priced at 1500, numbers > 300 are priced at 2000. Print out electricity payment statistics table of all subscribers; List of households using each type:

Sample code:

#include 
#include 
#include 
#define max 100

struct thuebao
{
	char ht[30];
	float sdtt, sdtn, sotien;
};

thuebao nhap();
int thongke(thuebao[], int, float, float);
void xuat(thuebao[], int);

void main()
{
	thuebao a[max];
	float dc;
	int i, j, n, d;
	clrscr();
	cout > n;
	cout > ah.sdtt;
		cout > ah.sdtn;
		sd = ah.sdtn - ah.sdtt;
	} while (sd = cd) && (sd 

C++ exercise number 7

Question 1: Create a number file, count numbers, largest number, smallest number

Create a file containing integers read from the keyboard. Then read from the created file to make statistics and print the results: number of numbers in the file, number of positive numbers, largest number, smallest number.

Sample code:

#include 
#include 

void main()
{
	int i, x, ts, sd, max, min;
	char t;
	FILE * fp;
	clrscr();
	fp = fopen("tepsn.dat", "w");
	printf("Nhap tung so nguyen :\n");
	i = 1;
	do {
		printf("So thu %d : ", i++);
		scanf("%d", &x);
		fprintf(fp, "%d ", x);
		printf("Tiep tuc nhap ? (c/k) : ");
		fflush(stdin);
		t = getchar();
	} while ((t == 'c') || (t == 'C'));
	fclose(fp);
	fp = fopen("tepsn.dat", "r");
	ts = sd = 0;
	if (!feof(fp))
	{
		fscanf(fp, "%d", &x);
		max = min = x;
		ts++;
		if (x > 0) sd++;
		while (!feof(fp))
		{
			fscanf(fp, "%d", &x);
			if (max  x) min = x;
			if (x > 0) sd++;
			ts++;
		}
	}

	if (x > 0) sd--;
	ts--;	//So nguyen sau cung duoc doc 2 lan
	fclose(fp);
	printf("Tat ca co %d so nguyen\n", ts);
	printf("Trong do so luong so duong = %d\n", sd);
	printf("Max=%d, Min=%d", max, min);
	getch();
}

Question 2: Create a file of student names, sort and print

Create a text file containing a list of student names entered from the keyboard. Then read from the created file into an array; Sort the array in ascending order and print out the sorted list of students with the column number.

Xem thêm  UPDATE command in SQL

Sample code:

#include 
#include 
#include 

void main()
{
	char i, s[30];
	FILE * f;
	clrscr();
	f = fopen("DSSV.TXT", "w");
	i = 1;
	printf("Nhap ho ten cua tung hoc sinh, ket thuc go Enter\n");
	do {
		printf("Ho ten hoc sinh thu %d : ", i++);
		gets(s);
		if (strlen(s) > 0)
		{
			strcat(s, "\n");
			fputs(s, f);
		}
	} while (strlen(s) > 0);
	fclose(f);
	clrscr();
	f = fopen("DSSV.TXT", "r");
	printf("Danh sach hoc sinh doc tu tep :\n\n");
	i = 1;
	while (fgets(s, 30, f))
	{
		printf("%d. ", i++);
		puts(s);
	}

	fclose(f);
	getch();
}

Question 3: Create a file list of student records as required

Create a file containing a list of student records including codes, full names, and average scores. Then read from the created file into an array; Sort the array in descending order by average score and print a list of students by column, with an ordinal index column included.

Sample code:

#include 
#include 

struct sv
{
	char maso[10];
	char ht[25];
	float dtb;
};

void main()
{
	int i, n;
	float d;
	sv bg;
	FILE * f;
	clrscr();
	f = fopen("HosoSV.DAT", "w+b");
	printf("Nhap so sv n=");
	scanf("%d", &n);
	fwrite(&n, sizeof(int), 1, f);
	for (i = 1; i 

C++ exercise number 8

Question 1: Draw a red flag with a yellow star in the center of the screen.

Sample code:

#include 
#include 
#include 
#include 
#include 

void main()
{
	int gdrv = DETECT, gmode, errorcode, mx, my;
	initgraph(&gdrv, &gmode, "..\\BGI");
	errorcode = graphresult();
	if (errorcode != grOk)
	{
		printf("Graphics error : %s\n", grapherrormsg(errorcode));
		printf("Press any key to halt ...");
		getch();
		exit(1);
	}

	mx = getmaxx() / 2;
	my = getmaxy() / 2;
	setbkcolor(BLUE);
	setcolor(RED);
	setfillstyle(1, RED);
	bar(mx - 150, my - 100, mx + 150, my + 100);
	setcolor(YELLOW);
	setfillstyle(1, YELLOW);
	moveto(mx, my - 70);
	lineto(mx + 50, my + 60);
	lineto(mx - 70, my - 25);
	lineto(mx + 70, my - 25);
	lineto(mx - 50, my + 60);
	lineto(mx, my - 70);
	floodfill(mx, my, YELLOW);
	floodfill(mx, my - 30, YELLOW);
	floodfill(mx + 20, my + 30, YELLOW);
	floodfill(mx - 20, my + 30, YELLOW);
	floodfill(mx - 50, my - 20, YELLOW);
	floodfill(mx + 50, my - 20, YELLOW);
	getch();
	closegraph();
}

Question 2: Draw a simulation of an antenna broadcast tower.

Sample code:

#include //ham printf
#include 
#include //ham getch(), kbhit()
#include //ham random, exit
#include //ham delay

const CHAM = 10;
int mx, my;
void khoitao();
void vecot();

void main()
{
	int dx = 10;
	khoitao();
	vecot();
	while (!kbhit())
	{
		setcolor(random(16));
		circle(mx, my, dx);
		delay(CHAM);
		dx = dx + 10;
		if (dx > 2 *my)
		{
			delay(20 *CHAM);
			dx = 10;
			vecot();
		}
	}

	closegraph();
}

void vecot()
{
	setbkcolor(BLUE);
	cleardevice();
	setcolor(RED);
	setfillstyle(6, LIGHTRED);
	line(mx, my, mx - 20, my + 15);
	line(mx, my, mx + 20, my + 15);
	line(mx - 20, my + 15, mx - 40, 2 *my);
	line(mx + 20, my + 15, mx + 40, 2 *my);
	line(mx - 40, 2 *my, mx + 40, 2 *my);
	floodfill(mx, my + 20, RED);
}

void khoitao()
{
	int gdrv = DETECT, gmode, errorcode;
	initgraph(&gdrv, &gmode, "..\\BGI");
	errorcode = graphresult();
	if (errorcode != grOk)
	{
		printf("Graphics error : %s\n", grapherrormsg(errorcode));
		printf("Press any key to halt ...");
		getch();
		exit(1);
	}

	mx = getmaxx() / 2;
	my = getmaxy() / 2;
}

Question 3: Draw the starry sky on the screen.

Sample code:

#include 
#include 
#include 
#include 
#include 
#include 

struct point
{
	int x, y, s, c, h;
};

void vediem(point, int);
void main()
{
	point p[100];
	int gdrv = DETECT, gmode, errorcode, mx, my, i;
	initgraph(&gdrv, &gmode, "..\\BGI");
	errorcode = graphresult();
	if (errorcode != grOk)
	{
		printf("Graphics error : %s\n", grapherrormsg(errorcode));
		printf("Press any key to halt ...");
		getch();
		exit(1);
	}

	mx = getmaxx();
	my = getmaxy();
	randomize();
	for (i = 0; i = 3) p[i].h = 0;
			}
			else
			{
				p[i].s--;
				if (p[i].s 

Question 4: Draw the graph of the function y=sinx.

Sample code:

#include 
#include 
#include 
#include 
#include 

void main()
{
	int gdrv = DETECT, gmode, errorcode, mx, my;
	float x, y, k, kx;
	initgraph(&gdrv, &gmode, "..\\BGI");
	errorcode = graphresult();
	if (errorcode != grOk)
	{
		printf("Graphics error : %s\n", grapherrormsg(errorcode));
		printf("Press any key to halt ...");
		getch();
		exit(1);
	}

	mx = getmaxx() / 2;
	my = getmaxy() / 2;
	x = 0;
	kx = 2 *M_PI / mx;
	setbkcolor(BLUE);
	setcolor(WHITE);
	line(0, my, 2 *mx, my);
	line(mx, 0, mx, 2 *my);
	moveto(mx, 0);
	linerel(7, 7);
	moveto(mx, 0);
	linerel(-7, 7);
	moveto(2 *mx, my);
	linerel(-7, -7);
	moveto(2 *mx, my);
	linerel(-7, 7);
	setcolor(RED);
	k = 100;
	while (x 

Question 5: Draw a moving ball in a rectangular frame.

Sample code:

#include 
#include 
#include 
#include 
#include 
#define R 7
#define MAU YELLOW
#define MAUNEN BLACK
#define CHAM 6

void bong();
void main()
{
	int gdrv = DETECT, gmode, errorcode;
	initgraph(&gdrv, &gmode, "..//BGI");
	errorcode = graphresult();
	if (errorcode != grOk)
	{
		printf("Graphics error : %s\n", grapherrormsg(errorcode));
		printf("Press any key to halt ...");
		getch();
		exit(1);
	}

	bong();
	closegraph();
}

void bong()
{
	int mx, my, dx, dy, x, y, d = 0;
	randomize();
	do {
		dx = random(3) - 1;
	} while (!dx);
	do {
		dy = random(3) - 1;
	} while (!dy);
	mx = getmaxx();
	my = getmaxy();
	x = mx / 2;
	y = my / 2;
	rectangle(0, 0, mx, my);
	do {
		setcolor(MAU);
		setfillstyle(1, MAU);
		fillellipse(x, y, R, R);
		delay(CHAM);
		setcolor(MAUNEN);
		setfillstyle(1, MAUNEN);
		fillellipse(x, y, R, R);
		x += dx;
		y += dy;
		if (x  mx - R - 1)
		{
			dx = -dx;
			x += 2 * dx;
			d = 1;
		}

		if (y  my - R - 1)
		{
			dy = -dy;
			y += 2 * dy;
			d = 1;
		}
	} while (!kbhit());
}

C++ exercise number 9

Question 1: Create vector layer as required

Create a vector class with size properties and an array containing the vector's elements; Methods: import, export, add 2 vectors. The main function uses the vector class to perform input, output and sum of 2 vectors.

Sample code:

#include 
#include 

class vecto
{
	int n;
	int *ptr;
	public:
		vecto(int n);
	~vecto();
	void inputvt();
	void sumvt(int *, int *);
	void displayvt(int*);
	void print();
};

vecto::vecto(int n1)
{
	int i;
	n = n1;
	ptr = new int[n1];
	for (i = 0; i > ptr[i];
	}
}

void vecto::displayvt(int *p)
{
	int i;
	for (i = 0; i > n;
	vecto a(n), b(n), c(n);
	cout 

Question 2: Create a fraction class as required

Create a fraction class with numerator and denominator properties; Methods: enter, show, simplify, reduce denominator to 2 fractions, add 2 fractions. The main function uses the class and implements these methods.

Sample code:

#include 
#include 

int usc(int a, int b)
{
	int r = a % b;
	while (r)
	{
		a = b;
		b = r;
		r = a % b;
	}

	return b;
}

class phanso
{
	public:
		int tuso, mauso;
	void nhap()
	{
		cout > tuso;
		cout > mauso;
	}

	void hienphanso()
	{
		cout 

Question 3: Create a product class as required

Create a product class with attributes such as product code, product name, unit of measure, unit price, quantity, amount; Methods: input, calculate into money. Create a new goods class that inherits the goods class, adding the following attributes: shipping unit price and shipping cost calculated by shipping unit price multiplied by quantity; Methods: calculating shipping costs, importing and calculating into money. The main function uses these classes and implements the methods.

Sample code:

#include 
#include 

class hanghoa
{
	public:
		char mahang[2];
	char tenhang[20];
	char donvitinh[10];
	float dongia, soluong, thanhtien;
	void nhap()
	{
		cout > mahang;
		cout > tenhang;
		cout > donvitinh;
		cout > dongia;
		cout > soluong;
	}

	void tinhthanhtien()
	{
		thanhtien = dongia * soluong;
	}
};

class hanghoamoi: public hanghoa
{
	public: float dongiavanchuyen, congvanchuyen;
	void nhap()
	{
		hanghoa::nhap();
		cout > dongiavanchuyen;
	}

	void tinhcongvanchuyen()
	{
		congvanchuyen = soluong * dongiavanchuyen;
	}

	void tinhthanhtien()
	{
		thanhtien = dongia *soluong + congvanchuyen;
	}
};

void main()
{
	hanghoamoi x;
	clrscr();
	x.nhap();
	x.tinhcongvanchuyen();
	x.tinhthanhtien();
	cout 

Question 4: Write a function to import, export, and sort the array

Use templates to write input, output, and array sorting functions. The main function uses these template functions to input an n-element array, printing out the array before and after sorting for two cases: integer array and real number array.

Sample code:

#include 
#include 

template 
	void nhap(T a[], int n)
	{
		int i;
		cout > a[i];
		}
	}

template 
	void xuat(T a[], int n)
	{
		int i, j;
		for (i = 0; i 
	void sapxep(T a[], int n)
	{
		int i, j;
		T tg;
		for (i = 0; i  a[j])
				{
					tg = a[i];
					a[i] = a[j];
					a[j] = tg;
				}
	}

void main()
{
	int a[100], n;
	float b[100];
	clrscr();
	cout > n;
	cout 

Basic C++ exercises on functions and recursion

Question 1: Write a C++ program to check parity

Sample code:

#include 
using namespace std;
 
int isEven(int num)
{
    return !(num & 1);
}
 
int main(){
 
    int num;
 
    // Nhập số từ người dùng
    cout>num;
 
    // Nếu hàm isEven() function trả về 0, thì số là số chẵn
    if(isEven(num))
    {
        //in số chẵn
        cout

Question 2: Write C++ to check prime numbers and armstrong numbers.

Sample code:

#include 
#include 
using namespace std;
 
int checkPrimeNumber(int n);
int checkArmstrongNumber(int n);
 
int main(){
 
    int num, flag;
 
    cout>num;
 
     // Kiểm tra số
    flag = checkPrimeNumber(num);
    if (flag == 1)
        cout

Hope these exercises will be useful to you. Wishing you good studies!

See more: Java exercises Basic, with sample code explanation

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments