How to store this kind of data in an array - c

The input consists of multiple lines.
The first line contains a number n which indicates that the number of rows in the Pascal’s triangle will be n+1.
The second line contains a number m which indicates the number of transactions to be performed on the Pascal’s triangle. Each transaction is given in a separate line. A transaction is a space separated list of integers. The first integer in each list indicates the row number, say R, and the rest of the integers in the list indicate the indices of values in row R. For each transaction, you have to compute the sum of given coefficients in the given row R.
Example: Input will be given in the following format:
5
3
3 1 2
5 1 1 1 4
4 2 3 2
what should be done to store the values of transition lines like
3 1 2
5 1 1 1 4
4 2 3 2
under a single array variable.So that it can be passed to a function completely.

If you make a structure like this you might be able to do what you are trying to do. You can pass structure to function to compute sum of each line.
struct pascaltirangle
{
int size; //The no of lines
int* no_transactions; //To store no of transactions of each line
int** contents; //To store contents of each line. No of contents in line determined by transaction[i]
} dat;
//code to take input of size
dat.no_transactions=(int*)malloc(sizeof(int) * (dat.size+1));
//code to take no of transaction for each line
for(int i=0;i<=dat.size;i++)
contents[i]=malloc(sizeof(int)*dat.no_transaction[i]);
//code to take input for contents[i][j]

It simply adds all the transactions for a line using recursive function.
#include <stdlib.h>
#include <stdio.h>
int add_transaction(int *contents,int size)
{
if(!size)
return 0;
return (*contents + add_transaction(contents+1,size-1));
}
void main()
{
int size; //The no of lines
int* no_transaction; //To store no of transactions of each line
int** contents; //To store contents of each line. No of contents in line determined by transaction[i]
int c1,c2;
printf("Give size of triangle :");
scanf("%d",&size);
no_transaction=(int*)malloc(sizeof(int) * (size+1));
contents=(int**)malloc(sizeof(int)*(size+1));
for(c1=0;c1<=size;c1++)
{
printf("\nGive no of transaction for line no %d :",c1+1);
scanf("%d",no_transaction+c1);
contents[c1]=(int*)malloc(sizeof(int)*no_transaction[c1]);
for(c2=0;c2<no_transaction[c1];c2++)
{
printf("\tFor line %d give transaction no %d :",c1+1,c2+1);
scanf("%d",contents[c1]+c2);
}
}
printf("\nThe sum of the series is :");
for(c1=0;c1<=size;c1++)
{
if(c1)
printf("+ %d ",add_transaction(contents[c1],no_transaction[c1]));
else
printf(" %d",add_transaction(contents[c1],no_transaction[c1]));
}
//Code to free the allocated memory.
}

Related

Print a matrix line from a sparse matrix saved without 'zeros'

How do I print a matrix line between 2 column indexs when I only have the non-zero indexes saved in a struct?
I need to basically, given the right most index of a matrix and the left most index of a matrix, print that matrix line between both values if there's at least one index in that line that isn't zero and if the line I want to print is between the row's bound.
I have a structure in which I store my row, column and value from each input, so that I don't have to generate a huge matrix full of 'zeros' and I have a variable that counts how many values I have stored.
int searchForLine(unsigned int l){
int i;
for(i=0;i<matrixcount;i++){
if((auxMatrix[i].line == l)&&(auxMatrix[i].column<=workingMatrix.maxCol)&&(auxMatrix[i].column>= workingMatrix.minCol))
return (int)auxMatrix[i].value;
}
return (int)workingMatrix.zero;
}
void print_line(){
unsigned int ii,i,userLine;
scanf("%u", &userLine);
if((userLine<workingMatrix.minLine) || (userLine>workingMatrix.maxLine)){
printf("empty line\n");
}
else{
for(ii=0;ii<matrixcount;ii++){
if(auxMatrix[ii].line!=userLine){
printf("empty line\n");break;
}else{;}
}
for(i=workingMatrix.minCol;i<workingMatrix.maxCol;i++){
printf("%u ",searchForLine(userLine));
}
}
printf("\n");
}
if the input is lets say
3 3 3.0
3 0 4.0
print_line(3)->
4.0 0.0 0.0 3.0
My current code prints only 0.0's

Creating an array in C

I am new to programming and i have been learning C the past few months.
I am working on a program that stores pairs of integers in an array. The program prompts the user to enter the number of pairs to be entered, and then I need to allocate storage for the array and then the user enters the pairs line by line to be stored in the array. The program needs to access these pairs to perform operations on later.
I am having trouble trying to set this up. How can I create this kind of data set, in which each member contains a pair of integers, without knowing the initial size of the array?
There is no built-in support for dynamic array in C. The type that you need is a pointer to your pairs that will be allocated regarding the user choice.
I have written a simple sample code from your description, to help you to understand dynamic allocations.
#include <stdio.h>
#include <stdlib.h>
struct MyPair
{
int first;
int second;
};
int main()
{
int nPairCount=0;
struct MyPair *pPairs = NULL;
// .... prompt from the user
// let's say we have a nPairCount>0
// We allocate a memory space in the heap that will be able to store
// nPairCount pairs contiguously.
pPairs = malloc(nPairCount*sizeof(struct MyPair));
if(pPairs == NULL)
{
// LOG ERROR, THERE IS NOT ENOUGH MEMORY TO ALLOCATE YOUR PAIRS
return -1;
}
for(int i= 0; i<nPairCount; ++i)
{
// you can access the i-th pair in memory thanks to [] operator
// Fill the currentPair
// pPairs[i].first = ... ;
// pPairs[i].second= ... ;
}
// Do your process
// Do not forget to free your pairs from memory
free(pPairs);
return 0;
}
I don't think that there is a bucket function available in c. But you could create an array that has the number of elements entered by the user.
#include<stdio.h>
int main(){
int a,i;
printf("Enter the number of pairs: ");
scanf("%d",&a);
double b[a*2];\\note that a is number of pairs, so 2a will make it elements
printf("Enter the numbers: \n");
for(i=0;i<(2*a-1);i=i+2)
{
scanf("%lf %lf",&b[i],&b[i+1]);
}
printf("The pairs entered by you are:\n ");
for(i=0;i<(2*a-1);i=i+2)
{
printf("%lf and %lf\n ",b[i],b[i+1]);
}
return 0;
}
All I have done is take up 2 elements at a time and assign them consecutive arrays and then print them pairwise.
Sample output:
Enter the number of pairs: 3
Enter the numbers:
12 14
45 456
321 568
The pairs entered by you are:
12.000000 and 14.000000
45.000000 and 456.000000
321.000000 and 568.000000

C reading input from a file into 2d array - variable number of lines per row

I am reading a list of grades from a txt file into an array. It worked fine when reading user input, but I'm having trouble reading each line when scanning from file. The number of students is variable. The number of grades per student is variable. I have no trouble reading the number of students and number of assignments, but when reading from file I'm having trouble pulling the int (grade) from each line for each student. The input may be like a or b (or any larger number of students/assignments):
txt-example1 (the comments including and after // are my own and not in txt file)
2 //number of students
3 //the number of grades per student (will match the number of grade rows below)
theo alvin //the number of names will match the number of students
75 60
89 90
79 95
txt-example2
3
4
theo alvin simon
78 85 90
85 96 76
77 99 100
88 55 92
I can put the names into 1 dimension of a 2d array (I'll use the second dimension later to print - no problems with that part). I want to get the grades into a 2d array. Here is what I have
#include<stdio.h>
#include<string.h>
int numStus;
int numGrades;
int main()
{
FILE* inputFile;
char stuNames[numStus][10];
int grades[numGrades][numStus];
inputFile = fopen("testData.txt","r"); //assume inputFile has data from Ex 1 or 2 above
fscanf(inputFile,"%d",&numStus);
fscanf(inputFile,"%d",&numGrades);
int i;
int j;
for (i=0; i<numStus; i++)
{
fscanf(inputFile,"%s",&stuNames[i]);
}
//here is where I'm having trouble
for(i=0;i<numGrades;i++)
{
for(j=0;j<numStus; j++)
{
//I want to use fscanf, but don't know how to account for carriage returns to iterate into next part of array
}
}
}
What worked when getting from user input:
int i;
int j;
int k;
for (i=0; i<numGrades; i++)
{
for (j=0; j<numStus; j++)
{
printf("Enter grade for Assignemnt %d for ",i)
for(k=0;k<10;k++)
{
printf("%c",stuNames[j][k]);
}
scanf("%d",&grades[i][j]);
}
}
The part immediately above worked well for user input grades. When getting the same input from a file I'm not sure how to get the grades into the proper dimensions. Any advice on how to account for the newline/CR to increment the array would be very much appreciated. Thanks.
The scanf can be used in the nested loops as usually for reading a single value, since the carrige return is skipped as a space, for example: fscanf(inputFile,"%d",&grades[i][j]);
However, the arrays stuNames and grades must be initialized only after reading numStus and numGrades, for example:
...
fscanf(inputFile,"%d",&numStus);
char stuNames[numStus][10];
fscanf(inputFile,"%d",&numGrades);
int grades[numGrades][numStus];
...
That trick is not allowed in ANSI C. In that case dynamic memory allocation should be used.
You have trouble much earlier than you think. You can't use uninitialized variables when you are declaring your arrays. In your working example you don't show how you allocated your arrays. Were they fixed size? Whatever you did there would probably work in your new program.
You first need to read the amount of students and amount of grades.
A uninitialized variable like int foo; has a "random" value.
You need to initialize the variable like int foo = 0;.
Knowing this lets analyze your code step by step.
int numStus; //numStus gets random value
int numGrades; //numGrades gets random value
int main()
{
FILE* inputFile;
char stuNames[numStus][10]; //random amount gets generated
int grades[numGrades][numStus]; //variable gets random value
fscanf(inputFile,"%d",&numStus); //numStus gets actual value
fscanf(inputFile,"%d",&numGrades); //numGrades gets actual value
C is a language which handles things in order.
This means that the array keeps the size is has been given.
The code can be fixed by switching around the statements like this:
int numStus; //numStus gets random value
int numGrades; //numGrades gets random value
int main()
{
FILE* inputFile;
fscanf(inputFile,"%d",&numStus); //numStus gets actual value
fscanf(inputFile,"%d",&numGrades); //numGrades gets actual value
char stuNames[numStus][10]; //array of wanted size gets created
int grades[numGrades][numStus]; //random amount gets
I hope this helps, may you have any questions ask them

Ascending order arrangement of numbers of a file

How to read a file which contains two columns and sort the first column numbers in ascending order and to print them with their corresponnding 2nd column values using C ?
fopen opens a file.
fscanf reads from a file and splits what is read into bits according to a format specification (e.g. "%d %s" means an integer followed by whitespace followed by a string of non-whitespace characters).
qsort is a standard library function that will sort an array. It sorts the array by comparing one item to another item. You give it the name of a function (which you write) that does this comparison.
I encourage you to read the manual pages for these functions if you are not familiar with them.
The program below uses all this to:
Open a file test.txt
Read lines from the file into an array arr
Sort the array using qsort, using the rowcmp function (rowcmp looks at the numerical value in the first column to determine whether one element is greater than, equal to, or less than another element)
Print out the elements of the array.
The code...
#include <stdio.h>
#include <stdlib.h>
#define MAXLEN 100
#define MAXITEMS 100
// A row has two columns, the first is a number and
// the second is any string of up to MAXLEN chars
struct row {
int col1;
char col2[MAXLEN];
};
// Function to do comparison of rows
// Sorts numerically on the value in the first column
int rowcmp(struct row * r1, struct row * r2) {
if (r1->col1 < r2->col1) return -1;
if (r1->col1 == r2->col1) return 0;
return 1;
}
int main(int argc, char ** argv) {
struct row arr[MAXITEMS]; // up to MAXITEMS rows
int rows = 0, i;
FILE * stream = fopen("test.txt", "r");
// Read in rows and put first and second columns into struct,
// building up an array
while (fscanf(stream, "%d %s", &(arr[rows].col1), arr[rows].col2) !=EOF) {
rows++;
}
// Sort the array using the rowcmp function to compare items
qsort(&arr[0], rows, sizeof(struct row), (__compar_fn_t)rowcmp);
fclose(stream);
// Print the sorted array
for (i=0; i<rows; i++) {
printf("%d\t%s\n", arr[i].col1, arr[i].col2);
}
}
With input file:
1 apple
3 cucumbers
21 dates
7 figs
4 grapes
output is
1 apple
3 cucumbers
4 grapes
7 figs
21 dates

Taking Input from a file Travelling Salesman in C

I am working on TSP which takes large number of city like 100 ,500 etc. I have wrote a code using greedy algorithm and works fine using command line arguments . But I need to take input from a file which has the below given format.
First line is the number of cities
Second line is 'euclidean' or'not euclidean'
Now from 3rd line we have co-ordinate of n cities (float)
And after cordinates we have nxn distance matrix for each city.
Something like that lets take number of city be 5
5
euclidean
1.3 4.2
1.6 -3.5
1.4 1.5
6.4 3.6
4 2.4
now a 5x5 cost matrix.
How do i store all the input in array ? (n,euclidean/non-euclidean,cordinates,matrix) After taking the input i need to work on the matrix itself.
I wouldn't store it all in one single array. First of all, worry about reading the number of cities. After you know that, you can allocate 2 arrays: one of them holds a structure with the coordinates for each city, and the other is a 2D array where you store the costs.
This assumes that you look at the cities and count them: in your example, the city with coordinates 1.3 4.2 will be city 0 (stored in position 0 of the array); the city with 1.6 -3.5 will be on position 1, etc. So, basically you'll be doing:
Read number of cities, x;
Read whether it's euclidean or not, store that in some variable;
Allocate an array cities of x elements, and another
bi-dimensional array costs of x by x;
Read each city's coordinates, and store them in cities[i] (cities
shall be an array of a structure with 2 floats to store the
coordinates);
For each line i (i starting on 0) and for each column j in that line
(also starting on 0), set cost[i][j] to whatever value is in the
input.
Here's the code that implements this approach:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFSIZE 32
struct city {
float c1;
float c2;
};
int main(void) {
int citiesNo, i, j;
struct city *cities;
float **cost;
char line[BUFSIZE], euclidean[BUFSIZE];
fgets(line, BUFSIZE, stdin);
citiesNo = atoi(line);
fgets(line, BUFSIZE, stdin);
strcpy(euclidean, line);
cities = malloc(sizeof(struct city)*citiesNo);
cost = malloc(sizeof(float *)*citiesNo);
for (i = 0; i < citiesNo; i++)
cost[i] = malloc(sizeof(float)*citiesNo);
/* Read coordinates */
for (i = 0; i < citiesNo; i++)
scanf("%f %f", &(cities[i].c1), &(cities[i].c2));
/* Read costs */
for (i = 0; i < citiesNo; i++)
for (j = 0; j < citiesNo; j++)
scanf("%f", &(cost[i][j]));
/* Everything is stored now... */
return 0;
}
fgets was used in the beginning because scanf("%d", &citiesNo) would leave a newline in the buffer, and the subsequent fgets() call would return an empty line. If you prefer, you can replace both fgets() by scanf(), I just didn't read the euclidean string with scanf because it makes no buffer size checking. If your input is always well formed, this is not a problem.
After this code runs, you have a string with "euclidean" or "not euclidean" stored in the variable euclidean.

Resources