Files and generating numbers ,c programming - c

Task is next:
After you generate 20 random numbers and read informations from file tombula.txt which contains names of users and their 9 numbers,print the first user (his/her name) who has 3 numbers from own array equal to generated numbers.
This is my part of code where i generate numbers and read from file but I don't know how to find that first person who has 3 numbers from array equal to generated numbers,if you know how to write that please help:
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include <time.h>
typedef struct
{ char name[50];
int num[8];
}someone;
void generating(int[]);
int check(int[], int);
int main(void)
{
someone *pK = NULL;
int i, j, count = 0, tip;
FILE *F;
int generated[30];
int brojac[5];
srand(time(NULL));
generating(generated);
for (int j = 0; j < 20; j++)
printf("%d ", generated[j]);
printf("\n\n\n");
F = fopen("tombula.txt", "r");
if (F == NULL)
{
printf("error!");
exit(1);
}
i = 0;
while (feof(F) == 0)
{
pK = ((someone *)realloc(pK, (i + 1)*sizeof(someone)));
fscanf(F, "%s", pK[i].name);
for (j = 0; j < 8; j++)
fscanf(F, "%d", &pK[i].num[j]);
i++;
count++;
}
i--;
count--;
for (int z = 0; z < count; z++){
printf("%s ", pK[z].name);
for (int k = 0; k < 8; k++){
printf("%d ", pK[z].num[k]);
}
printf("\n");
}
return 0;
}
void generating(int numbers[])
{
int i, tmp;
for (i = 0; i < 20; ++i)
{
tmp = rand() % 50 + 1;
if (check(numbers, tmp))
{
--i;
continue;
}
numbers[i] = tmp;
}
}
int check(int b[], int a){
int i;
int n = 8;
for (i = 0; i < 20; ++i)
{
if (b[i] == a)
return 1;
}
return 0;
}

1.You opened file in r mode.
2.In a loop (loop must work until EOF) read data stored in file using fscanf() .Store name into char array and number into integer array (As you defined in struct).
3.Inside loop check if the 3 numbers matches with the numbers generated and if they do print the persons name and use break to come out of loop.
4.After this close the file.

Related

Count number of elements in array after placing them in ascending order

I'm creating a program that reads input from an array and orders it in an ascending order. However, I also wanted to count the number of times each element appears in the array, but I'm struggling to to this. This is the code I have so far:
#include <stdlib.h>
#include <locale.h>
typedef enum _ordem {
Crescente=1
} ordem;
void troca(int *x, int *y){
int wk;
wk=*x;*x=*y;*y=wk;
}
int trocar(int x, int y, ordem dir){
if(dir == Crescente)
return x > y;
return 0;
}
void bubbleSort(int *array, int top, int fim, ordem dir){
int i, j, trocado;
for(i = top; i < fim; ++i){
trocado = 0;
for(j = top + 1; j <= fim - i; ++j)
if(trocar(array[j-1], array[j], dir)){
troca(&array[j-1], &array[j]);
trocado = 1;
}
if(trocado == 0)break;
}
}
int main(){
int vetor[100], index, ordem=1;
index=0;
setlocale(LC_ALL,"Portuguese");
printf("Introduza os nĂºmeros. Escreva -00 para parar. \n");
do{
scanf("%d", &vetor[index++]);
}while(vetor[index-1] != -00 && index < 100);
--index;
bubbleSort(vetor, 0, index-1, ordem);
{
int i;
for(i=0;i<index;++i)
printf("%d ", vetor[i]);
printf("\n");
}
return 0;
}
After the numbers have been sorted, equal numbers will be next to each other in the array. This makes it easy to count the number of times each number occurs using a single loop that iterates through the sorted array, with an extra variable that is incremented when the next element has the same number as the current element, or is reset when the next element has a different number.
The following block of code will do that:
{
int i, c;
c = 1;
for (i = 0; i < index; ++i) {
if (i < index - 1 && vetor[i] == vetor[i + 1]) {
c++;
} else {
printf("%d(x%d) ", vetor[i], c);
c = 1;
}
}
printf("\n");
}
You could create another array to store a table of the unique values with their frequency of occurrance:
struct freq {
int val;
int freq;
};
struct freq freq[100];
int nfreq = 0;
Fill the table using a loop similar to the earlier code:
{
int i, c;
c = 1;
for (i = 0; i < index; ++i) {
if (i < index - 1 && vetor[i] == vetor[i + 1]) {
c++;
} else {
freq[nfreq].val = vetor[i];
freq[nfreq].freq = c;
nfreq++;
c = 1;
}
}
}
Print the out the table with another simple loop:
{
int i;
for (i = 0; i < nfreq; i++) {
printf("%d(x%d) ", freq[i].val, freq[i].freq);
}
printf("\n");
}

Why is my selection sort output different to my input?

So i have a file called output.txt which contains a list of numbers (12365 25460 12522 22707 8714 28771 235 11401 25150 26342 0) and i want to take them and pass them through my selection sort, ive managed to open the file and read them into my program but instead when the selction sort fiishes it comes out with a list of numbers that have nothing to do with my input (although they are in order as they should be)
#include <stdio.h>
int main() {
FILE *outp;
char arr[10];
outp = fopen("output.txt", "r");
if (outp == NULL)
{
puts("Issue in opening the input file");
}
while(1)
{
if(fgets(arr, 10, outp) ==NULL)
break;
else
printf("%s", arr);
}
fclose(outp);
int n=10;
int i, j, position, swap;
for (i = 0; i < (n - 1); i++) {
position = i;
for (j = i + 1; j < n; j++) {
if (arr[position] > arr[j])
position = j;
}
if (position != i) {
swap = arr[i];
arr[i] = arr[position];
arr[position] = swap;
}
}
for (i = 0; i < n; i++)
printf("%d\n", arr[i]);
return 0;
}
You're just reading the first 10 characters in the file, and setting the elements of arr to their character codes.
You need to parse the file contents as integers.
int arr[10];
for (i = 0; i < 10; i++) {
fscanf(outp, "%d", &arr[i]);
}

I am trying to read a file into an Array and code wont output. I believe it has something to do with how im reading the file

I am trying to read a file where the first line tells the size of the array and the second line is the array elements separated by a tab. From this even will be sorted in ascending order first in a new array and odds followed in descending. So far I can't get it to output. Can anyone help?
int main(int argc, char* argv[]){
int evenArray[20];
int oddArray[20];
int n;
FILE *fp = fopen("array.txt","r");
if(fp == NULL){
return 0;
}
fscanf(fp,"%d\n",&n);
int array[n];
int i;
int countOdd = 0;
int countEven = 0;
//Scans the Doc and inputs the numbers
for(i = 0;i<n;i++)
{
fscanf(fp, "%d\t", &array[i]);
if(array[i] % 2 == 0){
evenArray[countEven] = i;
countEven++;
}
else{
oddArray[countOdd] = i;
countOdd++;
}
}
fclose(fp);
int final[n];
ascendingInsertionSort(evenArray,countEven);
descendingInsertionSort(oddArray,countOdd);
int j;
for ( j = 0; j < countEven; j++ ) {
final[ j ] = evenArray[j];
}
int k;
for ( k = countEven-1; k < n; k++ ) {
final[ k ] = oddArray[k];
}
int l;
for (l = 0; l < n; l++ ) {
printf("Element[%d] = %d\n", l, final[l] );
}
return 0;
}

Displaying the output of a sorted array causes problem

I tried applying bubble sort algorithm to an array of values.
I have 5000 values in my input, from 1 to 5000. I imported values from a text file to create the array, which worked fine. The bubble sort algorithm also worked fine.
The issue is somewhere with the output. Some values do not appear in the output at all, whereas some values are being printed multiple times. I am attaching my code and the image of the output for reference.
#include<stdio.h>
#include<conio.h>
int main() {
FILE * fp;
long int i, j, n, temp;
printf("Enter array size:");
scanf("%ld",&n);
long int array[n];
fp = fopen("5000averagecase.txt", "r");
for (i=0; i < n; ++i)
fscanf(fp,"%ld",&array[i]);
for (i=0; i < n; ++i)
for (j=0; j < n-1-i; ++j)
if (array[j] > array[j+1]) {
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
temp = 0;
}
for (i=0; i< n; ++i)
printf("%ld\t", array[i]);
return(0);
}
https://i.stack.imgur.com/ZbxVU.png
Since your file has only values from 1 to 5000 and I assume they're not sorted in any way, why don't you just make another file like this
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// shuffles an array given a pointer to the array and its length
void shuffleArray(int *array, int len) {
srand(time(NULL));
int n1, n2, tmp;
for(int i = 1;i < len - 1; i++) {
// get random two positions in the array to swap
n1 = rand() % len, n2 = rand() % len;
// just swap'em
tmp = array[n1];
array[n1] = array[n2];
array[n2] = tmp;
}
}
int main() {
FILE * fp = fopen("5000averagecase.txt", "w");
// check for file pointer validity
if(fp == NULL) {
printf("Error: can't open the file!");
exit(0);
}
// creating an array of 5000 number
int arr[5000];
// fill it from 1 to 5000
for(int i = 0;i < 5000; i++) {
arr[i] = i + 1;
}
// shuffle it
shuffleArray(arr, 5000);
// write the array in `5000averagecase.txt` for later use
for(int i = 0;i < 5000; i++) {
fprintf(fp, "%d ", arr[i]);
}
// don't forget to close the file at the end
fclose(fp);
return 0;
}
Now after executing this you get your valid file, and after executing your sorting code on it you see that it works as expected

(C) Radix Sort array from text file

I am attempting to get this queue-based radix sort to work, but I can't seem to figure out what's wrong with it. It uses a text file as the input medium and throws tons of errors when I try to compile it and run it with the text file.
Any advice would be helpful at this point.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX 10
#define SHOWPASS
//Compiled Using GNU GCC Compiler
void radixsort(int *a[], int n)
{
int i, b[MAX], m = *a[0], exp = 1;
for (i = 0; i < n; i++)
{
if (*a[i] > m)
m = a[i];
}
while (m / exp > 0)
{
int queue[10] =
{ 0 };
for (i = 0; i < n; i++)
queue[*a[i] / exp % 10]++;
for (i = 1; i < 10; i++)
queue[i] += queue[i - 1];
for (i = n - 1; i >= 0; i--)
b[--queue[*a[i] / exp % 10]] = *a[i];
for (i = 0; i < n; i++)
*a[i] = b[i];
exp *= 10;
#ifdef SHOWPASS
printf("\nPASS : ");
radixsort(a, n);
#endif
}
}
int main( int argc, char *argv[] )
{
if ( argc != 3 )
{
printf("Need two input parameters in the following order: \n 1. Input file path \n 2. Number of elements in file\n");
return 0;
}
int num_elements = atoi(argv[2]);
int *input_arr = (int*) calloc (num_elements, sizeof(int));
int i;
FILE *fin; //File pointer to read input file
fin = fopen(argv[1], "r"); //Initialize file pointer
for(i=0; i<num_elements; i++)
{
fscanf(fin, "%d", &(input_arr[0]));
}
radixsort(input_arr[0], i);
printf ( "\nArray before sorting: \n") ;
for ( i = 0 ; i < num_elements ; i++ )
printf ( "%d\t", input_arr[0] ) ;
printf ( "\n\n");
return 0;enter code here
}
There are plenty of errors in your code. Firstly, the way you are taking input is incorrect.
fscanf(fin, "%d", &(input_arr[0]));
While taking input, the array input_arr is filled with a single input value at input_arr[0]. The rest of the input is over-written at input_arr[0].
Replace it with, fscanf(fin, "%d", &(input_arr[i]));.
Even you are displaying output in incorrect way.After sorting, the same output will be displayed num_elements times because of the following incorrect statement:
printf ( "%d\t", input_arr[0] ) ;
Again replace the above statement with printf ( "%d\t", input_arr[i] ).
As an impact of following incorrect statement,
fscanf(fin, "%d", &(input_arr[i])); ,
your program experiences a Segmentation fault, since in function radixsort, you are iterating from 0 to n-1(Number of elements).
for (i = 0; i < n; i++)
{
if (*a[i] > m)
m = a[i];
}
As only a[0] is filled with input value and rest of the array(from a[1] to a[n-1]) contains a garbage value, you will get a runtime error while executing your code.
There are lot of other bugs too, which i had fixed. This is the perfect running code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX 10
// #define SHOWPASS
// Compiled Using GNU GCC Compiler
void radixsort(int a[], int n)
{
int i, b[MAX], m = a[0], exp = 1;
for (i = 0; i < n; i++)
{
if (a[i] > m)
m = a[i];
}
while (m / exp > 0)
{
int queue[10] = { 0 };
for (i = 0; i < n; i++)
queue[a[i] / exp % 10]++;
for (i = 1; i < 10; i++)
queue[i] += queue[i - 1];
for (i = n - 1; i >= 0; i--)
b[--queue[a[i] / exp % 10]] = a[i];
for (i = 0; i < n; i++)
a[i] = b[i];
exp *= 10;
#ifdef SHOWPASS
printf("\nPASS : ");
radixsort(a, n);
#endif
}
}
int main(int argc, char *argv[])
{
if (argc != 3)
{
printf
("Need two input parameters in the following order: \n 1. Input file path \n 2. Number of elements in file\n");
return 0;
}
int num_elements = atoi(argv[2]);
int *input_arr = (int *)calloc(num_elements, sizeof(int));
int i;
FILE *fin; // File pointer to read input file
fin = fopen(argv[1], "r"); // Initialize file pointer
for (i = 0; i < num_elements; i++)
{
fscanf(fin, "%d", &(input_arr[i]));
}
radixsort(input_arr, i);
printf("\nArray before sorting: \n");
for (i = 0; i < num_elements; i++)
printf("%d\t", input_arr[i]);
printf("\n\n");
return 0;
}

Resources