how to sort names in c by array - c

I want to know how to sort name by array.
I have a ploblem about sorting and print it. I have no idea because I'm beginner for C programing. please advice me (sorry for my english) thank you.
code that i have
#include<stdio.h>
#include<string.h>
#include <ctype.h>
int main(){
int i = 0;
char choose[10];
struct Student{
char name[61];
char surname[61];
char sex[10];
char age[3];
char id[12];
float gpa;
}student[20];
for(i=0;i<20;i++){
scanf("%s %s %s %s %s %f",student[i].name, student[i].surname, student[i].sex,student[i].age,student[i].id,student[i].gpa);
}
for(int i =0;i<20;i++){
//sort
}
}

When a task is about sorting arrays, qsort is - in most cases - your friend.
All you need to do is to provide a compare function that tells whether one element is less, equal or larger than another element. Then qsort handles the rest.
Example:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct Student{
char name[61];
char surname[61];
char sex[10];
char age[3];
char id[12];
float gpa;
};
void printData(struct Student* s, int n)
{
for (int i=0; i<n; ++i)
{
printf("%s %s %s %s %s %f\n",
s[i].sex, s[i].name, s[i].surname, s[i].age, s[i].id, s[i].gpa);
}
}
// Compare function for qsort
int cmp(const void *p1, const void *p2)
{
struct Student* pa = (struct Student*)p1;
struct Student* pb = (struct Student*)p2;
return strcmp(pa->name, pb->name);
}
int main(void)
{
struct Student data[3] = {
{"bbb", "bbbb", "Mr", "42", "idx", 42.0},
{"ccc", "cccc", "Ms", "42", "idy", 43.0},
{"aaa", "aaaa", "Mr", "42", "idz", 44.0}
};
printf("Before sorting:\n");
printData(data, 3);
qsort(data, 3, sizeof data[0], cmp);
printf("After sorting:\n");
printData(data, 3);
return 0;
}
Output:
Before sorting:
Mr bbb bbbb 42 idx 42.000000
Ms ccc cccc 42 idy 43.000000
Mr aaa aaaa 42 idz 44.000000
After sorting:
Mr aaa aaaa 42 idz 44.000000
Mr bbb bbbb 42 idx 42.000000
Ms ccc cccc 42 idy 43.000000

#include <stdio.h>
#include <string.h>
void main()
{
char name[10][8], tname[10][8], temp[8];
int i, j, n;
printf("Enter the value of n \n");
scanf("%d", &n);
printf("Enter %d names n \n", n);
for (i = 0; i < n; i++)
{
scanf("%s", name[i]);
strcpy(tname[i], name[i]);
}
for (i = 0; i < n - 1 ; i++)
{
for (j = i + 1; j < n; j++)
{
if (strcmp(name[i], name[j]) > 0)
{
strcpy(temp, name[i]);
strcpy(name[i], name[j]);
strcpy(name[j], temp);
}
}
}
printf("\n----------------------------------------\n");
printf("Input NamestSorted names\n");
printf("------------------------------------------\n");
for (i = 0; i < n; i++)
{
printf("%s\t\t%s\n", tname[i], name[i]);
}
printf("------------------------------------------\n");
}

Related

How to add the array "Name" inside "Surname" by the indicated position number in C language?

Example:
name: John
surname: Smith
position: 2
result: JoSmithhn
Code:
#include <stdio.h>
#include <stdlib.h>
int main() {
char name[50] = "John";
char surname[50] = "Smith";
char result[50] = { 0 };
int pos;
printf("Position: ");
scanf_s("%d", &pos);
for (int i = 0; i < pos; ++i) {
result[i] = name[i];
}
for (int i = 0; i < surname[i]; i++) {
result[pos + i] = surname[i];
}
printf("%s\n", result);
system("pause");
return 0;
}
Be aware that result is as long as surname and name, so when they are together longer than 50 chars, you will lose data.
Something like this can implement your example without the need of for loops.
#include <stdio.h>
#include <string.h>
int main() {
char name[50] = "John";
char surname[50] = "Smith";
char result[100];
int pos;
printf("Position: ");
scanf("%d", &pos);
char buf[pos];
memcpy(buf, name, pos);
snprintf(result, 100, "%s%s%s\n", buf, surname, name + pos);
printf(result);
return 0;
}

printing 2-d character array in c

I want to create and print 2-D char array in C, which i will eventually use as an input in function "execvp()" for execute and development of a shell. When i execute the code i take this as an output and not the whole array.
What is the problem?
In this part if the code i present only the part which i try to initialize the array:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i,j;
char **cmd[4][3] = {
{"ls", "-l",NULL},
{"grep", "test.c", NULL},
{"wc", NULL},
{"sort", "-r", NULL}
};
for(i=1;i<5;i++)
{
for(j=0;j<3;j++)
{
printf("%s\n",cmd[i][j]);
}
}
return (0);
}
Output:
grep
test.c
Segmentation fault (core dumped)
Hm. Why do you have for(i=1;i<5;i++) if you have only 4 rows?
Should it be
printf("%s\n",cmd[i-1][j]);
or
for(i=0;i<4;i++)
?
You have a 2 dimensional array of pointers to char. So the definition for cmd should be:
char *cmd[4][3] = {...
The for loop has incorrect indexes. for(i=1;i<5;i++) should loop from 0 to 4.
And you should check before trying to print NULL pointers, which definitely exist in the array:
if( cmd[i][j] )
printf("%s\n",cmd[i][j]);
The following program should give you an Idea:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void printArray(char **array,long unsigned int numWords){
printf("\n");
printf("Inside printArray:\n");
long unsigned int i;
for(i=0;i<numWords;i++){
printf("%s\n",array[i]);
}
printf("\n");
}
int main(void){
long unsigned int numWords,i;
char **array;
printf("Introduce how many words do you want:> ");
if((scanf("%lu", &numWords)) != 1){
printf("Error, Fix it!\n");
exit(1);
}
array = malloc(sizeof(char*) * numWords * numWords);
if (array == NULL) {
exit(2);
}
for (i = 0; i < numWords; i++){
array[i] = malloc(sizeof(char*) * 100);
}
for (i = 0; i < numWords; i++){
printf("Enter your word number %lu:> ", i + 1);
if((scanf("%s", array[i])) != 1){
printf("Error, Fix it!\n");
exit(3);
}
}
printf("Inside Main:\n");
for (i = 0; i < numWords; i++){
printf("%s \n", array[i]);
}
printArray(array,numWords);
for (i = 0; i < numWords; i++){
free(array[i]);
}
free(array);
return 0;
}
Output:
Inside Main:
Michael
Jackson
Inside printArray:
Michael
Jackson
EDIT:
based on your question, the following program does what you need:
#include <stdio.h>
int main(void){
int i,j;
char *array[4][3] = {
{"A", "B", "C"},
{"D", "E", "F"},
{"G", "H", "I"},
{"J", "K", "L"},
};
for (i = 0; i < 4; i++){
for(j=0;j<3;j++){
printf("%s ", array[i][j]);
}
}
return 0;
}
Output:
A B C D E F G H I J K L

How do you copy a Struct array to another struct in the same array?

I am trying to work through my code, I'm unable to use a sorting algorithm due to crashes caused by trying to copy a structure at a specific array position to another in the same array at a different location.
//include statements
#include <stdio.h>
#include <stdlib.h>
//defines
#define MAX 100
#define STRUCTMAX 26
#define STUDENTS 9
//Struct declarations
typedef struct{
char street[STRUCTMAX];
char city[STRUCTMAX];
char state[STRUCTMAX];
char zip[STRUCTMAX];
}Address;
typedef struct{
char firstName[STRUCTMAX];
char initial[STRUCTMAX];
char lastName[STRUCTMAX];
Address adress;
int age;
double gpa;
}Student;
//prototypes
void readFile(Student students[]);
void printAll(Student students[]);
void printBestGpaName(Student students[]);
double averageGPA(Student students[]);
void printAboveAverageGPA(Student students[]);
void printYoungestLowGPA(Student students[]);
void sortStruct(Student students[]);
void strSub(char s1 [], char s2 [], int start, int size);
void initialize(Student students[]);
void main(void){
Student students[STUDENTS];
readFile(students);
printAll(students);
printBestGpaName(students);
printf("Average G.P.A is %.2lf\n" ,averageGPA(students));
printAboveAverageGPA(students);
printYoungestLowGPA(students);
sortStruct(students);
printf("\n");
printAll(students);
}
void readFile(Student students[]){
int i = 0;
char numberValue[10];
char line[MAX];
FILE *fp;
fp = fopen(
"/Users/derekroy/Desktop/Lab_6/Lab_6A/Students.dat", "r");
if (fp == NULL) {
printf("Students.dat file not found.\n");
exit(1);
}
while (!feof(fp)) {
fgets(line, MAX, fp);
strSub(line, students[i].firstName, 0, 7);
strSub(line, students[i].initial, 10, 1);
strSub(line, students[i].lastName, 11, 9);
strSub(line, students[i].adress.street, 20, 16);
strSub(line, students[i].adress.city, 36, 13);
strSub(line, students[i].adress.state, 49, 2);
strSub(line, students[i].adress.zip, 52, 5);
strSub(line, numberValue, 58, 2);
students[i].age = atoi(numberValue);
strSub(line, numberValue, 60, 5);
students[i].gpa = atof(numberValue);
i++;
}
}
void printAll(Student students[]){
int i;
printf("All listed Students: \n");
for(i = 0; i < STUDENTS; ++i){
printf("%s %s %s %s %s %s, %s %d %.2lf\n" , students[i].firstName, students[i].initial,
students[i].lastName, students[i].adress.street, students[i].adress.city,
students[i].adress.state, students[i].adress.zip, students[i].age, students[i].gpa);
}
printf("\n");
printf("******");
}
void printBestGpaName(Student students[]){
int i, best = 0;
for(i = 0; i < STUDENTS; ++i){
if(students[i].gpa > students[best].gpa)
best = i;
}
printf("Student with best G.P.A: ");
printf("%s %s %s\n" , students[best].firstName, students[best].initial, students[best].lastName);
}
double averageGPA(Student students[]){
int i;
double sum = 0.0;
for(i = 0; i < STUDENTS; ++i){
sum += students[i].gpa;
}
return sum / i;
}
void printAboveAverageGPA(Student students[]){
int i;
double average = averageGPA(students);
printf("Students with above average G.P.A: \n");
for(i = 0; i < STUDENTS; ++i){
if(students[i].gpa > average)
printf("%s %s %s\n" , students[i].firstName, students[i].initial, students[i].lastName);
}
}
void printYoungestLowGPA(Student students[]){
int i, j, young = 1000;
double average = averageGPA(students);
for(i = 0; i < STUDENTS; ++i){
if(students[i].gpa < average){
if(students[i].age < young){
j = i;
young = students[i].age;
}
}
}
printf("The youngest student with a below average G.P.A: ");
printf("%s %s %s\n" ,students[j].firstName, students[j].initial, students[j].lastName);
}
void sortStruct(Student students[]){
int i, j;
Student temp;
for(i = 1; i < STRUCTMAX; ++i){
/*temp.firstName = students[i].firstName;
temp.initial = students[i].initial;
temp.lastName = students[i].lastName;
temp.adress.street = students[i].adress.street;
temp.adress.city = students[i].adress.city;
temp.adress.state = students[i].adress.state;
temp.adress.zip = students[i].adress.zip;
temp.age = students[i].age;
temp.gpa = students[i].gpa;*/
temp = students[i];
j = i - 1;
while(j >= 0 && temp.gpa < students[j].gpa){
//students[j+1] = students[j];
j = j - 1;
}
//students[j+1] = temp;
}
}
void strSub(char s1 [], char s2 [], int start, int size){
int i;
for(i = 0; i < size; ++i){
s2[i] = s1[start];
start++;
}
s2[i] = '\0';
}
The offending line is in the Sort function.
How can I make this work, and copy the specified structure to their new address in the structure array?
you defined only 9 student records
Student students[STUDENTS]; -> STUDENTS macro is 9
you are iterating till STRUCTMAX which is a macro defined as 26
so you will go out of bounds causing the crash
for(i = 1; i < STRUCTMAX; ++i){

Error: too few arguments to function 'strcmp'

I am having a few issues with my code. First: when I try to compile, I get error: too few arguments to function 'strcmp'. I have looked all over and made multiple changes and am still unable to get it to work. Second: when my code does compile (if I remove the strcmp part), it will not complete the count functions correctly. Can anyone please assist? Thank you!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int count(char array[], int size);
int stringLen(char array[]);
int convert(char ch);
int value, n;
int main()
{
//char * str;
//char s;
char a[100];
char b[100];
char c[100];
int charCount = stringLen(a);
int lCount = count(a, charCount);
printf("Enter your string: \n");
scanf("%s \n", a);
printf("Enter your string: \n");
scanf("%s \n", b);
printf("Enter your string: \n");
scanf("%s \n", c);
printf("The count is %d, length is %d\n", lCount, charCount);
int i;
for(i = 0; i < charCount; i++)
{
char c = a[i];
printf("Char %s = %d \n", &c, value);
}
n = strcmp(char string1[], char string2[], char string3[]);
printf("The first string in the alphabet is: %d \n", n);
return 0;
}
int stringLen(char array[])
{
char count;
int index;
while(array[index] !=0)
{
count++;
index++;
}
return count;
}
int count(char array[], int size)
{
int count;
int i;
for(i = 0; i < size; i++)
{
if(array[i] == 'a')
{
count ++;
}
else if(array[i] == 'A')
{
count ++;
}
}
return count;
}
This is not right way to use strcmp.
n = strcmp(char string1[], char string2[], char string3[]);
strcmp is used for compararison of string. See doc
int result = strcmp (string1,string2)
If strings are same, function will return 0.

Bubble sort in C. Output is the same as input

As a school assignment we are writing a bubble sort program in c. The code I wrote works. The only thing is that the output returns the input and doesn't return the swapped input. I'm kinda stuck. No matter what I do i either get an error or nothing changes. Does anybody know what is going wrong? Any help would be highly appreciated!!
#include <stdio.h>
#include <string.h>
#define MAXLENGTH 100
void getString(char *str);
void printResult(char *str);
int greaterThan(char ch1, char ch2);
void swap(char *str, int index1, int index2);
int main(void) {
int len; // length of the entered string
char str[MAXLENGTH]; // input should be no longer than MAXLENGTH
getString(str);
len = strlen(str); // get length of the string, from sting.h
int j;
for (j = 0; j < len-j; j++) {
int i;
for (i = 0; i < len-j; i++){
char ch1 = str[i];
char ch2 = str[i+1];
if (greaterThan(ch1, ch2)) {
swap(str, i, i+1); // swap char 1
swap(str, i, i+1); // swap char 2
}
}
}
printResult(str);
return(0);
}
void getString(char *str) {
printf("Enter the string you would like to sort: ");
scanf("%s",str);
}
void printResult(char *str){
printf("Here is the sorted string: ");
printf("%s",str);
}
int greaterThan(char ch1, char ch2){
return (ch1 > ch2);
}
void swap(char *str, int index1, int index2){
char h = str[index1];
str[index1] = str[index2];
str[index2] = h;
}
Try this:
getString(str);
len = strlen(str); // get length of the string, from sting.h
int j;
for (j = 0; j < len-j; j++) {
int i;
for (i = 0; i < len-j; i++){
char ch1 = str[i];
char ch2 = str[i+1];
if (greaterThan(ch1, ch2)) {
swap(str, i, i+1); // swap char 1
}
}
}
printResult(str);
return(0);
}
Here:
if (greaterThan(ch1, ch2)) {
swap(str, i, i+1); // swap char 1
swap(str, i, i+1); // swap char 2
}
you are swapping twice while you should swap only once.
I was bad the below part of my answer's previous version is not bubble short:
Another problem is that you are using elements next to each other and you are not using i and j indexed ones to compare and swap. So you better should have something like this:
if (greaterThan(str[i], str[j]))
swap(str, i, j);
if (greaterThan(ch1, ch2)) {
swap(str, i, i+1); // swap char 1
swap(str, i, i+1); // swap char 2
}
In this code you are swamping twice.
For Example: str = ['a','b','c'] swap(str,1,2) for first swap the " str " will be ['a','c','b'] and for the second swap " str " will be ['a','b','c']. That's why your Output is the same as input.
You Just Need To Call swap function only once.
if (greaterThan(ch1, ch2)) {
swap(str, i, i+1);
}

Resources