Computer Concept & Programming In C - Unit V - 8

Q.23 Write a program in C that takes ten integers from a file and write square of these integers into another file.                                             (AKTU. 2008-09)
Ans. # include <stdio.h>
# include <conio.h>
# include <stdlib.h>
# include <math.h>
# define INPUT_FILE “number.txt”
# define OUTPUT _FILE “square.txt”
# define size 19
# define N 10
void main ( )
{
char num[size];
double squ;
int i, j;
FILE*in, *out;
clrscr ( );
printf (“\n Enter %d numbers for INPUT_FILE:\n”, (int) N);
in = fopen (INPUT_FILE, “W”);
if (in != NULL)
{
for (i = 0; i < N; i++)
{
for (j = 0; j < N; j++)
num[j] = NULL;
printf (“\n Enter the %d number:\n”, i + 1);
gets (num);
fputs (num, in);
fputs (“\n, in);
}
fclose (in);
}
else
printf (“\n Enter in opening the file.”);
for (j = 0; j < size; j++)
num [j] = NULL;
printf (“\n The numbers / contents of the INPUT_FILE are:\n”);
in = fopen (INPUT_FILE, “r”);
out = fopen (OUTPUT_FILE, “w”);
if ((in != NULL) && (out != NULL))
{
for (i = 0; i < N; i++)
{
for (j = 0; j < size; j++)
num[j] = NULL;
fgets (num, size, in);
fputs (num, stdout);
squ = atof (num); //converting from characters to double
squ = pow (squ, 2.0); //squaring the number
for (j = 0; j < size; j++)
num[j] = NULL;
gcvt (squ, size, num); //converting square in double to string
fputs (num, out); //writing the square into OUTPUT_FILE
fputs (“\n”, out);
}
fclose (in);
fclose (out);
}
else
printf (“\n Error in opening the file.”);
printf (“\n The squares of the numbers / contents OUTPUT_FILE are:\n”);
out = fopen (OUTPUT_FILE, “r”);
if (out != NULL)
{
for (i = 0; i < N; i++)
{
for (j = 0; j < N; j++)
num[i] = NULL;
fgets (num, size, out);
fputs (num, stdout);
}
fclose (out);
}
else
printf (“\n Error in opening the file.”);
printf (“\n The numbers are written in C:\\TC\\BIN\\number.txt”);
printf (“\n The squares are written in C:\\TC\\BIN\\square.txt”);
printf (“\n Floating-point numbers are also allowed.”);
printf (“\nPress any key to exit”);
getch ( );
}