How to take input from a file using a C program? - c

I have to take input from a file and convert the number from kelvin to fahrenheit(vice versa), using a "C" program.
Requirements:
The conversion and numeric outputs must take place in the compiled program.
The script will give the user an option to convert either kelvin to fahrenheit or fahrenheit to kelvin.
Numbers need to be rounded to the nearest tenth.
Input file:
0
32
100
212
108
1243
3000
85
22
2388
235
Output File:
Fahrenheit Temperature Kelvin Temperature
0 256
32 273
100 310
212 373
108 315
1243 945
3000 1921
85 302
22 268
2388 1581
235 385
"C" Program:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
//assign the variables used in this program
int temp, conv_temp, conv_type;
//assign the input options to variables
conv_type = atoi(argv[1]);
temp = atoi(argv[2]);
//convert the temps
// if input number is 1, then convert from kelvin to fahrenheit
// if input number is anything else, convert from fahrenheit to kelvin
if(conv_temp == 1)
conv_temp = (((temp - 273) * 1.8) + 32);
else
conv_temp = ((((temp - 32) *5) / 9) + 273);
//print the data
printf(" %3.1i %3.1i\n",temp, conv_temp);
//end of main function
return 0;
}

You have several issues here.
First: you declare "conv_type" and initialize it, but fail to do anything with it.
conv_type;
conv_type = atoi(argv[1]);
Second: before you give a value for "conv_temp" you are attempting to use it in an if statement.
if(conv_temp == 1)
conv_temp = (((temp - 273) * 1.8) + 32);
else
conv_temp = ((((temp - 32) *5) / 9) + 273);
Third: in the problem statement, you state you have to do file I/O.
Here is a link to a tutorial on file IO in C.

Related

how to display the table in c? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 months ago.
Improve this question
#include <stdio.h>
#include <math.h>
int main(void)
{
// input value
int num, lower, upper;
double squareroot;
int square;
int cube;
printf("enter your number:\n");
scanf_s("%d", &num);
do
{
printf("the lower value limit is ");
scanf_s("%d", &lower);
} while (lower < 0 || lower > 50);
do
{
printf("the upper value limit is ");
scanf_s("%d", &upper);
} while (upper < 0 || upper > 50);
// the formular to find the squareroot, square, cube
squareroot = sqrt(num);
square = num * num;
cube = num * num * num;
//a for loop
for (num = 0; num <= upper; num++) {
printf("*base number* || *square root* || *square* || *cube*\n");
printf("*%d* || *%f* || *%ld* || *%ld*\n",
lower, squareroot, square, cube);
}
return 0;
}
i try to make a table to display the base number, square root, square, and cube
and set a limit for the table.
for example, if I input the lower number is 1 and the upper number is 5 then the table will stop at 5 then display the square root, square, and cube
At least this problem:
Mismatched specifiers/type
int square;
int cube;
...
printf("*%d* || *%f* || *%ld* || *%ld*\n",
lower, squareroot, square, cube);
Use "%d" with int, not "%ld".
Move assignments
Following assignments need to be inside the loop.
for (num = 0; num <= upper; num++) {
square = num * num;
cube = num * num * num;
Save time. Enable all compiler warnings
Try the Below Code Make all Changes I have added Comments to Clarify why I made The
#include <stdio.h>
#include <math.h>
int main(void)
{
// input value
int lower, upper;
double squareroot;
int square;
int cube;
//Read the Limits First
printf("Enter the Lower Limit: ");
scanf("%d", &lower);
printf("Enter the Upper Limit: ");
scanf("%d", &upper);
//Instead of Declaring an Entire Loop You Can Just Use an If Statement this Reduces Code Complexity
//You can also Set Your Limits
if(upper > 0 && upper < 50 && lower > 0 && lower < 50)
{
//THen Enter Actual Code
//Also Dont Set Lower to 0 It will Change Your Actual Value Instead Take another Loop Var
for (int i = lower; i <= upper; i++)
{
//Then Perform all Functions on i
squareroot = sqrt(i);
square = i * i;
cube = i * i * i;
printf("*base number* || *square root* || *square* || *cube*\n");
printf("*%d* || *%f* || *%d* || *%d*\n", i, squareroot, square, cube);
}
}
return 0;
}
Several issues:
You go to the trouble of asking for lower, but you don't use it to control your loop - your loop should befor( int num = lower; num <= upper; num++)
{
...
}
Put another way, if you always intend for your loop to start from zero, then you don't need lower at all.
You need compute the square root, square, and cube of num for each iteration of the loop. Instead, you're doing it once before the loop and just printing those same values over and over again;
You only need to print your table header once, outside the body of the loop;
You can compute your square root, square, and cube all as part of the printf statement:
printf( "%d %f %d %d\n", num, sqrt((double) num), num * num, num * num * num );
Field width specifiers are your friends - you can tell printf exactly how wide you want each column to be. Example:
printf( "%6d%12.2f%12d%12d", num, sqrt((double) num), num * num, num * num * num );
This means the column for num is 6 characters wide, the column for square root is 12 characters wide, with 3 characters reserved for the decimal point and two following digits, and the columns for square and cube are 12 characters wide. Example:
printf( "%6s%12s%12s%12s\n", "base", "root", "square", "cube" );
printf( "%6s%12s%12s%12s\n", "----", "----", "------", "----" );
for (int i = lower; i <= upper; i++ )
printf( "%6d%12.2f%12d%12d\n", i, sqrt( (double) i ), i*i, i*i*i );
Which gives output like this (lower == 1, upper == 10):
base root square cube
---- ---- ------ ----
1 1.00 1 1
2 1.41 4 8
3 1.73 9 27
4 2.00 16 64
5 2.24 25 125
6 2.45 36 216
7 2.65 49 343
8 2.83 64 512
9 3.00 81 729
10 3.16 100 1000
Full example:
#include <stdio.h>
#include <math.h>
int main( void )
{
int lower = 0, upper = 0;
printf( "Gimme a lower value: " );
while ( scanf( "%d", &lower ) != 1 || (lower < 0 || lower > 50 ))
{
/**
* Clear any non-numeric characters from the input stream
*/
while ( getchar() != '\n' )
; // empty loop
printf( "Nope, try again: " );
}
printf( "Gimme an upper value: " );
while ( scanf( "%d", &upper ) != 1 || (upper < lower || upper > 50 ))
{
while( getchar() != '\n' )
; // empty loop
printf( "Nope, try again: " );
}
printf( "%6s%12s%12s%12s\n", "base", "root", "square", "cube" );
printf( "%6s%12s%12s%12s\n", "----", "----", "------", "----" );
for (int i = lower; i <= upper; i++ )
printf( "%6d%12.2f%12d%12d\n", i, sqrt( (double) i ), i*i, i*i*i );
return 0;
}
I've written the input section such that it will reject inputs like foo or a123. It will not properly handle inputs like 12w4, but that would make the example more complicated than it needs to be (you're not asking about input validation, you're asking about computation and formatting). Example run:
$ ./table
Gimme a lower value: foo
Nope, try again: a123
Nope, try again: 123
Nope, try again: 1
Gimme an upper value: 100
Nope, try again: 50
base root square cube
---- ---- ------ ----
1 1.00 1 1
2 1.41 4 8
3 1.73 9 27
4 2.00 16 64
5 2.24 25 125
6 2.45 36 216
7 2.65 49 343
8 2.83 64 512
9 3.00 81 729
10 3.16 100 1000
11 3.32 121 1331
12 3.46 144 1728
13 3.61 169 2197
14 3.74 196 2744
15 3.87 225 3375
16 4.00 256 4096
17 4.12 289 4913
18 4.24 324 5832
19 4.36 361 6859
20 4.47 400 8000
21 4.58 441 9261
22 4.69 484 10648
23 4.80 529 12167
24 4.90 576 13824
25 5.00 625 15625
26 5.10 676 17576
27 5.20 729 19683
28 5.29 784 21952
29 5.39 841 24389
30 5.48 900 27000
31 5.57 961 29791
32 5.66 1024 32768
33 5.74 1089 35937
34 5.83 1156 39304
35 5.92 1225 42875
36 6.00 1296 46656
37 6.08 1369 50653
38 6.16 1444 54872
39 6.24 1521 59319
40 6.32 1600 64000
41 6.40 1681 68921
42 6.48 1764 74088
43 6.56 1849 79507
44 6.63 1936 85184
45 6.71 2025 91125
46 6.78 2116 97336
47 6.86 2209 103823
48 6.93 2304 110592
49 7.00 2401 117649
50 7.07 2500 125000

Same C program but different execution time

I wrote a C program to find out the prime numbers in a given parameter. But for the same input and output, the program has different execution times.
#include <stdio.h>
int main(int argc, char const *argv[])
{
int n,p,k;
scanf("%d", &n);
int prime[n+1];
for (p = 2; p <= n; ++p)
{
if (prime[p]!=-1)
{
for (int i = p*2,k=2; i < n; k++,i=k*p)
{
prime[i]=-1;
}
}
}
for (int i = 1; i < n ; ++i)
{
if (prime[i]!=-1)
{
printf("%d ",i );
}
}
return 0;
}
What you are measuring is the time it takes the user to type the input, i.e. 200.
Calculating the result after the input is given will not take 2 to 5 sec on any modern computer.
It is true that "the computer may be doing other things" and therefore give varying execution time - but that won't give you a 3 sec increase in code like this.
To make the measurement more reliable, you need to "remove" the user input, i.e. remove the scanf.
Instead of scanf you should give the value of n as a command line argument.
Use code like
// scanf("%d", &n); Dont use scanf but use lines like the two below.
if (argc < 2) exit(1); // user error - no number given
n = atoi(argv[1]); // convert command line arg to integer
And start the program like:
test2.exe 200
Now the measured time will be much smaller than 2-5 sec and you won't see execution time vary so much.
Note: While atoi is simple to use, it's in general better to use strtol
The execution of a program on an environment is not dependent only on the code but on some other environment variables such as CPU load.
CLOCKS_PER_SEC is a constant which is declared in <time.h>. To get the CPU time used by a task within a C application, use:
clock_t begin = clock();
/* Do the work. */
clock_t end = clock();
double time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
For your program, You can probably check the
CPU Time took on input.
CPU Time is taken to generate Prime Number
...... and so on
#include <stdio.h>
#include<time.h>
int main(int argc, char const *argv[])
{
int n,p,k;
clock_t t , t1, t2;
t = clock();
scanf("%d", &n);
t = clock() - t;
double time_taken = ((double)t)/CLOCKS_PER_SEC; // in seconds
printf("Took %f seconds to take the input\n", time_taken);
t2 = clock();
int prime[n+1];
for (p = 2; p <= n; ++p)
{
if (prime[p]!=-1)
{
for (int i = p*2,k=2; i < n; k++,i=k*p)
{
prime[i]=-1;
}
}
}
t2 = clock() - t2;
double time_taken2 = ((double)t2)/CLOCKS_PER_SEC; // in seconds
printf("Took %f seconds for generating the prime number \n", time_taken2);
for (int i = 1; i < n ; ++i)
{
if (prime[i]!=-1)
{
printf("%d ",i );
}
}
return 0;
}
Output:
200
Took 0.000075 seconds to take the input
Took 0.000004 seconds for generating the prime number
1 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 1
13 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199
The time is depended on your CPU load. For details please visit here

What are these numbers that convert to text?

/***
* Author: Omar IRAQI
*/
#include <stdio.h>
#include <stdlib.h>
#define N 11
int main(void) {
int i, *p, encoded_message[] = {1634558290, 544104804, 1701994827, 539782501, 1918985572,
1970565920, 1953391972, 1226845811, 1936289056, 1870209139, 8565};
char *message;
printf("%s\n", (char*)encoded_message);
/**
* Let's say it again!
*/
message = (char*)malloc(N * sizeof(int));
p = (int*)message;
for (i=0; i < N; i++, p++)
*p = encoded_message[i];
printf("%s\n", message);
return 0;
}
this outputs the message twice:
Ramadan Kareem, dear students. I miss you!
I was wondering what these encoded numbers are since they don't match with ASCII code
Each int should be split into 4 bytes to recover the individual ascii codes. You could simply print each int as hex.
You can also calculate:
1634558290 % 256
(1634558290 >> 8) % 256
(1634558290 >> 16) % 256
and so on.
You have 11 x 4 byte integers for a total of 44 bytes. This corresponds closely to the length of the message.
1 634 558 290 = 0x616D6152
52 : R
61 : a
6D : m
61 : a
Lookup little endian vs big endian for why the bytes are inverted.

conversion table from feet and inches to cm

I need to write a program which prints the conversion table from feet and inches to centimetres. The numbers printed in row i (counting from zero), column j (counting from zero) of the table should be the cm equivalent of i feet and j inches. i should go from 0 to 7, and j from 0 to 11. Each column should be five characters wide, and the cm figures should be rounded to the nearest integer.
The example of required output is given below:
0 3 5 8 10 13
30 33 36 38 41
61 64 66 69 71
91 94 97 99 102
The code I have prints only one row of inches and column of feet but I don't know how to make into table without producing lots of irrelevant repetitions.
The code is:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int i,j;
int cm,p;
for (i=0; i<= 11; i++) {
cm =round(i * 2.54);
printf ("%5d",cm);
}
for (j=0; j<=7; j++) {
p =round(j* 12.0 * 2.54);
printf ("%5d\n",p);
}
return 0;
}
This produces:
0 3 5 8 10 13 15 18 20 23 25 28 0
30
61
91
122
152
183
213
What am I doing wrong?
You have one loop after the other. What you need to do is run through the inches loop every iteration of your feet loop. What you get is nested loops:
#include <stdio.h>
int main()
{
for (int feet = 0; feet <= 7; ++feet) {
for (int inches = 0; inches < 12; ++inches) {
int microns = (feet * 12 + inches) * 25400;
int rounded_cm = (microns + 5000) / 10000;
printf("%5d", rounded_cm);
}
puts("");
}
}
I've made some other changes in my version; you're encouraged to study it and understand why it does what it does (read the man page for puts(), for example). Don't just copy it and hand it in - it will be obvious it isn't your code.
An alternative approach is to use a single loop (in inches), and insert a newline when we reach the 11th inch in each foot:
#include <stdio.h>
int main()
{
for (int i = 0; i < 96; ++i) {
printf("%4d%s",
(i * 25400 + 5000) / 10000,
i%12==11 ? "\n" : " ");
}
}
(You'll want to give meaningful names to your constants; the above is written in a "code-golf" style).
Whatever you do, don't be tempted to avoid multiplying by instead adding 2.54 repeatedly in the loop. Floating-point numbers are not exact, and addition will accumulate the error.
OP needs to put the "inches" loop inside the "foot" loop as well answered by others. #Toby Speight #VHS
Code could do its "round to nearest" via the printf() statement by using "%5.0f" to control the output width and rounding.
Let code use foot/inch instead of i/j #KevinDTimm for clarity.
#include <stdio.h>
#define INCH_PER_FOOT 12
#define CM_PER_INCH 2.54
int main(void) {
// go from 0 to 7, and ...
for (int foot = 0; foot <= 7; foot++) {
// from 0 to 11
// for (int inch = 0; inch < INCH_PER_FOOT; inch++) { is more idiomatic
for (int inch = 0; inch <= 11; inch++) {
printf("%5.0f", (foot * INCH_PER_FOOT + inch) * CM_PER_INCH);
}
puts("");
}
}
Output
0 3 5 8 10 13 15 18 20 23 25 28
...
213 216 218 221 224 226 229 231 234 236 239 241
You are running your loops backwards. First you need to run through feet and then through inches. But you are having it the other way round. Check the following snipped and compare it with your code and try to understand what's wrong.
#include <stdio.h>
#include <stdlib.h>
#include <math.h> // for rounding of a number
int main()
{
int i,j;
int cm,p;
for(i=0; i<=7;i++) {
for(j=0;j<=11;j++) {
cm = round(i*30.48 + j*2.54);
printf ("%5d",cm);
}
printf("\n");
}
return 0;
}

Scanf two numbers at a time from stdout

I have a program that outputs a huge array of integers to stdout, each integer in a line. Ex:
103
104
105
107
I need to write another program that reads in that array and fill up the spaces where the number isn't an increment of 1 of the previous number. The only different between numbers is going to be 2 (105,107), which makes it easier.
This is my code to do that logic:
printf("d",num1);
if ((num2-num1) != 1)
numbetween = num1 + 1;
printf("%d", numbetween);
printf("%d", num2);
else(
printf("%d",num2);
)
So the output of this program will now be:
103
104
105
106
107
My issue is reading the numbers. I know I can do while (scanf("%hd", &num) != EOF) to read all the lines one at a time. But to do the logic that I want, I'm going to need to read two lines at a time and do computation with them, and I don't know how.
You could always just read the first and last numbers from the file, and then print everything in between.
int main( void )
{
// get the first value in the file
int start;
if ( scanf( "%d", &start ) != 1 )
exit( 1 );
// get the last value in the file
int end = start;
while ( scanf( "%d", &end ) == 1 )
;
// print the list of numbers
for ( int i = start; i <= end; i++ )
printf( "%d\n", i );
}
Read first num then add missing if needed when you read next int
#include <stdio.h>
#include <stdlib.h>
int main()
{
int previous = 0;
int num;
scanf("%hd", &previous);
while (scanf("%hd", &num) != EOF) {
for (int i = previous; i < num; i++) {
printf("%d\n" , i);
}
previous = num;
}
printf("%d\n" , previous);
return 0;
}
this input
100
102
103
105
107
110
returns this output
100
101
102
103
104
105
106
107
108
109
110
While you can read the first and last, to fill the range, what you are really doing is finding the min and max and printing all values between them inclusively. Below the names are left first and last, but they represent min and max and will cover your range regardless whether the values are entered in order. Taking that into consideration, another approach insuring you cover the limits of the range of int would be:
#include <stdio.h>
int main (void) {
int num = 0;
int first = (1U << 31) - 1; /* INT_MAX */
int last = (-first - 1); /* INT_MIN */
/* read all values saving only first (min) and last (max) */
while (scanf (" %d", &num) != EOF) {
first = num < first ? num : first;
last = num > last ? num : last;
}
/* print all values first -> last */
for (num = first; num <= last; num++)
printf ("%d\n", num);
return 0;
}
Input
$ cat dat/firstlast.txt
21
25
29
33
37
41
45
49
53
57
61
65
69
73
77
81
85
89
93
97
101
Output
$ ./bin/firstlast < dat/firstlast.txt
21
22
23
24
25
26
27
28
29
<snip>
94
95
96
97
98
99
100
101
Note: you can change the types to conform to your expected range of data.

Resources