Printing asterisk pattern using nested for loops in C - c

This code is intended to print a pattern with asterisk like this
If a number is entered such as 5
Then the program should print the following pattern. It should print * in order according to the number given and then decreasing
*****
****
***
**
*
But it is printing only one line. Please tell me what is the fault here.
#include<stdio.h>
int main()
{
int lines,lines2;
printf("Enter the number of lines : ");
scanf("%d",&lines);
lines2=lines;
for(;lines>0;lines--) {
for(;lines2>0;lines2--){
printf("*");
}
}
printf("\n");
return 0;
}

First: The following line should be placed between two loop:
lines2=lines;
Second: The following line should be placed before the { of outer loop:
printf("\n");
The Final solution is:
#include<stdio.h>
int main()
{
int lines,lines2;
printf("Enter the number of lines : ");
scanf("%d",&lines);
for(;lines>0;lines--)
{
lines2=lines;
for(;lines2>0;lines2--)
{
printf("*");
}
printf("\n");
}
return 0;
}

lines2=lines;
for(;lines>0;lines--)
{ for(;lines2>0;lines2--)
You only initialize lines2 once BEFORE the outer loop; that is why past the first line it is always zero. You should reset it per each line, assigning to current value of lines. This one is probably what you wanted to do:
for(; lines > 0; --lines) {
for(lines2 = lines; lines2 > 0; --lines2) {

See this!
It works!
#include<stdio.h>
main()
{ int lines,lines2;
printf("Enter the number of lines : ");
scanf("%d",&lines);
lines2=lines;
for(;lines>0;lines--)
{ for(lines2=lines;lines2>0;lines2--)
{ printf("*");
}
printf("\n");
}
}

You just changed some lines' places. You need to put newline into first loop:
int main() {
int lines,lines2;
printf("Enter the number of lines : ");
scanf("%d", &lines);
for(;lines>0;lines--) {
lines2=lines;
for(;lines2>0;lines2--){
printf("*");
}
printf("\n");
}
return 0;
}

Related

My C code for a genetic algortihtm is not functioning, it dosent enter into the if condition

This is GA for a timetable problem. I'm trying to create an initial population, but it isn't working as it isn't entering the if condition. can someone point out the error?
I tried inserting statements in each condition, but everything checks out. Still, I don't seem to find a solution.
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include<ctype.h>
#include<time.h>
int random_number_creator(int upper, int lower)
{
int n;
n = rand() % (upper-lower)+ lower;
return n;
}
struct pop{
int subjects[6];
int days[5][9];
}oldpop, bench;
main()
{
int i,j,s=1,d,h,stop=1,cou=0;
for(i=0;i<5;i++)
{
for(j=0;j<9;j++)
if(j!=6)
bench.days[i][j]=0;
else
bench.days[i][j]=11111;
}
for(i=0;i<6;i++)
{
if(i<4)
oldpop.subjects[i]=3;
else
oldpop.subjects[i]=2;
}
for(i=0;i<5;i++)
{
printf("\n");
for(j=0;j<9;j++)
printf(" %d",bench.days[i][j]);
}
for(i=0;i<6;i++)
{
printf(" \n %d",oldpop.subjects[i]);
}
cou=0;
for(i=0;i<6;i++)
{
cou=cou+ oldpop.subjects[i];
}
printf("\n%d\n",cou);
do
{
s=random_number_creator(5,0);
printf("\nsubject number:%d\n",s);
printf("\nloop 1 entery %d",cou);
do
{
printf("\nloop 2 entry\n");
d=random_number_creator(5,0);h=random_number_creator(8,0);
printf("\nDay Number:%d \nHour Number:%d\n",d,h);
if(bench.days[d][h]==0&&oldpop.subjects[s]!=0)
{
printf("\nif condition reached\n");
oldpop.days[d][h]=10+s;
bench.days[d][h]=11111;
stop=0;
cou--;
oldpop.subjects[s]--;
}
else
{
printf("\nIf condition not satisified.\n");
break;
}
}while(stop!=0);
}while(cou!=0);
for(i=0;i<5;i++)
{
printf("final entery \n");
for(j=0;j<9;j++)
printf(" %d",oldpop.days[i][j]);
}
}
I want the oldpop variable to be initialized for this timetable problem but the code does not enter the if condition in the do while loop.
The problem in your program comes from the subject selection (after adding the missing }):
s=random_number_creator(5,0);
Will return a random number between 0 and 4 included.
To correct this, just replace this line by
s=random_number_creator(7,0);
To pick a number between 0 and 6. So the cou variable will be able to reach 0
Your code can be improved:
Instead of this kind of block:
for(i=0;i<5;i++)
{
printf("final entery \n");
for(j=0;j<9;j++)
printf(" %d",oldpop.days[i][j]);
}
Create a function, learn to use printf:
void print_table(struct pop pop, const char *label)
{
int i, j;
printf("\n%s\n", label);
for (i=0;i<5;i++)
{
for (j=0;j<9;j++)
{
printf(" %5d",pop.days[i][j]);
}
}
}
And use it this way
print_table(oldpop, "oldpop");

Function Crashes Main After Finishing Execution - C

I made this simple program that asks the user to input the number of columns the matrix called arp is going to have because, that way when the program asks the user to input a number so it can find matches on the numbers stored at the array without comparing all 10 columns allocated on memory with array to pointer type.
The problem here comes when the user inputs into the columns size definition 2. All works fine before the last function of p3() does its job, then it doesn't even return to main to execute the infinite loop defined there. I have tried removing the pointers and didn't work; I also tried removing other parts of the code but still nothing...
Update: Tried removing the function to find elements felmnt() and still the same.
Here is The Buggy Code:
#include <stdio.h>
#include <stdlib.h>
int loop = 1;
void keepalive(void)
{
int ckr = 0;
fflush(stdin);
printf("\n\n ******[s]<< CONTINUE | EXIT >>[n]******\n");
while(printf(" > ") && (ckr = getchar()) != 's' && ckr != 'n') fflush(stdin);
getchar();
if(ckr == 'n') loop = 0;
system("CLS");
}
void felmnt(int *colu, int (*arp)[10])
{
int nius=0, colmts, x, i, ejct;
do
{ // loop to let the user find more elements inside matrix
colmts=0;
printf("\n Insert The Number To Find\n > ");
scanf("%d", &nius);
for(x=0; x<*colu; x++) // search of element inside matrix
{
for(i=0; i<=9; i++)
if(nius == arp[i][x])
colmts++;
}
if(colmts>1) // results printing
{
printf("\n %d Elements Found", colmts);
}else if(colmts)
{
printf("\n 1 Element Found");
}else
{
printf("\n Not Found");
}
printf("\n TRY AGAIN? s/n\n > ");
ejct=getchar();
getchar();
}while(ejct=='s');
}
void mat(int *colu, int (*arp)[10])
{
int ci, cn, tst=0;
for(ci=0; ci<*colu; ci++)
{
for(cn=0; cn<10; cn++)
{
printf("\n Input The Number [%d][%d]\n > ", ci+1, cn+1);
scanf(" %d", &arp[cn][ci]);
}
}
printf(" Numbers Inside Matrix> ");
for(ci = 0; ci<*colu; ci++)
{
for(cn=0; cn<10; cn++) printf(" %d", arp[cn][ci]);
}
}
void p3(void)
{ // >>>>main<<<<
int colu=0;
while(loop)
{
printf("\n Input The Quantity Of Columns To Use\n > ");
scanf("%d", &colu);
int arp[10][colu];
mat(&colu, arp);
felmnt(&colu, arp);
keepalive();
}
}
int main(void)
{
int ck = 0, ndx;
while(1)
{ // infinite loop
p3();
fflush(stdin);
printf("\nPause !!!");
getchar();
}
return 0;
}

Matrix multiplication

I can't understand where is the mistake. Help me correct it please. The output is coming as all the elements of resultant matrix being zero.
#include<stdio.h>
#include<conio.h>
int main()
{
int a[5][5],b[5][5],c[5][5],i=0,j=0,row1,col1,row2,col2,row3,col3,s=0,k=0,l=0;
printf("Enter no. of rows and no. of columns of first matrix:\n");
scanf("%d %d",&row1,&col1);
printf("Enter no. of rows and no. of columns of second matrix:\n");
scanf("%d %d",&row2,&col2);
if(col1==row2)
{
row3=row1;
col3=col2;
}
else
{
printf("Not possible!");
exit(1);
}
printf("Enter elements of first matrix:\n");
for(i=0;i<row1;i++)
{
for(j=0;j<col1;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter elements of second matrix:\n");
for(i=0;i<row2;i++)
{
for(j=0;j<col2;j++)
{
scanf("%d",&b[i][j]);
}
}
i=0;
j=0;
for(k=0;k<row3;k++)
{
for(l=0;l<col3;l++)
{
while(i<row3 || j<col3)
{
//printf("Hi");
s=s+a[i][j++]*b[i++][j];
//printf("%d\n",s);
}
}
printf("%d\n",s);
c[k][l]=s;
s=0;
}
printf("Sum matrix is:\n");
for(k=0;k<row3;k++)
{
for(l=0;l<col3;l++)
{
printf("%d ",c[k][l]);
}
printf("\n");
}
getch();
}
I have included comments of printing in the while loop so as to debug but it's not helping.
You are setting the result outside of your column loop, so you only set one result per row. Change the code to this by moving those 3 lines inside the brace:
for(k=0;k<row3;k++)
{
for(l=0;l<col3;l++)
{
i = 0; j = 0;
while(i<row3 || j<col3)
{
//printf("Hi");
s=s+a[k][j++]*b[i++][l];
//printf("%d\n",s);
}
// THIS CODE HAS MOVED:
printf("%d\n",s);
c[k][l]=s;
s=0;
}
}
Also, your addition needs to use the k and l indices, so that you move along a row of a[][] given by k and a column of b[][] given by l:
s=s+a[k][j++]*b[i++][l];
You forgot to initialize i and j inside the loop where you add the two matrices.
According to your code add.
i=0; j=0 inside the double for loop for addition.
Hope this helps

DFA is not accepting strings

my program is supposed to implement a dfa for a binary string... dfa is a machine that can be in only one state at a time (when you enter a string the machine should use it and at the last step it should reach to the final state. if so, we say that string is accepted by the machine) ...
this machine works this way:
at first program asks the number of states, if u consider my pic, u see that it has 3 states(q0,q1,q2) so we enter 3. then it asks about the number of inputs. my inputs are 0,1 so I enter 2... then it asks to enter the inputs, we enter 0 then 1! then it asks the number of final states, the final state here is only q1... so we enter it... then u see this: (q0,0) = q it means q0 goes to which state with 0... for example here q0 goes to q0 with 0 ... others are like that. after filling this part, we enter the sring and it would say if string is valid or not
here is the code:
#include<stdio.h>
#include<conio.h>
int ninputs;
int check(char,int ); //function declaration
int dfa[10][10];
char c[10], string[10];
int main()
{
int nstates, nfinals;
int f[10];
int i,j,s=0,final=0;
printf("enter the number of states that your dfa consist of \n");
scanf("%d",&nstates); // 3
printf("enter the number of input symbol that dfa have \n");
scanf("%d",&ninputs); // 2
printf("\nenter input symbols\t");
for(i=0; i<ninputs; i++)
{
printf("\n\n %d input\t", i+1);
printf("%c",c[i]=getch()); // 01
}
printf("\n\nenter number of final states\t");
scanf("%d",&nfinals); // 1
for(i=0;i<nfinals;i++)
{
printf("\n\nFinal state %d : q",i+1);
scanf("%d",&f[i]); // 1
}
printf("-----------------------------------------------------------------------");
printf("\n\ndefine transition rule as (initial state, input symbol ) = final state\n");
for(i=0; i<ninputs; i++)
{
for(j=0; j<nstates; j++)
{
printf("\n(q%d , %c ) = q",j,c[i]);
scanf("%d",&dfa[i][j]);
// q(0,0)=0
// q(1,0)=0
// q(2,0)=2
// q(0,1)=1
// q(1,1)=2
// q(2,1)=1
}
}
do
{
i=0;
printf("\n\nEnter Input String.. ");
scanf("%s",string); // 01
while(string[i]!='\0')
{
if((s=check(string[i++],s))<0)
break;
for(i=0 ;i<nfinals ;i++)
{
if(f[i] ==s )
final=1;
if(final==1)
printf("\n valid string");
else
printf("invalid string");
getch();
printf("\nDo you want to continue.? \n(y/n) ");
}
}
}
while(getch()=='y');
getch();
}
int check(char b,int d)
{
int j;
for(j=0; j<ninputs; j++)
if(b==c[j])
return(dfa[d][j]);
return -1;
}
the problem is that when I enter my string, the program says it's invalid, however it should be accepted by the machine... for example consider the machine in the photo and test this string on it: 01
so what's wrong with the code?
Optimized C code for Accepting String using DFA
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
int a,b,i,j,k,state,ch;
char s[10][10],*st,v[10],ss[10];
printf("Enter the number of state:\n");
scanf("%d",&a);
printf("Enter State :\n");
for(i=0;i<a;i++)
{
fflush(stdin);
scanf("%c",&ss[i]);
}
printf("Enter th no. of var..:\n");
scanf("%d",&b);
printf("Enter variable :\n");
for(i=0;i<b;i++)
{
fflush(stdin);
scanf("%c",&v[i]);
}
printf("Enter table:\n");
for(i=0;i<a;i++)
{
for(j=0;j<b;j++)
{
fflush(stdin);
scanf("%c",&s[i][j]);
}
}
printf("Enter string :\n");
fflush(stdin);
gets(st);
i=0;
state=0;
while(st[i]!='\0')
{
for(j=0;j<b;j++)
{
if(st[i]==v[j])
{
if(s[state][j]=='-')
{
goto check;
}
else
{
for(k=0;k<a;k++)
{
if(s[state][j]==ss[k])
{
printf("State:%c\n",s[state][j]);
state=k;
goto o;
}
}
}
o:
}
}
i++;
}
check:
ch=1;
for(i=0;i<b;i++)
{
if(s[state][i]!='-')
{
ch=0;
}
}
if(ch==1)
{
printf("String is matching..");
}
else
{
printf("String is not matching..");
}
getch();
return 0;
}
Just put an space before %c . And edit some lines of the code.
This code is successfully complied on Code::Blocks 13.12 version.
As it C++ Compiler save the file with .cpp extension.
And Click On the " output image " . You will see how to input & output from
console
<--------Here Is the edited code && It will work fine ---> #
output image
#include<stdio.h>
#include<cstdio>
#include<iostream>
int ninputs,bb;
int check(char,int ); //function declaration
int dfa[10][10];
char c[10], string[10],b;
int main()
{
int nstates, nfinals;
int f[10];
int i,j,s=0,final=0;
printf("enter the number of states that your dfa consist of \n");
scanf("%d",&nstates);
printf("enter the number of input symbol that dfa have \n");
scanf("%d",&ninputs);
printf("\nenter input symbols");
for(i=0; i<ninputs; )
{
bb =i;
printf("\n %d input",bb+1);
// printf(" %c",c[i]=getchar());
scanf(" %c" , &c[i]); //just put an space before %c
i++;
}
printf("\n\nenter number of final states\t");
scanf("%d",&nfinals);
for(i=0;i<nfinals;i++)
{
printf("\n\nFinal state %d : q",i+1);
scanf("%d",&f[i]);
}
printf("-----------------------------------------------------------------------");
printf("\n\ndefine transition rule as (initial state, input symbol ) = final state\n");
for(i=0; i<ninputs; i++)
{
for(j=0; j<nstates; j++)
{
printf("\n(q%d , %c ) = q",j,c[i]);
scanf("%d",&dfa[i][j]);
}
}
do
{
i=0;
printf("\n\nEnter Input String.. ");
scanf("%s",string);
while(string[i]!='\0')
if((s=check(string[i++],s))<0)
break;
for(i=0 ;i<nfinals ;i++)
if(f[i] ==s )
final=1;
if(final==1)
printf("\n valid string");
else
printf("invalid string");
printf("\nDo you want to continue.? \n(y/n) ");
}
while(b =='y');
scanf(" %c", &b); // chnge here
}
int check(char b,int d)
{
int j;
for(j=0; j<ninputs; j++)
if(b==c[j])
return(dfa[d][j]);
return -1;
}
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
main()
{
int state,symbol;
char str[30];
cout<<"Enter the string which you want to check :: "<<endl;
fgets(str,sizeof(str),stdin);
cout<<"Enter the Number of state :: ";cin>>state;
cout<<"Enter the Number of input symbol :: ";cin>>symbol;
cout<<"Enter the states : "<<endl;
char st[state];
for(int i=0;i<state;i++)
{
cout<<"state : "<<i<<" : ";cin>>st[i];
}
cout<<"Enter the input symbol : "<<endl;
char sy[symbol];
for(int i=0;i<symbol;i++)
{
cout<<"symbol : "<<i<<" : ";cin>>sy[i];
}
char table[state][symbol];
cout<<"------Enter next move or state------ if no relation put -"<<endl;
for(int i=0;i<state;i++)
{
for(int j=0;j<symbol;j++)
{
cout<<"("<<st[i]<<", "<<sy[j]<<") = ";cin>>table[i][j];
}
}
char ststate,fnstate;
cout<<"Start state :: ";cin>>ststate;
cout<<"Final state :: ";cin>>fnstate;
cout<<"----------------------------------"<<endl;
int str_len=strlen(str);
int p,q;
int flag=1;
int j=0;
for(j=0;j<str_len-1;j++)
{
cout<<"input state"<<endl;
for(int i=0;i<state;i++)
{
if(st[i]==ststate)
{
p=i;
cout<<p<<endl;
break;
}
else
{
p=-1;
}
}
cout<<"input string"<<endl;
for(int i=0;i<state;i++)
{
if(sy[i]==str[j])
{
q=i;
// cout<<q<<endl;
break;
}
else
{
q=-1;
}
}
if(p!=-1 && q!=-1)
{
cout<<"table output :: "<<table[p][q]<<endl;
ststate=table[p][q];
}
}
cout<<endl;
cout<<"----------------------------------------------------------------------------------";
if((table[p][q]==fnstate) && (j==str_len-1))
{
cout<<"String is recognized"<<endl;
flag=0;
}
if(flag!=0)
{
cout<<"String is not recognized.";
}
cout<<endl;
return 0;
}
This part of the code:
while(string[i]!='\0')
{
if((s=check(string[i++],s))<0)
break;
for(i=0 ;i<nfinals ;i++)
{
uses and changes i in both loops. You need to use something else in one of them.

Print the last string name in C

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

Resources