I have the following code which sorts the strings using bubble sort logic. The part that I am confused about is the for loop which Im not sure why i is set to one and why J is iterated until it is less than n-j:
#include <stdio.h>
#include <string.h>
void main()
{
char name[25][50],temp[25];
int n, i, j;
printf("\n\nSorts the strings of an array using bubble sort :\n");
printf("-----------------------------------------------------\n");
printf("Input number of strings :");
scanf("%d",&n);
printf("Input string %d :\n",n);
for(i=0; i<=n; i++)
{
fgets(name[i], sizeof name, stdin);
}
/*Logic Bubble Sort*/
for(i=1; i<=n; i++)
{
for(j=0; j<=n-i; j++)
{
if (strcmp(name[j],name[j+1])>0)
{
strcpy(temp,name[j]);
strcpy(name[j],name[j+1]);
strcpy(name[j+1],temp);
}
}
}
printf("The strings appears after sorting :\n");
for(i=0;i<=n;i++)
printf("%s\n",name[i]);
}
There are a few subtle things wrong with this code
You are running the for loop one more than necessary.
for(i=0;i<=n;i++)
{
fgets(name[i], sizeof name, stdin);
}
The reason that is the line above scanf("%d",&n);
Here the end of line remains in the input stream and is being added to name[0]. You should change it to scanf("%d ",&n);
This will consume the end of line in the same statement. Also the for loop should now run from for(i=0;i< n;i++).
Additionally, the fgets function receives a size of name which is too large.
It should receive a size of name[0] i.e. fgets(name[i], sizeof name[0], stdin);
Now, your strings are being stored from name[0] to name[n-1] and the rest of your sort algorithm can be fixed.
for(i=0;i< n;i++){
for(j=0;j< n-i;j++)
{
if(strcmp(name[j],name[j+1])>0)
{
strcpy(temp,name[j]);
strcpy(name[j],name[j+1]);
strcpy(name[j+1],temp);
}
}
}
printf("The strings appears after sorting :\n");
for(i=0;i< n;i++)
printf("%s",name[i]);
The reason for the inner for loop going from 0 to n-i is that at the end of 1 outer loop the largest element is in names[n-1]
After 2 outer loops, 2 elements are sorted [n-2] and [n-1]. So there is no need to check these elements.
And so on.
Related
I'm just trying to write a simple code where I enter a 3 letter word and then print out the word I entered. I tried doing this by creating the array, and then making a loop where the counter "i" keeps incrementing and the scan function keeps working for each index value of the letter I add.
But there seems to be some error in line 16, and even then not sure if the logic of the code is right.
#include <string.h>
#define ALEN 3
int main (void)
{
char array[ALEN];
int i;
printf("Enter a 3 letter word> ");
scanf("%s", array);
for(i=0; i<ALEN; i++)
{
array[i] = array[ALEN];
scanf("%s", &array[i]);
}
printf("\n");
printf("Word entered: %s", char array[i]);
return 0;
}```
I'm trying to ask K amounts of words to add them in a matrix.
And i have 2 problems:
I tried to make the condition that the strlen(string) must be less than the size of n(matrix size). But when it enters the do while loop, it never quits.
How can i make the for loop to repeat until k words are entered?
I already tried a few days ago, and the do while worked fine. Until i changed something and it got messy.
/* Enter the matrix dimension */
int n;
do{
printf("\nEnter the matrix size");
scanf("%d", &n);
}while(2>n);
/* Ask for the amount of words the user will enter */
int k;
do{
printf("\nInsert how many words you will enter:");
scanf("%d", &k);
}while(k<0);
/* k Words loop */
int amountOfWords=0;
char string[20];
int i;
for(i=0; i<k; i++, amountOfWords++)
{
do {
printf("\nEnter the %d word:\n", amountOfWords+1);
scanf("%s", &string);
}while(strlen(string) > n);
}
The problem with your current code is that the amountOfWords variable is never incremented inside the do-while loop, so the condition for the loop strlen(string) > n is always true.
Here is one way to fix the problem:
int amountOfWords=0;
char string[20];
for(int i=0; i<k; i++)
{
do {
printf("\nEnter the %d word:\n", i+1);
scanf("%s", string);
}while(strlen(string) > n);
amountOfWords++;
}
In this way, if the user enters a word that is longer than the maximum size (n), the loop will ask again for a word until a valid word is entered, and the variable amountOfWords will be incremented after a valid word is entered.
Another way to do it could be using a while loop, like this:
int amountOfWords=0;
char string[20];
int i=0;
while(amountOfWords<k)
{
printf("\nEnter the %d word:\n", amountOfWords+1);
scanf("%s", string);
if(strlen(string) <= n)
{
amountOfWords++;
}
}
In this way, the loop will keep running until amountOfWords reaches the desired amount of words (k).
Task is to display the array that has no repetitions based on some user generated input.
I'm trying to compare the number with every number before it, if the equality happens, a=1, it should skip it. Code doesn't return anything.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int X[30],Y[30],i,j,k=0,a,N;
printf("Length of the vector: ");
scanf("%d",&N);
printf("Input the numbers: ");
for(i=0;i<N;i++)
scanf("%d",X+i);
Y[0]=X[0];
for(i=1;i<N;i++){
for(j=i-1;j>=0;j--)
if(X[i]=X[j])
a=1;
if(a==0){
k++;
Y[k]=X[i];
}
a=0;
}
for(i=0;i<k;i++)
printf("%d",Y[i]);
}
Three separate issues in your code block:
a is not initialized the first time through your loop. Add a line a = 0; above your loop.
Your if block reads if(X[i]=X[j]); it should be if(X[i] == X[j]) (you're missing one =)
Your final value of k is going to be one less than the total number of elements that you have. Change your final for loop to i = 0; i <= k; i++
What am I doing wrong? the program run but the output isn't in the right order.
#include <stdio.h>
int main () { /*program to ask user to input array values and sort them in ascending order.*/
int n,j,i,temp;
printf ("how many numbers?\n");
scanf ("%d",&n);
int a[n];
for (i=0;i<n;i++){
printf ("enter number");
scanf ("%d",&a[i]);
}
for (i=0;i<n;i++); {
for (j=i+1;j<n;j++){
if (a[i]>a[j]){
temp=a[i];
a[i]=a[j];
a[j]=temp; }
} }
printf("The numbers arranged in ascending order are given below \n");
for (i = 0; i < n; ++i)
printf("%d\n", a[i]);
}
Change
for (i=0;i<n;i++); {
To
for (i=0;i<n-1;i++) {
Semicolon was executed instead of following błock {}
Element form right/end cant propagate to left, because for example first element of array can be swapped only at first check with second element.
I am trying to learn C and here i got a program in which we have to take the input from the user as n number os strings, compare it and arrange it in a alphabetical order. After arranging them in a alphabetical order , i have to only print the last name which was occurring in the order.
Here is the code for the above problem:
#include<stdio.h>
#include<string.h>
int main()
{
int i,j,m,n,len;
char a[50][50],temp[100];
char last ;
printf("Enter the number of elements you wish to order : ");
scanf("%d",&m);
printf("\nEnter the names :\n");
for (i=0;i<m;i++){
scanf("%s",a[i]);
}
for (i=0;i<m;i++){
for (j=i+1;j<m+1;j++) {
if (strcmp(a[i],a[j])>0) {
strcpy(temp,a[i]);
strcpy(a[i],a[j]);
strcpy(a[j],temp);
}
}
}
printf("\n\nSorted strings are : ");
for (i=0;i<m+1;i++){
printf("%s \n",a[i]);
}
return 0;
}
~
The Answer goes this way:
Enter the number of elements you wish to order : 4
Enter the names :
territory
states
hello
like
Sorted strings are : S$???
hello
like
states
territory
My question goes that why am i getting "S$???" and i want only the last word "territory should be printed out not all the names".
Can anyone let me know where am i going wrong? It will be a great help.
Thanks
Tanya
You are sorting m+1 strings with indexes [0..m]. But you input only m strings.
Your indexes should never go above m-1.
\Check this code
In your code you get input as 4
then
a[0]=territory
a[1]=states
a[2]=hello
a[3]=like
But your code runs upper loop at most 3 time then i=3
In next loop j=i+1 then j=4
but a[4]=not exists
Thats why "S$???" occurs
Solution:
#include<stdio.h>
#include<string.h>
int main() {
int i, j, m, n, len;
char a[50][50], temp[100];
char last;
printf("Enter the number of elements you wish to order : ");
scanf("%d", &m);
printf("\nEnter the names :\n");
for (i = 0; i < m; i++) {
scanf("%s", a[i]);
}
for (i = 0; i < m - 1; i++) { // m - 1 enough maximum i = 2;
for (j = i + 1; j < m; j++) { // j maximum j = i + 1 j = 3
if (strcmp(a[i], a[j]) > 0) {
strcpy(temp, a[i]);
strcpy(a[i], a[j]);
strcpy(a[j], temp);
}
}
}
printf("\n\nSorted strings are : "); // print all words in sorted order
for (i = 0; i < m; i++) {
printf("%s \n", a[i]);
}
printf("Last Word:\n");
printf("%s\n", a[m - 1]); // a[3] contains last name
return 0;
}
this was my program it worked for me in turbo c++
#include<conio.h>
#include<iosream.h>
#include<ctype.h>
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
void main()
{
clrscr();
char name[100];
int c=0;
// to take the name including spaces
gets(name);
//this line is to print the first character of the name
cout<<name[0];
//this loop is to print the fist character which is there after every space
for(int l=0;name[l]!='\0';l++)
{
if(name[l]==' ')
{
cout<<"."<<name[l+1];
//l+1 is used because l is the space and l+1 is the character that we need
}
}
//this loop is to find out the last space in the entire sting
for(int i=0;name[i]!='\0';i++)
{
if(name[l+1]==NULL)
{
//here we fond the last space in the string
for(int j=i;name[j]!=' ';j--)
{
c=j+1;
}
// c=j+1 is used bacause we have already taken the first letter of the that word
//no need of taking it again
}
}
//this loop starts from the last space and the position(of space) is stored in k
for(int k=c;name[k]!='\0';k++)
{
cout<<name[k];
}
getch();
}
output:
anentt ranjan shukla
a.r.shukla