C: Alphabetical sorting of array of character arrays - c

This showed up in our laboratory finals examination:
Make a program that takes in 10 string inputs into an array.
Then outputs the strings in alphabetical order.
I couldn't figure it out during the examination and now I want to know how exactly is it done.
So far this is what I've done. It doesn't work well with similar or equivalent strings, their index gets lost? Anyone can share their solution using only the stdio.h and string.h libraries?
/*Write a program that takes 10 strings input into an array and outputs them in alphabetical order*/
#include<stdio.h>
#include<string.h>
char strings[10][150];
char ordered[10][150];
int i,j,k;
int ind;
main()
{
printf("INPUT 10 STRINGS\n");
for(i=0;i<10;i++)
{
gets(strings[i]);
}
for(i=0;i<10;i++)
{
ind=0;
for(j=0;j<10;j++)
{
if(strings[i][0]<strings[j][0])
{
ind++;
}
else if(strings[i][0]==strings[j][0])
{
k=0;
while((strings[i][k]==strings[j][k])&&strings[j][k+1]!='\0')
{
if(strlen(strings[i])<strlen(strings[j]))
{
if(strings[i][k+1]=='\0')
{
ind++;
}
else if(strings[i][k+1]<strings[j][k+1])
{
ind++;
}
}
else if(strlen(strings[i])>strlen(strings[j]))
{
if(strings[i][k+1]<strings[j][k+1])
{
ind++;
}
}
k++;
}
}
}
strcpy(ordered[ind],strings[i]);
}
printf("STRINGS: \n");
for(i=9;i>-1;i--)
{
puts(ordered[i]);
}
}

Just Found a simple way for that:
#include<stdio.h>
#include<string.h>
int main()
{
int i,j,n;
char str[20][20],temp[20];
puts("Enter the no. of string to be sorted");
scanf("%d",&n);
for(i=0;i<=n;i++)
{
gets(str[i]);
}
for(i=0;i<=n;i++)
for(j=i+1;j<=n;j++)
{
if(strcmp(str[i],str[j])>0)
{
strcpy(temp,str[i]);
strcpy(str[i],str[j]);
strcpy(str[j],temp);
}
}
printf("The sorted string\n");
for(i=0;i<=n;i++)
{
puts(str[i]);
}
return 0;
}

strcmp and strcpy are inbuilt functions defined in string.h
for (i=0; i<10; i++) {
for (j=0; j<9; j++) {
if (strcmp(strings[j], strings[j+1]) > 0) {
strcpy(temp, strings[j]);
strcpy(strings[j], strings[j+1]);
strcpy(strings[j+1], temp);
}
}
}

Here's a solution retrieved from here that does what you want but with 5 strings instead. I have adapted it so that it sorts 10 strings instead of 5. All strings have 20 characters at most :
#include<stdio.h>
#include<string.h>
void main() {
char s[10][20], t[20];
int i, j;
clrscr();
printf("\nEnter any five strings : ");
for (i = 0; i < 10; i++)
scanf("%s", s[i]);
for (i = 1; i < 10; i++) {
for (j = 1; j < 10; j++) {
if (strcmp(s[j - 1], s[j]) > 0) {
strcpy(t, s[j - 1]);
strcpy(s[j - 1], s[j]);
strcpy(s[j], t);
}
}
}
printf("\nStrings in order are : ");
for (i = 0; i < 10; i++)
printf("\n%s", s[i]);
getch();
}

Related

How do I sort lastname by alphabetical order?

This program is only for sorting the firstname alphabetically.
My Code
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void main()
{
char name[10][8], temp[8];
int i, j, n;
printf("Enter the value of n \n");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
scanf("%s", 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("Input name changes alphabetically\n");
for (i = 0; i < n; i++)
{
printf("\t%s\n", name[i]);
}
return 0;
}
(output of the program)
Suppose,Input
Enter the value of 2
merge
bubble
output
Input name changes alphabetically
bubble
merge
But I want to write this program to sort the lastname alphabetically.
suppose,for example
Input
Marop hossain
Nihan ahmed
output
Nihan ahmed
Marop hossain
I'm new to programming so i don’t understand. How do I change the code above to get this result.
the code below should work fine
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char name[10][8], temp[8];
int i, j, n,L,k;
printf("Enter the value of n \n");
scanf("%d", &n);
fflush(stdin);
for (i = 0; i < n; i++)
{
gets(name[i]);
}
for (i = 0; i < n - 1 ; i++)
{
k=0;
while(1) //searches for the whitespace in the string
{
++k;
if(name[i][k]==' ')
break;
}
for (j = i + 1; j < n; j++)
{
L=0;
while(1)
{
++L;
if(name[j][L]==' ')
break;
}
if(name[i][k+1]>name[j][L+1]) //compares the char after the whitespace
{
strcpy(temp, name[i]);
strcpy(name[i], name[j]);
strcpy(name[j], temp);
}
}
}
printf("Input name changes alphabetically\n");
for (i = 0; i < n; i++)
{
puts(name[i]);
}
return 0;
} ```

how to find common letters between shortest and longest word in a sentence, string in C

i have code for find longest and shortest word in sentence. but how to find common letters in
this 2 words(what to add to the program?)? In C
#include<stdio.h>
#include<string.h>
int main() {
long int i=0,j=0,k=0,a,minIndex=0,maxIndex=0,max=0,min=0;
char str1[100]={0},substr[100][100]={0};
printf("Enter a sentence\n");
gets(str1);
while(str1[k]!='\0') {
j=0;
while(str1[k]!=' '&&str1[k]!='\0') {
substr[i][j]=str1[k];
k++; j++;
}
substr[i][j]='\0';
i++;
if(str1[k]!='\0') {
k++;
}
}
long int len=i;
max=strlen(substr[0]);
min=strlen(substr[0]);
for(i=0;i<len;i++) {
a=strlen(substr[i]);
if(a>max) {
max=a; maxIndex=i;
}
if(a<min) {
min=a; minIndex=i;
}
}
printf("Largest Word is %s \nSmallest word is %s\n",substr[maxIndex],substr[minIndex]);
}
Remove the printf at the end of your code and add the following lines to your code before closing the main() method.
int common[26] = {0};
for(i = 0; i < strlen(substr[minIndex]); i++)
{
for(j = 0; j < strlen(substr[maxIndex]); j++)
{
if(tolower(substr[maxIndex][j]) == tolower(substr[minIndex][i]))
{
common[tolower(substr[minIndex][i]) - 'a'] = 1;
}
}
}
for(i = 0; i < 26; i++)
{
if(common[i] == 1)
{
printf("%c\n", (i + 'a'));
}
}
What this does is, it compares every letter in the longest word with every letter in the shortest word and for every match, it marks the corresponding index in common alphabets array as 1. After all the letters have been traversed through, we simply iterate through the common array and print the marked letters.
Full working code below:
#include<stdio.h>
#include<string.h>
int main() {
long int i=0,j=0,k=0,a,minIndex=0,maxIndex=0,max=0,min=0;
char str1[100]={0},substr[100][100]={0};
printf("Enter a sentence\n");
gets(str1);
while(str1[k]!='\0') {
j=0;
while(str1[k]!=' '&&str1[k]!='\0') {
substr[i][j]=str1[k];
k++; j++;
}
substr[i][j]='\0';
i++;
if(str1[k]!='\0') {
k++;
}
}
long int len=i;
max=strlen(substr[0]);
min=strlen(substr[0]);
for(i=0;i<len;i++) {
a=strlen(substr[i]);
if(a>max) {
max=a; maxIndex=i;
}
if(a<min) {
min=a; minIndex=i;
}
}
printf("The longest word is: %s \nThe shortest word is: %s\n",substr[maxIndex],substr[minIndex]);
int common[26] = {0};
for(i = 0; i < strlen(substr[minIndex]); i++)
{
for(j = 0; j < strlen(substr[maxIndex]); j++)
{
if(tolower(substr[maxIndex][j]) == tolower(substr[minIndex][i]))
{
common[tolower(substr[minIndex][i]) - 'a'] = 1;
}
}
}
printf("Common letters between the longest word and the shortest word are: ");
for(i = 0; i < 26; i++)
{
if(common[i] == 1)
{
printf("%c, ", (i + 'a'));
}
}
printf("\b\b ");
}
INPUT
This is Isomorphic
OUTPUT
The longest word is: Isomorphic
The shortest word is: is
Common letters between the longest word and the shortest word are: i, s

How to remove the last comma in comma separated prime numbers within a range?

I have the code for finding prime numbers within a range.
The problem is to remove the last comma.
#include<stdio.h>
int main()
{
int a,b,i,x,c,f=1;
scanf("%d%d",&a,&b);
for(x=a;x<=b;(x++,f=0))
{
for(i=2;i<x;i++)
{
if(x%i==0)
{
f=1;
}
}
if(f==0)
printf("%d,",x);
}
}
But the output contains an extra comma in the last.
For example
2,3,5,7,
whereas the expected output is
2,3,5,7
Instead of flag you can decide directly what you want to print between numbers
And note that you can break out of the internal loop as soon as f is set to 1
#include<stdio.h>
int main()
{
int a,b,i,x,c,f=1;
const char* delim = "";
scanf("%d%d",&a,&b);
for(x=a; x<=b; (x++,f=0))
{
for(i=2; i<x; i++)
{
if(x%i==0)
{
f=1;
break; //no need to continue the checking
}
}
if(f==0) {
printf("%s%d",delim,x);
delim = ", ";
}
}
putchar('\n');
}
#include<stdio.h>
int main()
{
int a,b,i,x,c,f=1;
char backspace = 8;
scanf("%d%d",&a,&b);
for(x=a;x<=b;(x++,f=0))
{
for(i=2;i<x;i++)
{
if(x%i==0)
{
f=1;
}
}
if(f==0)
printf("%d,",x);
}
printf("\b"); // or printf("%c", backspace);
}
Add another flag, just a simple counter that tells you if you are printing the first time then check the flag to decide what to print, e.g.
#include<stdio.h>
int main()
{
int a,b,i,x,c,first=0,f=1;
scanf("%d%d",&a,&b);
for(x=a;x<=b;(x++,f=0))
{
for(i=2;i<x;i++)
{
if(x%i==0)
{
f=1;
}
}
if(f==0)
{
if(first==0){
printf("%d",x);
}else{
printf(",%d",x);
}
first++
}
}
}
Use a flag to detect the first occurrence of printf() and print the first number as such without any ,. For consecutive number printing precede with ,
#include<stdio.h>
int main()
{
int a,b,i,x,c,f=1,flag=0;//Flag to mark first occurrence
scanf("%d%d",&a,&b);
for(x=a;x<=b;(x++,f=0))
{
for(i=2;i<x;i++)
{
if(x%i==0)
{
f=1;
break;// Once the condition fails can break of the for loop as it fails for the prime number condition at the first case itself
}
}
if(f==0)
{
if(flag==0)
{//Check if it is first time
printf("%d",x);
flag = 1;//If so print without ',' and set the flag
}
else
printf(",%d",x);// On next consecutive prints it prints using ','
}
}
}
This method also avoids the , when only one number is printed.
Eg: When input is 2 and 4. It prints just 3 and not 3,
Simply you need odd number best practice for minimum loop is given below;
#include<stdio.h>
int main()
{
int a,b,i,x,c,f=1;
scanf("%d%d",&a,&b);
while (a < b)
{
if ( (a%2) == 1) {
printf("%d", a);
if ( (a + 1) < b && (a + 2) < b)
printf(",");
}
a = a + 1;
}
}
please check from the site
http://rextester.com/MWNVE38245
Store the result into a buffer and when done print the buffer:
#include <stdio.h>
#include <errno.h>
#define RESULT_MAX (42)
size_t get_primes(int * result, size_t result_size, int a, int b)
{
int i, x, f = 1;
size_t result_index = 0;
if (NULL == result) || (0 == result_size) || ((size_t) -1 == result_size))
{
errno = EINVAL;
return (size_t) -1;
}
for (x = a; x <= b; (x++, f = 0))
{
for (i = 2; i < x; i++)
{
if (x % i == 0)
{
f = 1;
break;
}
}
if (f == 0)
{
result[result_index] = x;
++result_index;
if (result_size <= result_index)
{
fprintf(stderr, "Result buffer full. Aborting ...\n");
break;
}
}
}
return result_index;
}
int main(void)
{
int a = 0, b = 0;
int result[RESULT_MAX];
scanf("%d%d", &a, &b);
{
size_t result_index = get_primes(result, RESULT_MAX, a, b);
if ((size_t) -1 == result_index)
{
perror("get_primes() failed");
}
else if (0 == result_index)
{
fprintf(stderr, "No primes found.\n");
}
else
{
printf("%d", result[0]);
for (size_t i = 1; i < result_index; ++i)
{
printf(", %d", result[i]);
}
}
}
return 0;
}
This example uses a simple fixed-size buffer, if this does not suite your needs replace it by a dynamic one.
This is more of a "language-agnostic" problem: "How do I output a comma-separated list without a final comma?" It is not specifically about prime numbers.
You seem to be thinking of you list as a series of [prime comma] units. It isn't. A better way to think of it is as a single prime as the head of the list, followed by a tail of repeated [comma prime] units.
Some pseudocode to illustrate the general idea:
outputList(theList)
separator = ", "
output(theList.firstItem())
while (theList.hasMoreItems())
output(separator)
output(theList.nextItem())
endwhile
return
/* this is just logic */
for(i=2;i<=n;i++)
{
k=0;
for(j=2;j<=i/2;j++)
{
if(i%j==0)
k=1;
}
if(k==0)
{
c++;
c++;
}
}
System.out.println(c);
for(i=2;i<=n;i++)
{
k=0;
for(j=2;j<=i/2;j++)
{
if(i%j==0)
k=1;
}
if(k==0)
{
System.out.print(i);
b++;
if(b!=c-1)
{
System.out.print(",");
b++;
}
}
}
}
}
//comma separated values
#include <bits/stdc++.h>
using namespace std;
int Prime(int a, int n){
bool prime[n+1];
memset(prime,true,sizeof(prime));
for(int p=2;p*p<=n;p++){
if(prime[p]==true){
for(int i=p*p ; i<=n; i+=p ){
prime[i] = false;
}
}
}
for(int i = 2;i<= n;i++){
if(i==2) cout<<i; // here is the logic first print 2 then for other numbers first print the comma then the values
else if(prime[i]) cout<<","<<i;
}
}
int main(){
int a =2 ;
int n = 30;
Prime(a , n);
}
#include <stdio.h>
int main()
{
int i, j, n, count;
scanf("%d", &n);
for(i=2; i<n; i++)
{
count=0;
for(j=2; j<n; j++)
{
if(i%j==0)
count++;
}
if(count==1)
printf("%d," i);
}
printf("\b \b");
}
\b is a nondestructive backspace. It moves the cursor backward, but doesn't erase what's there, it replaces it. For a a destructive backspace,
use "\b \b" i.e. a backspace, a space, and another backspace.
This Program prints all the prime number up to given number with comma separated

Fgets and sscanf not waiting for input C

Originally I was using scanf, but I was running into the newline char getting stuck in the stdin. Everything I have read was saying to switch to fgets and use sscanf instead. With that, I decided to switch to that...but that still is not working. Below you will find my code. My question is, what am I doing wrong with my fgets and sscanf that is causing it to not wait for the user input?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct f_in{
char outline;
int lines;
int rows;
int num_args;
} F_IN;
typedef struct args_in {
char in_string[20];
int t_format;
} ARGS_IN;
void printInterface(char argQs[5][50], char argChar);
int main(int argv, char** argc){
char defaultQuestions[5][50] = { { "1) What char for border?" }
, { "2) Add question" }
, { "3) Remove Question" }
, { "4) Print last answers" }
, { "5) Exit" } };
int commandEntry, exitFlag;
char borderChar = '*', addQ[50],userInp[1];
exitFlag = 1;
while (exitFlag){
printInterface(defaultQuestions, borderChar);
printf("Enter the integer value for the command you wish to select: ");
fgets(userInp, sizeof(userInp),stdin);
sscanf(userInp,"%d", &commandEntry);
printf("\nYou selected: %s\n", defaultQuestions[commandEntry - 1]);
userInp[0] = 0;
if (commandEntry == 1){
printf("Please enter the character you wish to be the border: ");
fgets(userInp,sizeof(userInp),stdin);
sscanf(userInp,"%c",&borderChar);
}
else if (commandEntry == 2){
printf("What question would you like to add? (only enter 50 char max)\n");
fgets(addQ, 50, stdin);
printf("This was your question: %s", addQ);
}
else if (commandEntry == 5){
printf("Goodbye!\n");
exitFlag = 0;
}
}
return 0;
}
void printInterface(char argQs[5][50], char argChar){
int i, j;
int lineCnt = 13;
int borderLen = 75;
for (i = 0; i<100; i++){
printf("\n");
}
for (i = 0; i<lineCnt; i++){
if (i == 0 || i == lineCnt - 1){
for (j = 0; j<borderLen; j++){
printf("%c", argChar);
}
printf("\n");
}
else if (i >= 3 && i <= 10){
printf("%c %s", argChar, argQs[i - 3]);
for (j = 0; j < ((borderLen - strlen(argQs[i - 3]))-6); j++){
printf(" ");
}
printf("%c\n", argChar);
}
else{
for (j = 0; j<borderLen; j++){
if (j == 0){
printf("%c", argChar);
}
else if (j == (borderLen - 1)){
printf("%c\n", argChar);
}
else{
for (j = 0; j<borderLen; j++){
if (j == 0){
printf("%c", argChar);
}
else if (j == (borderLen - 1)){
printf("%c\n", argChar);
}
else{
printf(" ");
}
}
}
}
for (i = 0; i<10; i++){
printf("\n");
}
}
"userInp[1] only allows enough memory to store the terminating '\0'"
- user312023

How do I print a string's characters in a diagonal pattern?

I am trying to write a program that reads a string from the user and prints the string's characters in a diagonal pattern. I set the maximum length of the string as 50 characters. The program can print the characters in a diagonal pattern, but it doesn't print the characters correctly.
#include<stdio.h>
int main () {
int i = 0, j = 0, m;
char c[50];
printf("Enter a string: ");
scanf("%c", c);
m = sizeof(c) / sizeof(c[0]);
for (i = 1; i <= m; i++) {
for (j = 1; j <= i; j++) {
if (j == i) {
printf("%c", c[i-1]);
} else {
printf(" ");
}
}
printf("\n");
}
return 0;
}
Check the code below:
#include<stdio.h>
int main ()
{
int i=0,s=0;
char c[50];
printf("Enter a string: ");
scanf("%s",c);
while(c[i] != '\0')
{
s = i;
while(s--)
printf(" ");
printf("%c\n",c[i]);
i++;
}
return 0;
}

Resources