Reading, Processing & Outputting numbers from files in C [closed] - c

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 8 years ago.
Improve this question
Before I go on a mission to write some code, I was hoping someone could confirm the following is possible (or at least fairly simple) to do.
I am wanting to read a file containing numbers that are in 9 columns (separated by a single space) and many rows. The second column is ordered numerically, from largest to smaller. I want to discard all rows that contain below a specified number in this second column and then generate a new file and output just the top rows that conform to this rule.
Additionally, I would like to add a 10th column that is the result of a calculation between 2 other columns.
Is this done using arrays?
Many thanks in advance.

This is trivial in awk. Suppose $N is a shell variable that contains the minimum value you want from the second column, and you want to make column 10 the sum of columns 3 and 5:
awk '$2 > '$N'{ $10 = $3 + $5 }1' input-file
This outputs all of the rows. Pipe the output to head to reduce the number of lines output, or add a counter in the awk script. If you write C code to do this, you are wasting your time unless it is an exercise to help learn C.
On the other hand, it's pretty straightforward in C. For simplicity, assume you only have 2 columns:
int c[2];
do {
rc = scanf( "%d %d", c, c + 1 );
if( c[1] > N && rc == 2 )
printf( "%d %d %d", c[0], c[1], c[0] + c[1] );
} while( rc > 0 );

The most strait-forward approach is probably to convert each column within the file into an array, then manipulate it as you describe from there.
Keep in mind, the file stores characters not integers, make sure you allocate your arrays accordingly to what you desire to store.
You may also find this question discussing the conversion of characters to integers useful.

Related

How can I delete the first zero(s) in a string? (Without using atoi) [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 3 years ago.
Improve this question
I was making a script that is calculating the additions between two natural numbers which decimal lengths should be smaller or same with 10000, and printing a result of the sum.
Of course, there ain't any variable type that can hold a integer which length is 10000 in C.
So, I made the program by utilizing the simple additions' calculating logic that all we learn in a school when we were young. And also, I just should use strings to get those gigantic numbers.
But some results were starting with zero. I knew why did the zero appeared there, but I did prefer to have a result that is like "1234", not "01234". By the way, all other stuffs were perfect.
I needed a function that gets input as string, and erases a single zero starts with a string if it exists.
And could you make it instead of me, please? You should probably consider that the strings we will deal with can have such a length that is smaller or same with 10000.
Maybe this:
char * f( char * str )
{
while ( *str == '0' && str[1] )
str++; // skips all zero-s when it is not last character in string
return str;
}

I don't know what to put in the place of β and α in order to print all 3 digit numbers different from 0 and unique [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 3 years ago.
Improve this question
I don't get what I should put in the place of: "α" and "β" in order to print all the 3 digit numbers which are different from 0 and from one another.
It is required to replace those 2 variables, with some code
We are entering G(0)!!!
It's from an exam paper, I really don't get it, please help.
void G(int k)
{int i;
for(i=1;i<=α;i++)
{ p[k]=i;
if(β)G(k+1);
else
printf("%d%d%d\n",p[0],p[1],p[2]);
}
}
For any of this to make sense, it must be that p is declared as a global int array of dimension at least 3. I assume for the purposes of this answer that it is in fact so declared.
Note that the function sets p[k] = i, but it later reads back only p[0], p[1], and p[2]. This should give you a pretty good idea about what makes sense for expression β, which controls whether to recurse (increasing k) or print.
Note also that the function sets p[k] = i, and that when it reads back those p[k] for various k, it wants to get values ranging from 1 to 9 (no more and no less). This should give you a pretty good idea of what expression makes sense for α, the inclusive upper bound on i.
Having figured those out, it remains to satisfy yourself that the natural substitutions for those expressions indeed produce a resulting function that behaves as required when initially called as G(0). I suspect that you will find that easier than you did discerning the needed expressions.
(Details are left as an exercise.)

Matrix in C without arrays [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Hello my coding teacher give us this exercise:
"Write a C program that, considering two values row and col (both int) chosen by the user, prints a matrix composed by row rows and col columns in which the first element is 1 and every next element is the previous one incremented by one."
I know that a matrix can be composed with arrays but we haven't study them yet so I have to make that only using basic C functions. How can I do?
It is true that, arrays can be used to store matrices like data in memory.
In your case, yout don't have to store anything. The problem is only about displaying matrix.
Please try to implement following steps in C.
Initialize counter to 1
For i = 1 to row
For j = 1 to col
Display counter
Increment counter
Put a line break
That's all.
Try this on a bit of paper.
Choose rows, say 2, and columns say 3.
You need a current value, starting at 1.
Write this down
1
Now move a bit and write the next value
1 2
Same again
1 2 3
... keep an eye on how many numbers you have printed out... We're at the 3 columns now.
So, print a new line '\n' and continue
1 2 3
4
This might end up being a bit wonky if the numbers get big, but you need a current_value starting at 1, and a loop, over rows and columns.
You can walk over the numbers and print as you go, rather than storing them.
int current_value = 1;
for(int row=0; row < rows; ++row)
{
for(int column = 0; column < columns; ++column)
{
printf("%i ", current_value++);
}
printf("\n");
}
Allocate memory for the matrix elements using malloc(). You'll need columns * rows * element size bytes.
malloc() will return you a pointer to the memory.
Use pointer arithmetic to access the elements.

Finding all solutions to equation using recursion [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I've been given a task to write program in C using recursion. The program is given an equation as a string, such as "123+123=246".
My task is to determine, whether the equation is right. The catch is, that numbers in the equation are sometimes replaced with a '?', for example "1??+??3=??6". Using recursion, I need to sum all possibilities, when the '?' is replaced with a digit and the equation is right.
Obviously, the solution will be based on trying out all possibilities and only selecting those, that make up the right equation. But I have no idea, how to implement it.
Could anyone give me a hint or reply with a piece of code I could base my solution on ?
Thanks very much !
Here's a general idea:
Basically we want to first of all be able to determine if the equation is right or not
Implement this function
int eval(char * string )
This will return 1 for true 0 for false and -1 when there are still '?'
Now we want write our recursion it will return a string and take a string
char * recursion (char * string)
First we need to see if the string holds a full equation.
Int res = eval(string);
if(res == 1)return string;
else if(res == 0)return "";
If it didn't stop yet that means that it can not determine because of the '?' , we need to find a way to kill them.
etch '?' can be 0 or 1 or 2 or 3 or 4 or 5 or 6 or 7 or 8 or 9
Let's do a for loop
But first implement the method to replace the first '?' with a number,
char * Replace(char* string,int num);
After you've implemented this we create our for loop
for (int i = 0; i< 10 ; i++){
char * result =recursion(Replace(string , I));
if(Eval(result)==1) ;//we found a right answer add it to our return
}
return ""+ [all right answers we found if we even found ];
Good luck learning !

print the changed variable before the calculation is done [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 8 years ago.
Improve this question
in a c program, i want the variable 'count' to be printed at the beginning of the program. But the calculation for the value of 'count' is done later. How do you accomplish this?
count = 0;
printf("the value of count is : %d", count);
count = 20;
I know in this case, the output is 0. But I need 20 to be printed.
The idea of program flow is that commands are executed in a certain order. You don't expect the waiter to bring you your meal before you have told him what you want to eat - but that seems to be what you are asking.
Of course the order of lines in a file is not necessarily the order of execution: you have have a line "at the start of the file" that is executed later: for example
#include <stdio.h>
// we define the print statement here:
void printCount(count) {
printf("the count is now %d\n", count);
}
int main(void) {
int count = 20;
printCount(count); // but we don't execute it until we get here...
return 0;
}
Now your "print" statement occurs (in the file) before you assign (calculate) count - but of course they are being executed in the correct order.
afterthought
If it's a case of printing "the number of cases is n", you could of course do
printf("the number of cases is ");
cases = 5; // whatever math is needed happens here...
printf("%d\n", cases);
and the result is
the number of cases is 5
just as you wanted... this works because there was no carriage return after printing "the number of cases is" - so the number follows when you have figured it out.
edit
Reading through the question and comments one more time I think I understand what your issue is. You have a loop that counts a number of inputs (say the number of lines in a file) and want to print both the total number of cases (not known before the loop) and something about each case (discovered during the loop) but without having to loop over all the data twice. There is a way to do this, using a print buffer. If data access is really slow and looping twice would be prohibitive, this might be an option. You would want to initialize a "sufficiently large" print buffer in memory and use snprintfto create the string you need. In reality you will "loop over" the bytes in the output string twice but there is minimal performance penalty (compared to everything else). Incomplete example:
int count=0,num, sofar=0;
char buf[2000];
// assume file is opened and handle is fp
while(true){
if (fscanf(fp, "%d", &num) <1) break;
sofar+=snprintf(buf+sofar, "%d\n", 2*num); // some "math" on number for each "case"...
count++;
}
printf("There were %d lines\n", count);
printf("Here they are multiplied by two:\n");
printf("%s\n", buf);
Obviously the above is incomplete - you need to check for errors, open/close the file, etc - I am just trying to point out the principle - this way you only loop through the data (file) once but print the count before the contents.
you can't print 20. how can you print a variable before its get initialized?

Resources