C ++ exercises with answers (sample code)


Besides Python, Java exercises, Webmaster also summarizes for you some basic C ++ exercises to practice more in learning C ++ programming language.

This list of C ++ exercises is divided into 9 sections, each with 3 to 5 exercises, with increasing difficulty. Initially, you will “start” with the very basic C ++ exercises, such as simulating multiplication, printing the sum, checking a set of 3 numbers to see if it is the edge of a triangle, calculating the circumference, area of ​​that triangle.

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

List of C ++ exercises

  • Exercise C ++ No. 1

    • Sentence 1: Simulate multiplication by hand
    • Question 2: Enter the amount, print the number of sheets, face value
    • Question 3: Convert numbers to Roman numbers
    • Question 4: Print the number reading
    • Sentence 5: Solve quadratic equations
  • Exercise C ++ No. 2

    • Question 1: Check if the 3 numbers are not triangular, if there are any types of triangle, circumference, area
    • Question 2: Calculate the number of years to save
    • Sentence 3: Print number of PI calculated with given error
    • Question 4: Find and print the perfect number
    • Sentence 5: Find and print primes less than n
  • Exercise C ++ number 3

    • Question 1: Check the square root
    • Sentence 2: Solve first-degree inequalities
    • Sentence 3: Write recursive function to find the greatest common divisor
    • Sentence 4: Calculate factorial way of positive integers n
    • Sentence 5: Write recursive function to solve Hanoi tower problem
  • Exercise C ++ number 4

    • Sentence 1: Print elements of array as required
    • Sentence 2: Import, sort, print arrays
    • Sentence 3: Enter, print array, count paragraph by criteria
    • Sentence 4: Enter, print, calculate the product of 2 matrices
    • Sentence 5: Enter, print square matrix, calculate determinant
  • Exercise C ++ No. 5

    • Sentence 1: Check the symmetry of a string
    • Sentence 2: Statistics of the number of occurrences of a character in a string
    • Question 3: Standardize the string
    • Sentence 4: Enter an array of characters and sort ascending
  • Exercise C ++ number 6

    • Question 1: Managing test takers’ scores by array
    • Question 2: Manage documents, print lists as required
    • Question 3: Managing electricity bill payment
  • Exercise C ++ number 7

    • Question 1: Create a file of numbers, counting numbers, largest numbers, smallest numbers
    • Question 2: Create a student name file, organize and print
    • Question 3: Create a student profile list file as required
  • Exercise C ++ No. 8

    • Question 1: Draw a red flag with a yellow star at the center of the screen.
    • Sentence 2: Draw a simulated antenna broadcast tower.
    • Question 3: Draw a star sky on the screen.
    • Question 4: Graph the function y = sinx.
    • Question 5: Draw a moving ball in a rectangular frame.
  • Exercise C ++ number 9

    • Question 1: Create a vector layer as required
    • Question 2: Create a fractional class as required
    • Question 3: Create commodity classes as required
    • Sentence 4: Write function to import, export and sort arrays

Exercise C ++ No. 1

Sentence 1: Simulate multiplication by hand

Program the screen to simulate multiplication of 2 positive integers with 3 digits entered from the keyboard. For example, if the two numbers entered are 763 and 589, the screen must be printed as follows:

Exercise C ++ No. 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 taynn");
printf("%20dn",a);
printf("%15c%5dn",'x',b);
printf("%20sn","-------");
printf("%20dn",a*dv);
printf("%19dn",a*chuc);
printf("%18dn",a*tram);
printf("%20sn","-------");
printf("%20ldn",long(a)*b);
getch();

}

Question 2: Enter the amount, print the number of sheets, face value

One needs to withdraw some money from the T bank and wants the least number of sheets. Indicate the denominations of 100, 20, 5 and 1. denominations from the keyboard the amount T and print the number of sheets of each face value and the total number of notes 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 ton",t100);
 printf("Loai 20 : %d ton",t20);
printf("Loai 5 : %d ton",t5);
printf("Loai 1 : %d ton",t);
printf("Tong so to cac loai la : %dn",t+t5+t20+t100);
 getch();
}

Question 3: Convert numbers to Roman numbers

Program the program to enter a positive integer less than 1000 and convert it to the corresponding Roman number, print the results on the screen.

Sample code:

#include

#include

void main()

{int n,dv,ch,tr;

clrscr();

cout<<"Nhap so nguyen duong <1000 :n"; cin>>n;

cout<<"So "<

tr=n/100;n=n%100; ch=n/10;dv=n%10;

switch (tr)

{case 1:cout<<"C";break;

case 2:cout<<"CC";break;

case 3:cout<<"CCC";break;

case 4:cout<<"CD";break;

case 5:cout<<"D";break;

case 6:cout<<"DC";break;

case 7:cout<<"DCC";break;

case 8:cout<<"DCCC";break;

case 9:cout<<"CM";

}

switch (ch)

{case 1:cout<<"X";break;

case 2:cout<<"XX";break;

case 3:cout<<"XXX";break;

case 4:cout<<"XL";break;

case 5:cout<<"L";break;

case 6:cout<<"LX";break;

case 7:cout<<"LXX";break;

case 8:cout<<"LXXX";break;

case 9:cout<<"XC";

}

switch (dv)

{case 1:cout<<"I";break;

 case 2:cout<<"II";break;

 case 3:cout<<"III";break;

 case 4:cout<<"IV";break;

 case 5:cout<<"V";break;

 case 6:cout<<"VI";break;

 case 7:cout<<"VII";break;

 case 8:cout<<"VIII";break;

 case 9:cout<<"IX";

}

getch();

}

Question 4: Print the number reading

Print out the screen how to read a positive integer smaller than 1000000. For example, 726503 read: 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<<"Nhap so nguyen duong <1000000 can doc = ";cin>>so;

  cout<<"Cach doc so "<

  van=so/10000; ngan=so/1000%10; tram=so/100%10; chuc=so/10%10; donvi=so%10;

  if(van)

{chv=van/10; dv=van%10;

  if(chv==1)cout<<"muoi ";

  else if(chv>1)cout<

  if(dv)cout<

  cout<<" van ";

}

if((ngan==0)&&van)cout<<" khong ngan ";

else if(ngan)cout<

if((tram==0)&&(van||ngan))cout<<" khong tram ";

else if(tram)cout<

if((chuc==0)&&donvi&&(van||ngan||tram))cout<<"le ";

else if(chuc==1)cout<<" muoi ";

  else cout<

if(donvi)cout<

getch();

}

Sentence 5: Solve quadratic equations

Programming solve the ax equation2 + bx + c = 0, real coefficients a, b, c 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("Vo nghiem !");

if (d==0) printf("Nghiem kep x=%4.2f",-0.5*b/a);

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();

}

Exercise C ++ No. 2

Question 1: Check if the 3 numbers are not triangular, if there are any types of triangle, circumference, area

Enter 3 real numbers a, b, c and check 3 are the 3 sides of a triangle? If it is a triangle, then tell us which of the following triangles: regular, isosceles, isosceles, squares, isos, usually and its perimeter and area. Print 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(" deun");

else if(vuong&&can)printf(" vuong cann");

  else if(vuong)printf(" vuongn");

  else if(can)printf(" cann");

  else printf(" thuongn");

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 giacn");

getch();

}

Question 2: Calculate the number of years to save

A person needs to have a T sum, accumulated by saving the initial amount of S with an annual interest rate of P% by the progressive method (the interest of each year is added to the principal). . Please enter 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

printf("So nam can gui tiet kiem = %dn",n);

printf("Sau %d nam gui tiet kiem, so tien co la : %4.2f",n,s);

getch();

}

Sentence 3: Print number of PI calculated with given error

Program the calculation of PI number with the given eps number error from the keyboard. Know that the PI number is calculated using the formula: PI = 4 - 4/3 + 4/5 - 4/7 + ... sum the terms whose value is not less than eps. Print out the calculated PI and PI of Turbo C ++ 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.10fn",eps,pi);

printf("nSo PI cua Turbo C++, PI=%12.10fn",M_PI);

getch();

}

Question 4: Find and print the perfect number

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

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<=n; i++)

{ s=1;

  for(j=2;j<=i/2;j++)

  if(i%j==0)s+=j;

  if(s==i)

  { ts++;

  printf("n %d = 1", i);

  for(j=2;j<=i/2;j++) if(i%j==0)printf(" + %d",j);

  }

}

if(ts)printf("nCo tat ca %d so hoan hao",ts);

else printf("nKhong co so hoan hao nao");

getch();

}

Sentence 5: Find and print primes less than n

Find and print on the screen all prime numbers that do not exceed the given number n entered from the keyboard. A prime number is a number that has only a divisor of 1 and that 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<=n;i++)

{for (j=2;j<=i/2; j++)

  if(i%j==0)break;

  if (j==i/2+1)

  {d++;

  printf(" %d",i);

  }

 }

 printf("nTong so co %d so nguyen to",d);

 getch();

} 

Exercise C ++ number 3

Question 1: Check the square root

Write a function that checks whether a number is the square root (the square root is the square of a certain integer); A function that tests whether a number is a Pythagorean number or not (the Pythagorean number is the square root and the sum of the other two squares). In the main function, enter a positive integer and use the above functions to check if the square is the square root? Pitago number?

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

if(socp(i)&&socp(n-i))break;

if(i

else return 0;

}

}

Sentence 2: Solve first-degree inequalities

Programming solve the inequality ax + b> 0 as required: Write a function to enter the coefficients a, b; a function for solving inequalities. The main function uses the written functions and can run many times solving 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<<"nTiep tuc ? (c/k):"; cin>>c;

}while ((c=='c')||(c=='C'));

}

void nhap(float &a, float &b)

{cout<<"Nhap cac he so a, b :"; cin>>a>>b;

}

void giaibpt(float a, float b)

{if(a>0)cout<<"Nghiem x>"<<-b/a;

else if(a<0)cout<<"Nghiem x<"<<-b/a;

  else if(b>0) cout<<"Vo so nghiem";

  else cout<<"Vo nghiem";

}

Sentence 3: Write recursive function to find the greatest common divisor

Write the recursive function to find the greatest common divisor of 2 natural numbers; a function that finds the least common multiple of 2 natural numbers. The main function uses the written functions and can run multiple times to find the greatest common divisor and the least common multiple of the pairs of different positive integers. Check input requirements 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<<"Nhap 2 so nguyen duong a, b : "; cin>>a>>b;

}while((a<=0)||(b<=0));

d=usc(a,b);

p=bsc(a,b);

cout<<"USCLN("<

cout<<"nBSCNN("<

fflush(stdin);

cout<<"nTiep tuc ? (c/k):"; cin>>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);

}

Sentence 4: Calculate factorial way of positive integers n

Write a recursive function that calculates the factorial of positive integers n. The main function uses this function and can be run multiple times to calculate different numbers for the input n from the keyboard. The input test must be a positive integer. The formula calculates 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<<"Nhap so nguyen duong n : "; cin>>n;

}while (n<1);

cout<

fflush(stdin);

cout<<"nTiep tuc ? (c/k):"; cin>>c;

}while ((c=='c')||(c=='C'));

}

long gtc(long n)

{if((n==0)||(n==1))return 1;

else return n*gtc(n-2);

}

Sentence 5: Write recursive function to solve Hanoi tower problem

Write a recursive function to solve the problem of Hanoi tower: Need to move n towers from position A to position B using position C as an intermediary. Requirement: Only one floor is transferred at a time, only the A, B and C locations can be used to place the towers, not the larger floors on the small floors. The main function uses this function and can be run multiple times to calculate different numbers for the input n 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<<"Nhap so tang thap (<10), n="; cin>>n;

}while ((n<1)||(n>9));

chuyen(n,'A','B','C');

cout<<"nTong so lan chuyen="<

fflush(stdin);

cout<<"nTiep tuc ? (c/k):"; cin>>c;

}while ((c=='c')||(c=='C'));

}

void chuyen(int n,char a,char b,char c)

{if(n==1)cout<<"nLan chuyen "<<++d<<" : Tu "<

else

{chuyen(n-1,a,c,b);

chuyen(1,a,b,c);

chuyen(n-1,c,b,a);

}

}

Exercise C ++ number 4

Sentence 1: Print elements of array as required

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

Sample code:

#include

#include

#define max 100

void main()

{int i,j,n;

float a[max],tbc,pmax,pmin;

clrscr();

cout<<"Nhap so phan tu n<"<

for (i=0;i

{cout<<"A["<>a[i];

}

pmax=pmin=tbc=a[0];

for(i=1;i

{tbc+=a[i];

if(pmax

if(pmin>a[i])pmin=a[i];

}

tbc=tbc/n;

cout<<"nPhan tu max="<

cout<<"nPhan tu min="<

cout<<"nGia tri TBC="<

cout<<"nCac phan tu < TBC:n";

for (i=0;i

cout<<"nCac phan tu > TBC:n";

for (i=0;itbc) cout<

}

Sentence 2: Import, sort, print arrays

Write an array entry function, an array sort function, and a function that prints the elements of the array to the screen. The main function uses these functions to enter the array of n elements, printing the array before and after the arrangement.

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<<"Nhap so phan tu n<"<

xuat(a,n);

sapxep(a,n);

cout<<"nMang sau khi sap xep :n";

xuat(a,n);

}

void nhap(int a[],int n)

{int i;

cout<<"Nhap cac phan tu cua mang :n";

for (i=0;i

{cout<<"A["<

cin>>a[i];

}

}

void xuat(int a[],int n)

{int i,j;

for (i=0;i

}

void sapxep(int a[],int n)

{int i,j,tg;

for (i=0;i

for (j=i+1;j

if (a[i]>a[j])

{tg=a[i]; a[i]=a[j]; a[j]=tg;

}

}

Sentence 3: Enter, print array, count paragraph by criteria

Write an array entry function, a function that prints the elements of the array to the screen, a function that counts the number of increments, a function that finds the longest increase segment in the array. The main function uses these functions to enter the array of n elements, print the array, print the longest number of increments and arrays 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<<"Nhap so phan tu n<"<

xuat(a,n);

cout<<"nSo doan tang :"<

timdoantangmax(a,n,d,c);

cout<<"nDoan tang dai nhat la : ";

for(i=d;i<=c;i++)cout<

}

void nhap(int a[],int n)

{int i;

cout<<"Nhap cac phan tu cua mang :n";

for (i=0;i

{cout<<"A["<

cin>>a[i];

}

}

void xuat(int a[],int n)

{int i;

for (i=0;i

}

int sodoantang(int a[],int n)

{int i,d;

if(n>0)d=1;

else d=0;

for(i=0;i

if(a[i+1]

return d;

}

void timdoantangmax(int a[],int n,int &d,int &c)

{int t,p;

p=0;d=c=0;

do

{t=p;

for(p=t;(p

if(p-t>c-d)

{d=t; c=p;

}

if(p

}while(p

}

Sentence 4: Enter, print, calculate the product of 2 matrices

Write a function for importing elements of a 2-dimensional matrix, a function for printing matrices in rows, and a function for multiplying 2 matrices. The main function uses these functions to enter the matrix A size MxN and matrix B size NxP. Print matrix A, B and matrix C are products 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<<"Nhap kich thuoc mang a: so hang, so cot <10, so hang m="; cin>>m;

cout<<"so cot n="; cin>>n;

cout<<"Nhap kich thuoc mang b: so hang = so cot mang a la "<

nhap('a',m,n);

cout<<"Nhap mang b :n";

nhap('b',n,p);

cout<<"nMang A :n";

xuat('a',m,n);

cout<<"nnMang B :n";

xuat('b',n,p);

nhan(m,n,p);

cout<<"nnMang C=AxB:n";

xuat('c',m,p);

}

void nhap(char k,int p,int q)

{int i,j,t;

for (i=0;i

{cout<<"Nhap cac phan tu hang thu "<

for (j=0;j

{cout<

  cin>>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

{cout<

for (j=0;j

{cout<<" ";

  switch(k)

  {case 'a':cout<

  case 'b':cout<

  case 'c':cout<

  }

  }

  }

}

void nhan(int m,int n,int p)

{int i,j,k,s;

for (i=0;i

for (j=0;j

{for (k=s=0;k

c[i][j]=s;

}

}

Sentence 5: Enter, print square matrix, calculate determinant

Write a function for importing the elements of a n-square matrix, a function for printing matrices in a column structure, and a function for determining n-matrix determinants. The main function uses these functions to enter the n-square matrix, print out the matrix, calculate and print out the determinant of that matrix.

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<<"Nhap kich thuoc ma tran vuong a: so hang = so cot <10, n="; cin>>n;

cout<<"Nhap ma tran a :n";

nhap();

cout<<"nMa tran A :n";

xuat();

cout<<"nnDinh thuc ma tran A :"<

}

void nhap()

{int i,j,t;

for (i=0;i

{cout<<"Nhap cac phan tu hang thu "<

for (j=0;j

{cout<<"A["<>t; a[i][j]=t;

}

}

}

void xuat()

{int i,j;

for (i=0;i

{cout<

for (j=0;j

{cout<<" "; cout<

}

}

}

void doicot(int k,int t)

{int i;float p;

for(i=0;i

{p=a[i][k];

a[i][k]=a[i]

Exercise C ++ No. 5

Sentence 1: Check the symmetry of a string

Write a function to check the symmetry of a string of characters. In the main function, input the string of characters from the keyboard and indicate whether the string is symmetric. Require the program to run repeatedly.

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<=n/2)&&d;i++)

d=(s[i]==s[n-1-i]);

return d;

}

Sentence 2: Statistics of the number of occurrences of a character in a string

Write a statistical function that shows the frequency of each character in a string. The main function imports a string of characters from the keyboard and prints the frequency of each character. Require the program to run repeatedly.

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<128;i++)

if(ts[i])

if(i==32) printf("nDau cach : %d",ts[i]);

else printf("nKy tu %c : %d",i,ts[i]);

printf("nTiep tuc ? (c/k):");

fflush(stdin);

c=getchar();

}while ((c=='c')||(c=='C'));

}

void thongke(char s[])

{int i,n;

n=strlen(s);

for(i=0;i<128;i++)ts[i]=0;

for(i=0;i

}

Question 3: Standardize the string

Write a string normalization function: convert the string to a string so that there are no two consecutive spaces in the string, a function that finds the number of words of a string of characters, a function that finds the longest word in a string of characters. . The main function uses these functions to input a string of characters from the keyboard, printing the string before and after normalization, the number of words in the string and the longest word in the 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 : %dn",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

if(i

}while(i

if(s[0]==32)for(i=0;(i

}

int sotu(char s[])

{int i,n,d;

n=strlen(s);

if((n>0)&&(s[0]-32))d=1;

else d=0;

for (i=0;i

return d;

}

char *timtumax(char s[])

{int t,p,n,c,d;char x[80];

d=0;c=t=-1; n=strlen(s);

do

{do t++; while ((tQuestion 1: Draw the red flag with the yellow star at 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 : %sn",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 simulated 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 : %sn",grapherrormsg(errorcode));

printf("Press any key to halt ...");

getch();

exit(1);

}

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

}

Question 3: Draw the star 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 : %sn",grapherrormsg(errorcode));

printf("Press any key to halt ...");

getch();

exit(1);

}

mx=getmaxx();my=getmaxy();

randomize();

for (i=0;i<100;i++)

{p[i].x=random(mx);

p[i].y=random(my);

p[i].s=random(4);

p[i].c=random(16);

p[i].h=random(2);

}

while (!kbhit())

{for (i=0;i<100;i++) vediem(p[i],1);

delay(100);

for (i=0;i<100;i++) vediem(p[i],0);

for (i=0;i<100;i++)

{if (p[i].h)

{p[i].s++;

if (p[i].s>=3) p[i].h=0;

}

else

{p[i].s--;

if (p[i].s<=3) p[i].h=1;

}

}

}

closegraph();

}

void vediem(point p,int v)

{int mau;

if (v) mau=p.c;

else mau=BLACK;

setcolor(mau);

switch (p.s)

{case 0: putpixel(p.x,p.y,mau); break;

case 1: line(p.x-1,p.y,p.x+1,p.y);

  line(p.x,p.y-1,p.x,p.y+1); break;

case 2: line(p.x-2,p.y,p.x+2,p.y);

  line(p.x,p.y-2,p.x,p.y+2); break;

case 3: line(p.x-4,p.y,p.x+4,p.y);

  line(p.x,p.y-4,p.x,p.y+4);

  rectangle(p.x-1,p.y-1,p.x+1,p.y+1);

}

}

Question 4: Graph 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 : %sn",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

{ y=k*sin((x-mx)*kx);

putpixel((int)floor(x),my-(int)floor(y),RED);

x=x+0.1;

}

settextstyle(1,0,2);

setcolor(LIGHTGREEN);

outtextxy(50,10,"Do Thi Ham So");

outtextxy(50,40," y = Sin(x)");

settextstyle(2,0,5);

outtextxy(mx+7,my+5,"0");

line(mx+mx/4,my-2,mx+mx/4,my+2);

line(mx-mx/4,my-2,mx-mx/4,my+2);

line(mx/4,my-2,mx/4,my+2);

line(2*mx-mx/4,my-2,2*mx-mx/4,my+2);

line(mx-2,my-100,mx+2,my-100);

line(mx-2,my+100,mx+2,my+100);

outtextxy(mx-13,my-107,"1");

outtextxy(mx-20,my+90,"-1");

moveto(mx+mx/2-4,my+17);

lineto(mx+mx/2-4,my+9);

lineto(mx+mx/2+1,my+9);

lineto(mx+mx/2+1,my+17);

moveto(mx/2-4,my+17);

lineto(mx/2-4,my+9);

lineto(mx/2+1,my+9);

lineto(mx/2+1,my+17);

line(mx/2-10,my+12,mx/2-7,my+12);

getch();

closegraph();

}

Question 5: Draw moving balls in the 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 : %sn",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 (xmx-R-1)

{dx=-dx;

x+=2*dx;

d=1;

}

if (ymy-R-1)

{dy=-dy;

y+=2*dy;

d=1;

}

}while (!kbhit());

}

Exercise C ++ number 9

Question 1: Create a vector layer as required

Create vector layers with dimension and array properties containing vector elements; methods: input, output, plus 2 vectors. The main function uses the vector layer 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

 }

vecto ::~vecto()

  { delete[]ptr;

  }

void vecto::inputvt()

{ int i;

  cout<<"n input vecto:";

  for (i=0;i

 { cout<<"ptu["<

  cin>>ptr[i];

 }

}

void vecto::displayvt(int *p)

 { int i;

  for (i=0;i

 }

void vecto::print()

 { int i;

  for (i=0;i

  { cout <

  cout <<"n";

  }

  }

void vecto::sumvt(int *p,int *p1)

  {int i;

  for(i=0;i

  }

void main()

  { int n, *p,*p1;

  clrscr();

  cout<<"enter sign of vecto :"<<'n';

  cout<<"n="; cin>>n;

  vecto a(n),b(n),c(n);

  cout<<"input vecto a:"<

  a.inputvt();

  cout <<"input vecto b:"<

  b.inputvt();

  a.displayvt(p);

  b.displayvt(p1);

  c.sumvt(p,p1);

  cout <<"display input vecto:"<

  cout<<"n display vecto a:"<

  a.print ();

  cout <<"ndisplay vecto b"<

  b.print();

  cout<<"n display vecto tong c"<

  c.print();

  getch();

} 

Question 2: Create a fractional class as required

Create a class of fractions with numerator and denominator properties; methods: inputting, presenting, reducing, converging 2-digit denominator and adding 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<<"Nhap tu so : ";cin>>tuso;

cout<<"Nhap mau so : ";cin>>mauso;

}

void hienphanso()

{cout<

}

void quydong(phanso &b)

{b.tuso=b.tuso*mauso;

mauso=mauso*b.mauso;

tuso=tuso*b.mauso;

b.mauso=mauso;

}

phanso operator+(phanso b)

{phanso c;

c.tuso=tuso+b.tuso;

c.mauso=mauso;

return c;

}

void rutgon()

{int u=usc(tuso,mauso);

tuso=tuso/u;

mauso=mauso/u;

}

};

class phansomoi:public phanso

{public:

phansomoi operator+(phansomoi b)

{phansomoi c;

c.tuso=tuso+b.tuso;

c.mauso=mauso;

return c;

}

phansomoi operator*(phansomoi b)

{phansomoi c;

c.tuso=tuso*b.tuso;

c.mauso=mauso*b.mauso;

return c;

}

};

void main()

{

clrscr();

phansomoi x,y,kq;

cout<<"Nhap phan so thu nhat :"<

x.nhap();

cout<<"Nhap phan so thu hai :"<

y.nhap();

cout<<"Cac phan so da nhap la :"<

x.hienphanso();

y.hienphanso();

x.quydong(y);

kq=x+y;

kq.rutgon();

cout<<"Tong 2 phan so da nhap la :"<

kq.hienphanso();

kq=x*y;

kq.rutgon();

cout<<"Tich 2 phan so da nhap la :"<

kq.hienphanso();

getch();

}

Question 3: Create commodity classes as required

Create commodity class with attributes such as item code, goods name, unit of calculation, unit price, quantity and amount; methods: enter, calculate into money. Create a new cargo class that inherits the cargo class, adding the attributes: shipping unit cost and shipping cost calculated by the shipping unit multiplied by the quantity; methods: calculating shipping, importing and calculating money. The main function uses these classes and implements methods.

Sample code:

#include

#include

class hanghoa

{public:

char mahang[2];

char tenhang[20];

char donvitinh[10];

float dongia,soluong,thanhtien;

void nhap()

{cout<<"Nhap ma hang : ";cin>>mahang;

cout<<"Nhap ten hang : ";cin>>tenhang;

cout<<"Nhap don vi tinh : ";cin>>donvitinh;

cout<<"Nhap don gia : ";cin>>dongia;

cout<<"Nhap so luong : ";cin>>soluong;

}

void tinhthanhtien()

{thanhtien=dongia*soluong;

}

};

class hanghoamoi:public hanghoa

{public:

float dongiavanchuyen,congvanchuyen;

void nhap()

{hanghoa::nhap();

cout<<"Nhap don gia van chuyen : ";cin>>dongiavanchuyen;

}

void tinhcongvanchuyen()

{congvanchuyen=soluong*dongiavanchuyen;

}

void tinhthanhtien()

{thanhtien=dongia*soluong+congvanchuyen;

}

};

void main()

{hanghoamoi x;

clrscr();

x.nhap();

x.tinhcongvanchuyen();

x.tinhthanhtien();

cout<<"Thanh tien : "<

getch();

}

Sentence 4: Write function to import, export and sort arrays

Use templates to write functions for importing, exporting, and arranging arrays. The main function uses these template functions to enter an array of n elements, printing the array before and after sorting for two cases: integer arrays and real numbers arrays.

Sample code:

#include

#include

template

void nhap(T a[],int n)

{int i;

cout<<"Nhap cac phan tu cua mang :n";

for (i=0;i

{cout<<"A["<

cin>>a[i];

}

}

template

void xuat(T a[],int n)

{int i,j;

for (i=0;i

}

template

void sapxep(T a[],int n)

{int i,j;T tg;

for (i=0;i

for (j=i+1;j

if (a[i]>a[j])

{tg=a[i]; a[i]=a[j]; a[j]=tg;

}

}

void main()

{int a[100],n;

float b[100];

clrscr();

cout<<"Nhap so phan tu n= ";

cin>>n;

cout<<"nNhap mang so nguyen:n";

nhap(a,n);

cout<<"Mang truoc khi sap xep :n";

xuat(a,n);

sapxep(a,n);

cout<<"nMang sau khi sap xep :n";

xuat(a,n);

cout<<"nNhap mang so thuc:n";

nhap(b,n);

cout<<"Mang truoc khi sap xep :n";

xuat(b,n);

sapxep(b,n);

cout<<"nMang sau khi sap xep :n";

xuat(b,n);

}

Hope these exercises will be helpful to you. Wish you all good study!

Explore more: Java exercises Basically, there is a sample code solution

.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *