find first repeating name in multiple names entered by the user - c

There was a breakfast organised by social workers. There were many people in line to get the food packet. Find out first person who reappeared in line for food packet quickly.
Given
Adam, Binny, Sohail, Krishna , Mayank, Sohail, Adam
The output should be:
Sohail
I am unable to solve this in c language.
Please can somebody explain what to do?
This is my code:
#include<stdio.h>
int main()
{
int n,i,j;
char str[20][20];
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%s",&str[i]);
}
for(i=0;i<n;i++){
for(j=i+1;j<n;j++){
if(str[i]==str[j]){
printf("%s\n",str[i]);
return 0;
}
}
}
return 0;
}
I am getting nothing in output.

It can give you some directions:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct PersonInfo
{
char *name;
int number;
} person_info;
void check(person_info arr[], size_t size);
int main()
{
char *arr_debug[20] = {"Adam", "Binny", "Sohail", "Krishna", "Mayank", "Sohail", "Adam"};
int i = 0;
person_info arr[7];
size_t size = sizeof(arr)/sizeof(arr[0]);
person_info temp;
for (i = 0; i < size; i++) {
// scanf("%s", temp.name);
temp.name = arr_debug[i];
temp.number = i + 1; // start counting from 1
arr[i] = temp;
}
check(arr, size);
return 0;
}
void check(person_info arr[], size_t size) {
char *temp_name;
int nums[size]; // filled with 0s
int num = 0;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (strcmp(arr[i].name, arr[j].name) == 0 && arr[i].number < arr[j].number) {
nums[num] = arr[j].number;
num++;
//store the number of the person
}
}
}
//find the earliest occurence
int earliest = nums[0];
for (int i = 1; i < size; i++) {
if (earliest > nums[i] && nums[i] != 0) {
earliest = nums[i];
}
}
//find the name associated to the number
for (int i = 0; i < size; i++) {
if (arr[i].number == earliest) {
temp_name = arr[i].name;
printf("%s \n", temp_name);
}
}
}

Related

printTriangle with alphabets

#include <stdio.h>
int inputNumber();
void printTriangle(int size, char ch[]);
int main()
{
char arr_char[] = {'a','e','i','o','u'};
int number;
number = inputNumber();
printTriangle(number,arr_char);
return 0;
}
int inputNumber()
{
int size;
printf("Input Size: ");
scanf("%d",&size);
printf("===\nTriangle Size is %d\n===\n",size);
return size;
}
void printTriangle(int size, char ch[5])
{
int i,j;
for(i=0;i<size;i++)
{
for(j=0;j<size;j++)
{
if(j <= 4)
{
printf("%s ",ch[j]);
}
if(j > 4 )
{
printf("# ");
}
}
}
}
This is what it supposed to look like. And I'm confused as what I did wrong because it only work with inputNumber but not with printTriangle. a e i o u # # # please go easy on me since I'm kinda new to this.
The segmentation fault is caused by an incorrect format string (%s should be %c). The output format doesn't match expectations as the inner loop condition is wrong and you need a newline after you print each line (after inner loop):
#include <stdio.h>
#define LEN 5
int inputNumber() {
int size;
printf("Input Size: ");
scanf("%d",&size);
printf("===\nTriangle Size is %d\n===\n",size);
return size;
}
void printTriangle(int size, char ch[]) {
for(int i = 0; i < size; i++) {
for(int j = 0; j <= i; j++) {
printf("%c ", j < LEN ? ch[j] : '#');
}
printf("\n");
}
}
int main() {
char arr_char[LEN] = {'a','e','i','o','u'};
int number;
number = inputNumber();
printTriangle(number,arr_char);
return 0;
}
Consider using the type unsigned instead of int as negative size, row (i) and column (j) doesn't make sense.
Here is an alternatively implementation of printTriangle() that does a bit of work upfront to generate the last row, then use a prefix of that last row to print all rows:
void printTriangle(unsigned size, char ch[]) {
// use malloc if size is large (say >4k),
// or you don't want to use a variable length array (VLA)
char str[2 * size];
for(unsigned column = 0; column < size; column++) {
str[2 * column] = column < LEN ? ch[column] : '#';
str[2 * column + 1] = ' ';
}
for(unsigned row = 0; row < size; row++) {
printf("%.*s\n", 2 * row + 1, str);
}
}

How fix the bubble-sort ? It doesn't line up in numerical order

#define stdMax 5
#define SWAP(a,b) {int t; t = a; a=b; b=t;}
typedef struct student {
char name[100];
int stdNum;
} Student;
void bubbleSort(int std[], int n );
int main() {
char text[stdMax][100];
Student std[stdMax];
char* temp = NULL;
for (int i = 0; i < stdMax; i++) {
printf("%d Enter student name / student number: ", i + 1);
gets(&text[i][0]);
}
for (int i = 0; i < stdMax; i++ ) {
strcpy_s(std[i].name, 100, strtok_s(&text[i][0], "/",&temp));
std[i].stdNum = atoi(strtok_s(NULL,"/",&temp));
}
bubbleSort(std, 5);
for (int i = 0; i < stdMax; i++) {
printf("%d %s\n", std[i].stdNum, std[i].name);
}
}
void bubbleSort(int *std, int n)
{
int i, j;
for (i = n; i > 1; i--)
{
for (j = 1; j < i; j++)
{
if (std[j - 1] > std[j])
{
SWAP(std[j - 1], std[j]);
}
}
}
}
ex) student/1234,
I'd like to put 5 in order of number size. However, when this code is executed, it only outputs as it is entered. I don't know which part is wrong. I think there's something wrong with the bubble sort, so I'd appreciate it if you could help me.
You are dealing with an array of Student, but the bubbleSort function is for sorting int. Mismatch here.
#define stdMax 5
#define SWAP(a,b) {Student t; t = a; a=b; b=t;}
typedef struct student {
char name[100];
int stdNum;
} Student;
void bubbleSort(Student std[], int n );
/* omit: same as original */
void bubbleSort(Student *std, int n)
{
int i, j;
for (i = n; i > 1; i--)
{
for (j = 1; j < i; j++)
{
if (std[j - 1].stdNum > std[j].stdNum)
{
SWAP(std[j - 1], std[j]);
}
}
}
}

I have to arrange the elements in this array from greatest to smallest using 2 methods, but the output is completely different

Here is the code
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int IndexOfMaxInRange(int ra[], int first, int last)
{
int index = first;
int max = ra[first];
for(int i = first+1; i < last; i++)
{
if(ra[i] > max)
{
index = i;
}
}
return index;
}
void SwapElement(int ra[], int iOne, int iTwo)
{
int temp = ra[iOne];
ra[iTwo] = ra[iOne];
ra[iOne] = temp;
}
void SortArray(int ra[],int length)
{
for(int i = 0; i < length; i++)
{
SwapElement(ra, i, IndexOfMaxInRange(ra, i, (length-1)));
}
}
int main(void)
{
int ra[5] = {2,5,8,3,4};
int length = sizeof (ra) / sizeof (ra[0]);
SortArray(ra, length);
for(int i = 0; i < length; i++)
{
printf("%d ", ra[i]);
}
return(EXIT_SUCCESS);
}
I am supposed to arrange the elements from greatest to smallest, but my output is: "2 5 5 2 4"
I know I am doing something wrong, but I can't put my eye on it, thanks in advance for all the feedback.
First of all, the swap was incorrect, you lost ra[iTwo] in the process. Change to
void SwapElement(int ra[], int iOne, int iTwo)
{
int temp = ra[iOne];
ra[iOne] = ra[iTwo];
ra[iTwo] = temp;
}
Second error is that you are not updating the current max in IndexOfMaxInRange
if(ra[i] > max)
{
max = ra[i];
index = i;
}
Now it should work.

Basic square function done with array & malloc

#include <stdio.h>
#include <stdlib.h>
int *squares(int max_val) {
int *result = malloc(max_val * sizeof(int));
int i;
for(i = 1; i <= max_val; i++) {
result[i-1] = i*i;
}
return(result);
}
int main() {
int *sq = squares(10);
int i;
for(i = 0; i < 10; i++) {
printf("%d\t", sq[i]);
}
printf("\n");
return(0);
}
Basically take's an integer and returns a integer array of its squares. (Above works)
How would I do this without malloc or pointers?
#include <stdio.h>
#include <stdlib.h>
int[] squares(int max_val) {
int result[max_val];
int i;
for(i = 1; i <= max_val; i++) {
result[i-1] = i*i;
}
return(result);
}
int main() {
int sq[] = squares(10);
int i;
for(i = 0; i < 10; i++) {
printf("%d\t", sq[i]);
}
printf("\n");
return(0);
}
Above errors because of the function call. Is this possible? Or do we have to do it with pointers?
How about something like this.. ?
#include <stdio.h>
#include <stdlib.h>
void squares(int values[], int max_val) {
for(int i = 1; i <= max_val; i++) {
values[i - 1] = i * i;
}
}
int main() {
int sq[10];
squares(sq, 10);
int i;
for(i = 0; i < 10; i++) {
printf("%d\t", sq[i]);
}
printf("\n");
return(0);
}
This
int[] squares(int max_val) {
int result[max_val];
int i;
for(i = 1; i <= max_val; i++) {
result[i-1] = i*i;
}
return(result);
}
is not valid C:
a.c:3:4: error: expected identifier or ‘(’ before ‘[’ token
int[] squares(int max_val)
It should be
int *squares(int max_val) {
...
}
Putting that aside, your second squares returns a pointer to a local array.
This array ceases to exist once squares ends it's execution, so you are
returning an pointer that become invalid the moment it returns.
Also
int sq[] = squares(10);
is invalid C as well
a.c:9:13: error: invalid initializer
int sq[] = squares(10);
^~~~~~~
you cannot assign a function value to an array. The correct
version is
int *sq = squares(10);
So, if you don't want squares to allocate memory with malloc for the result, then you can
either allocate the memory in main or create an array in main and pass it to
squares:
int squares(int *result, int max_val) {
if(result == NULL || max_val <= 0)
return 0;
int i;
for(i = 1; i <= max_val; i++) {
result[i-1] = i*i;
}
return 1;
}
// version 1
int main() {
int *sq = malloc(10 * sizeof *sq);
// NEVER forget to check the return value of malloc
if(sq == NULL)
{
fprintf(stderr, "not enough memory\n");
return 1;
}
squares(sq, 10);
int i;
for(i = 0; i < 10; i++) {
printf("%d\t", sq[i]);
}
printf("\n");
free(sq); // NEVER forget to free
return 0;
}
// version 2
int main() {
int sq[10];
squares(sq, sizeof sq / sizeof sq[0]);
int i;
for(i = 0; i < 10; i++) {
printf("%d\t", sq[i]);
}
printf("\n");
return 0;
}

Mergesort An Array of Strings in C

I'm trying to implement a merge sort for an array of strings entered from standard input, and am at a loss at what is wrong. Right now I'm facing a segmentation fault. How should I modify my code?
main() {
char temp;
int i = 0;
char Strings[NUM][LEN];
printf("Please enter %d strings, one per line:\n", NUM);
for (i; i < 25; i++) {
fgets(&Strings[i][0], LEN, stdin);
}
i = 0;
puts("\nHere are the strings in the order you entered:");
for (i; i < 25; i++) {
printf("%s\n", Strings[i]);
}
mergesort(Strings, NUM);
i = 0;
puts("\nHere are the strings in alphabetical order");
for (i; i < 25; i++) {
printf("%s\n", Strings[i]);
}
}
int mergesort(char list[NUM][LEN], int length) { // First part
mergesort_r(0, length, list);
return 0;
}
int mergesort_r(int left, int right, char list[NUM][LEN]) { // Overloaded portion
if (right - left <= 1) {
return 0;
}
int left_start = left;
int left_end = (left + right) / 2;
int right_start = left_end;
int right_end = right;
mergesort_r( left_start, left_end, list);
mergesort_r( right_start, right_end, list);
merge(list, left_start, left_end, right_start, right_end);
}
int merge(char list[NUM][LEN], int left_start, int left_end, int right_start, int right_end) {
int left_length = left_end - left_start;
int right_length = right_end - right_start;
char *left_half[left_length];
char *right_half[right_length];
int r = 0;
int l = 0;
int i = 0;
for (i = left_start; i < left_end; i++, l++) {
strcpy(left_half[l], list[i]);
}
for (i = right_start; i < right_end; i++, r++) {
strcpy(right_half[r], list[i]);
}
for (i = left_start, r = 0, l = 0; l < left_length && r < right_length; i++) {
if (strcmp(left_half[l], right_half[r]) < 0) {
strcpy(list[i], left_half[l++]);
} else {
strcpy(list[i], right_half[r++]);
}
}
for ( ; l < left_length; i++, l++) {
strcpy(list[i], left_half[l]);
}
for ( ; r < right_length; i++, r++) {
strcpy(list[i], right_half[r]);
}
return 0;
}
I'm not sure if it's that I'm passing in my array incorrectly, or maybe it's that I am not even executing swaps properly. I'm at my wits end with this and could use some advice.
should be
char left_half[left_length][LEN];
char right_half[right_length][LEN];
#include<stdio.h>
#include<stdlib.h>
#include<string.h> //To use the string functions like strcmp and strcpy
#define MAX 10 // This is the default size of every string
void Merge(char* arr[],int low,int mid,int high) //Merging the Array Function
{
int nL= mid-low+1;
int nR= high-mid;
char** L=malloc(sizeof(char *)*nL);
char** R=malloc(sizeof(char *)*nR);
int i;
for(i=0;i<nL;i++)
{
L[i]=malloc(sizeof(arr[low+i]));
strcpy(L[i],arr[low+i]);
}
for(i=0;i<nR;i++)
{
R[i]=malloc(sizeof(arr[mid+i+1]));
strcpy(R[i],arr[mid+i+1]);
}
int j=0,k;
i=0;
k=low;
while(i<nL&&j<nR)
{
if(strcmp(L[i],R[j])<0)strcpy(arr[k++],L[i++]);
else strcpy(arr[k++],R[j++]);
}
while(i<nL)strcpy(arr[k++],L[i++]);
while(j<nR)strcpy(arr[k++],R[j++]);
}
void MergeSort(char* arr[],int low,int high) //Main MergeSort function
{
if(low<high)
{
int mid=(low+high)/2;
MergeSort(arr,low,mid);
MergeSort(arr,mid+1,high);
Merge(arr,low,mid,high);
}
}
int main()
{
printf("\nEnter the size of the array desired: ");
int size; //This is the String array size
scanf("%d",&size);
char** arr= malloc(sizeof(char *)* size); //Creating required string array
printf("\nEnter the strings of the array: ");
int i;
for(i=0;i<size;i++)
{
arr[i]=malloc(sizeof(char)*MAX);
printf("\nEnter String: ");
scanf("%s",arr[i]);
}
MergeSort(arr,0,size-1);
printf("\nThe Sorted Array is: ");
for(i=0;i<size;i++)printf("%s ->",arr[i]);
return 0;
}
This is a Working solution to the same problem. Hope it Helps!
Cheers! :)
This solution of yours might give a memory error for long inputs or repeated executions. You need to free the allocated memory or not dynamically allocate it in the first place.
The latter is an easier option. What you can do is find the length of the longest string in the array of strings before hand and pass it as an argument to the merge sort and merge function.
Let's say that length is LEN.
Then instead of dynamically allocating memory for the L and R array, just declare it as:
char L[nL][LEN] and char R[nR][LEN].
It might take a slightly larger stack memory but avoids crashing the program.

Resources