Showing posts with label C/Cpp. Show all posts
Showing posts with label C/Cpp. Show all posts

Feb 15, 2020

[C/Cpp] an example of permutation

// Permutation,  total number of cases = R^N

#include <stdio.h>

#define N 3
#define R 4 

int temp[R];  
FILE *fp ;


void permutation(int value)
{
  int i;
  
  if(R==value){ 
    for(i=0; i<R; i++){
      printf("%d ", temp[i]);
      fprintf(fp, "%d ", temp[i]);
    }
    printf("\n"); 
    fprintf(fp, "\n");
    return;
  }
  for(i=1; i<=N; i++){
    temp[value]=i;
    permutation(value+1);
  }
}


int main()
{
    fp = fopen("all_cases.txt", "w");
    permutation(0);  
    return 0;
    fclose(fp);
}

[C/Cpp] file I/O

#include <stdio.h>

int main(){

    FILE *fp;
    int i, j;

    fp = fopen("test.txt", "w");
    for(i=0; i<10; i++){
        fprintf(fp, "%d\n", i);
    }
    fclose(fp);


    fp = fopen("test.txt", "r");
    while(fscanf(fp, "%d", &j) != EOF){
        printf("%d\n", j);
    }
    fclose(fp);

    return 0; 
}

 

Nov 20, 2017

[C/Cpp] How to include an external function in a C code

If you'd like to use an external function of add.c in main.c, you need to import the function in main.c.
Then, compile main.c with having add.c in same folder.


main.c
#include <stdio.h>
#include "add.c"
 
extern int add(int x, int y);
extern int sum;
 
 
void main(void)
{
 int a=2, b=5;
 
 sum = add(a,b);
 printf("%d\n", sum);
}


add.c
#include <stdio.h>
 
int add(int x, int y);
int sum=0;
 
int add(int x, int y)
{
 sum = x+y;
 return sum;
}


Dec 4, 2016

[C/Cpp] the greatest common divisor, the least common multiple

#include<stdio.h>
 
void main()
{
    int a,b,c,d;
    printf("Input two numbers for 'greatest common divisor' and 'least common multiple' : ");
    scanf("%d %d", &a, &b);
 
    d=a*b;
    while(a%b != 0){
        c=a%b;
        a=b;
        b=c;
    }
 
    printf("The greatest common divisor = %d\nThe least common multiple = %d\n", b, d/b);
 
}
 

Jan 27, 2016

[C/C++] find out whether a number is odd or even

#include <stdio.h>
 
void main(void)
{
    int i;
    printf("\nEnter a number (integer).. ");
    scanf("%d", &i);
 
    if(i & 1){
        printf("%d is odd \n", i);
    } else {
        printf("%d is even \n", i);
    }
    return 0;
}
 

Apr 24, 2015

[C/C++] command line arguments

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int isStringDouble(char *s);


int main(int argc, char* argv[]) {

  if (argc == 1) {
    fputs("No arguments found.\n", stderr);
    exit(1);
  }


// to check if input argument is number
  if (isStringDouble(argv[1])) {
    double d = atof(argv[1]);       // to convert the argument into number (double)
    printf("Number argument found : %.3f\n", d);
  }
  else {
    fputs("Argument is not a number.\n", stderr);
  }

  return 0;
}

int isStringDouble(char *s) {
  int size = strlen(s);
  if (size == 0) return 0;     //  if "strlen" function returns 0, it is not a number.

  int i=0;
  for (i = 0; i < size; i++) {
      if (s[i] == '.' || s[i] == '-' || s[i] == '+') continue;
      if (s[i] < '0' || s[i] > '9') return 0;           // if the argument contains alphabet, it is not a number.
  }

  return 1;      // otherwise, the argument is a number.
}


---------------------------------------------------------------------------------

#include <stdio.h>

int main ( int argc, char *argv[] )
{
    if ( argc != 2 ) // # of command line arguments should be 2 for correct execution (argv[0] = program filename, argv[1] = 1st command line argument)
    {
        printf( "usage: %s filename", argv[0] );     // print argv[0] (the program filename)
        char *fn = argv[1];
    }
    else
    {
        FILE *file = fopen( argv[1], "r" );     // assume argv[1] is a filename to open
      //or  FILE *file = fopen( fn, "r" ); 

        if ( file == 0 )        // fopen returns 0, the NULL pointer, on failure
        {
            printf( "Could not open file\n" );
        }
        else
        {
            int x;
// read one character at a time from file, stopping at EOF, which indicates the end of the file.  Note that the idiom of "assign to a variable, check the value" used below works because the assignment statement evaluates to the value assigned.
            while  ( ( x = fgetc( file ) ) != EOF )
            {
                printf( "%c", x );
            }
            fclose( file );
        }
    }
}


Aug 19, 2014

[C/C++] read xyz file and convert element symbol into atomic number

// This program reads a text file containing molecular configuration (element symbol, and xyz coordinates), and convert element symbol into atomic number.
 
#include <stdio.h>
 
#define max 1000
 
    int element[max], t_element=0, c_element[max];
    float x[max], y[max], z[max], t_x, t_y, t_z, c_x[max], c_y[max], c_z[max];
    int total_n=0;
    int count_atom=0;
    void list_atoms(int count_atom, int t_element, float *t_x, float *t_y, float *t_z);
 
 
void main(void)
{
FILE *xyzfile = fopen("example.txt", "r");
    if(xyzfile==NULL) {
        printf("\nError: Unable to open file.\n");
        exit(1);
    } else {
        fscanf(xyzfile, "%d\n", &total_n);
//       printf("\n\tTotal number of atoms : %d\n", total_n);
        char description[100];
        fgets(description, 100, xyzfile);
//       printf("\nDescription : %s\n", description);
 
        char e_type[2];
        int i=1;           // [1] is for first atom (third line)
        while(fscanf(xyzfile, "%s %f %f %f\n", e_type, &x[i], &y[i], &z[i]) != EOF){       // loop through and store elemental symbol, x, y, and z values into the array
 
            if (strcmp(e_type, "H")==0 || strcmp(e_type, "h")==0) {                        // convert elemental symbol into elemetal number
                element[i] = 1;
                t_element=element[i];
                t_x=x[i]; t_y=y[i]; t_z=z[i];
                count_atom++;
                list_atoms(count_atom, t_element, &t_x, &t_y, &t_z);
                i++;
            } else if(strcmp(e_type, "C")==0 || strcmp(e_type, "c")==0) {
                element[i] = 6;
                t_element=element[i];
                t_x=x[i]; t_y=y[i]; t_z=z[i];
                count_atom++;
                list_atoms(count_atom, t_element, &t_x, &t_y, &t_z);
                i++;
            } else if(strcmp(e_type, "N")==0 || strcmp(e_type, "n")==0) {
                element[i] = 7;
                t_element=element[i];
                t_x=x[i]; t_y=y[i]; t_z=z[i];
                count_atom++;
                list_atoms(count_atom, t_element, &t_x, &t_y, &t_z);
                i++;
            } else if(strcmp(e_type, "O")==0 || strcmp(e_type, "o")==0) {
                element[i] = 8;
                t_element=element[i];
                t_x=x[i]; t_y=y[i]; t_z=z[i];
                count_atom++;
                list_atoms(count_atom, t_element, &t_x, &t_y, &t_z);
                i++;
            } else if(strcmp(e_type, "Na")==0 || strcmp(e_type, "na")==0 || strcmp(e_type, "NA")==0) {
                element[i] = 11;
                t_element=element[i];
                t_x=x[i]; t_y=y[i]; t_z=z[i];
                count_atom++;
                list_atoms(count_atom, t_element, &t_x, &t_y, &t_z);
                i++;
            } else if(strcmp(e_type, "Mg")==0 || strcmp(e_type, "mg")==0 || strcmp(e_type, "MG")==0) {
                element[i] = 12;
                t_element=element[i];
                t_x=x[i]; t_y=y[i]; t_z=z[i];
                count_atom++;
                list_atoms(count_atom, t_element, &t_x, &t_y, &t_z);
                i++;
            } else if(strcmp(e_type, "Ca")==0 || strcmp(e_type, "ca")==0 || strcmp(e_type, "CA")==0) {
                element[i] = 20;
                t_element=element[i];
                t_x=x[i]; t_y=y[i]; t_z=z[i];
                count_atom++;
                list_atoms(count_atom, t_element, &t_x, &t_y, &t_z);
                i++;
            } else {
                element[i] = 0;
            }
    }
    fclose(xyzfile);
 
    printf("\nNumber of atoms : %d", count_atom);
}
}
 
 
void list_atoms(int count_atom, int t_element, float *t_x, float *t_y, float *t_z)
{
    int k = count_atom;
 
    c_element[k] = t_element;
    c_x[k] = *t_x;
    c_y[k] = *t_y;
    c_z[k] = *t_z;
    printf("\nafter function, converted element %-3d = %-2d %.5f %.5f %.5f", count_atom, c_element[k], c_x[k], c_y[k], c_z[k]);
}
 

Aug 17, 2014

[C/C++] How to calculate angle between three points in 3D

// This program calculates angle between three points in 3D.
//
// 3 points = A(Ax, Ay, Az), B(Bx, By, Bz), C(Cx, Cy, Cz)
// To calculate angle ABC,
//      vector BA = (Ax-Bx, Ay-By, Az-Bz)
//      vector BC = (Cx-Bx, Cy-By, Cz-Bz)
// The dot product of vector BA and BC is a function of the cosine of the angle ABC, i.e., it's scaled by the product of their magnitude.
// So,
//      (1) normalize vector BA and BC with the product of their magnitude
//      (2) calculate the dot product
//      (3) recover the angle
 
 
#include <stdio.h>
#include <math.h>
 
 
void main(void)
{
    float Ax, Ay, Az, Bx, By, Bz, Cx, Cy, Cz;
 
    printf("\nThis program calculates angle of three points (ABC).\n");
    printf("\nEnter 'x,y,z' of point A : ");
    scanf("%f,%f,%f", &Ax, &Ay, &Az);
    printf("Enter 'x,y,z' of point B : ");
    scanf("%f,%f,%f", &Bx, &By, &Bz);
    printf("Enter 'x,y,z' of point C : ");
    scanf("%f,%f,%f", &Cx, &Cy, &Cz);
 
    float vector_BA_x = Ax-Bx;
    float vector_BA_y = Ay-By;
    float vector_BA_z = Az-Bz;
    float vector_BC_x = Cx-Bx;
    float vector_BC_y = Cy-By;
    float vector_BC_z = Cz-Bz;
 
    float magnitude_BA = sqrt(vector_BA_x*vector_BA_x + vector_BA_y*vector_BA_y + vector_BA_z*vector_BA_z);
    float magnitude_BC = sqrt(vector_BC_x*vector_BC_x + vector_BC_y*vector_BC_y + vector_BC_z*vector_BC_z);
 
    // (1) normalize vector BA and BC with the product of their magnitude
    float normalized_BA_x = vector_BA_x / magnitude_BA;
    float normalized_BA_y = vector_BA_y / magnitude_BA;
    float normalized_BA_z = vector_BA_z / magnitude_BA;
    float normalized_BC_x = vector_BC_x / magnitude_BC;
    float normalized_BC_y = vector_BC_y / magnitude_BC;
    float normalized_BC_z = vector_BC_z / magnitude_BC;
 
    // (2) calculate the dot product
    float dot = normalized_BA_x * normalized_BC_x  +  normalized_BA_y * normalized_BC_y  +  normalized_BA_z * normalized_BC_z;
 
    // (3) recover the angle
    float angle = acos(dot);
    float angle_degree = angle * 180 / 3.14159265359;
 
 
    printf("\n\tAngle ABC = %.2f degrees\n", angle_degree);
 
}
 

Aug 6, 2013

[C/C++] how to change the random number seed every milisecond

(1) This changes the random number seed every second.
#include <time.h>
srand(time(NULL));

(2) This changes the random number seed every milisecond.
#include <Windows.h>
srand(GetTickCount());   // This uses CPU clock instead.

Mar 20, 2013

[C/C++] print 6 randomly generated numbers in order of larger number

// This program find maximum and minimum numbers out of 6 randomly generated numbers between 1 and 45.
 
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
 
void main(void)
{
int minv=1;  // minimum value of one number
int maxv=45;  // maximum value of one number
int i, t;
int ran[6];
int a,b,c,d,e,f;
int max1=minv-1, max2=minv-1, max3=minv-1, min1=maxv+1, min2=maxv+1, min3=maxv+1;
srand(time(NULL));
 
printf("This program find maximum and minimum numbers out of 6 randomly generated numbers between 1 and 45.\n\n\t");
 
for(i=1; i<=6; i++){
    ran[i] = rand() % 45 + 1;
    for(t=1; t<=5; t++){
        if(ran[i] == ran[i-t]) {
        ran[i]=rand()%45+1;
        }
    }
    a=ran[1]; b=ran[2]; c=ran[3]; d=ran[4]; e=ran[5]; f=ran[6];
 
    if(max1 < ran[i]){
        max3 = max2;
        max2 = max1;
        max1 = ran[i];
    }
       else if(max2 < ran[i]){
            max3 = max2;
            max2 = ran[i];
       }
            else if(max3 < ran[i]){
                max3 = ran[i];
            }
 
    if(min1 > ran[i]){
        min3 = min2;
        min2 = min1;
        min1 = ran[i];
    }
       else if(min2 > ran[i]){
            min3 = min2;
            min2 = ran[i];
       }
            else if(min3 > ran[i]){
                min3 = ran[i];
            }
 
}
 
printf("\t%2d  %2d  %2d  %2d  %2d  %2d", a,b,c,d,e,f);
printf("\n\n\tIn order of large numbers = %2d %2d %2d %2d %2d %2d ", max1, max2, max3, min3, min2, min1);
 
printf("\n\nPress 'Enter' key to continue...");
getchar();   // This command stops the cmd windows from closing automatically after running the code.
}
 

Mar 19, 2013

[C/C++] Australian Powerball number generator

// Australian Powerball number generator
// 6 random numbers between 1 and 40, and 1 additional number between 1 and 20


[C/C++] Gauss elimination method

// Gauss elimination method
# include<stdio.h>
# include<conio.h>

void main()
{
 int i,j,k,n;
 float a[10][10],x[10];
 float s,p;
 printf("Enter the number of equations : ");
 scanf("%d",&n) ;
 printf("\nEnter the coefficients of the equations :\n\n");

 for(i=0;i<n;i++) {
    for(j=0;j<n;j++){
        printf("a[%d][%d]= ",i+1,j+1);
        scanf("%f",&a[i][j]);
    }

    printf("d[%d]= ",i+1);
    scanf("%f",&a[i][n]);
 }

 for(k=0;k<n-1;k++){
    for(i=k+1;i<n;i++){
        p = a[i][k] / a[k][k] ;
    for(j=k;j<n+1;j++)
        a[i][j]=a[i][j]-p*a[k][j];
    }
 }

 x[n-1]=a[n-1][n]/a[n-1][n-1];
 for(i=n-2;i>=0;i--){
    s=0;
    for(j=i+1;j<n;j++){
        s +=(a[i][j]*x[j]);
        x[i]=(a[i][n]-s)/a[i][i];
    }
 }

 printf("\nThe result is:\n");
 for(i=0;i<n;i++)
  printf("\nx[%d]=%f",i+1,x[i]);

 printf("\n");
 getch();
}

[C/C++] Gauss-Seidel iterative method

// Gauss-Seidel iterative method
#include<stdio.h>
#include<conio.h>
#include<math.h>
#define e 0.01

void main()
{
    int i,j,k,n;
    float a[10][10],x[10];
    float sum,temp,error,big;
    printf("Gauss-Seidel iterative method\n\n");
    printf("Enter the number of equations: ");
    scanf("%d",&n) ;
    printf("Enter the coefficients of the equations: \n");

    for(i=1;i<=n;i++){
        for(j=1;j<=n+1;j++){
            printf("a[%d][%d]= ",i,j);
            scanf("%f",&a[i][j]);
        }
    }

    for(i=1;i<=n;i++){
        x[i]=0;
    }

    do {
        big=0;
        for(i=1;i<=n;i++){
            sum=0;
            for(j=1;j<=n;j++){
                if(j!=i){
                    sum=sum+a[i][j]*x[j];
                }
            }


        temp=(a[i][n+1]-sum)/a[i][i];
            error=fabs(x[i]-temp);

            if(error>big){
            big=error;
            }

            x[i]=temp;
            printf("\nx[%d] =%f",i,x[i]);
        }

        printf("\n");
    }

    while(big>=e);
    printf("\n\nconverges to solution");
    for(i=1;i<=n;i++){
        printf("\nx[%d]=%f",i,x[i]);
    }

 printf("\n");
 getch();
}

OR

#include<stdio.h> #include<conio.h> #include<math.h> #include<stdlib.h>   void main() { float a[20][20],x[20],e,big,temp,relerror,sum; int n,i,j,maxit,itr;   printf("Gauss-Seidel iterative methodnn"); printf("Enter the number of equations : "); scanf("%d",&n);   for(i=1;i<=n;i++){ printf("Enter the coefficints of equation %d : ",i); for(j=1;j<=n+1;j++) scanf("%f",&a[i][j]); }   printf("Enter relative error and maximum number of iterations : "); scanf("%f%d",&e,&maxit);   for(i=1;i<=n;i++) x[i]=0; for(itr=1;itr<=maxit;itr++){ big=0; for(i=1;i<=n;i++){ sum=0; for(j=1;j<=n;j++){ if(i!=j ) sum=sum+a[i][j]*x[j]; } temp=(a[i][n+1]-sum)/a[i][i]; relerror=fabs((x[i]-temp)/temp); if(relerror>big) big=relerror; x[i]=temp; } if(big<=e){ printf("nConverges to a solution in %d iterationsn",itr); for(i=1;i<=n;i++) printf("%.4ftn",x[i]); getch(); exit(1); } }   printf("ndoes not converge in %d iterations n",maxit); getch();   }