In this article we will make some exercises, to see how C works. I hope this article will help you understand better how a program should look.Let’s get to work!
1. Prime Numbers
#include "stdafx.h" #include <iostream> using namespace std; int main() { int i,j,nr; printf("Number::"); scanf("%d", &nr); for(i = 2; i < nr; i++) { for(j = 2; j <= i/2; j++) { if(!(i % j)) break; } if(j > i / 2) { printf(" "); printf("%d",i); } } getchar(); return 0; }
This program gives us all prime numbers down to a number that we choose.
2. Checking Prime Number
#include "stdafx.h" #include <iostream> using namespace std; int main() { int nr, s = 0;; printf("Number:"); scanf("%d",&nr); for(int i = 1; i <= nr; i++) { if(nr % i == 0) s =s + 1; } if(s == 2) printf("The number is prime"); else printf("The number is not prime"); getchar(); return 0; }
In this example I check if a number is prime or not.
3. Matrix
#include "stdafx.h" #include <stdio.h> int main() { int l, c, mat[10][10]; printf("Number of lines:"); scanf("%d", &l); printf("Number of columns:"); scanf("%d", &c); if( l!= c) { printf("Matrix is not square"); } if(l == c) { for(int i = 0;i < l;i++) { for(int j = 0 ;j < c;j++) { printf("mat[%d][%d]=", i, j); scanf("%d", &mat[i][j]); } } printf("Main diagonal elements:"); for(int q = 0; q < l; q++) { printf("%d", mat[q][q]); printf(" "); } } getchar(); return 0; }
As you can see in this example I made an application, that returns us the main diagonal elements of a matrix with n lines and n columns (n < 10).
4. Amicable Numbers
Amicable numbers are two different numbers so related that the sum of the proper divisors of each is equal to the other number. For example, the smallest pair of amicable numbers is (220, 284); for the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110 – whose sum is 284; and the proper divisors of 284 are 1, 2, 4, 71 and 142- the sum of which is 220.
#include "stdafx.h" #include <iostream> #include <stdio.h> using namespace std; int main() { int nr,sd1,sd2; nr = 2; while(nr < 10000) { sd1 = 0; for(int i = 1; i <= nr / 2; i++) { if(nr % i == 0) { sd1 = sd1 + i; } } sd2 = 0; for(int i = 1; i <= sd1 / 2; i++) { if(sd1%i == 0) { sd2 = sd2 + i; } } if(sd2 == nr && nr < sd1) { printf("%d - %d\n", nr,sd1); } nr++; } getchar(); return 0; }
Now we have all amicable numbers till 10000.