I am trying to input some data into a file and then read and print it on the console.
Here is my code:
fp=fopen("user1","w+");
char line[1000];
char *c;
//write on file
while(1)
{
fgets(line,sizeof(line),stdin);
if(strcmp(line,":wq\n")==0) //input ends when user enters :wq
break;
else
fputs(line,fp);
}
//read from file
fflush(stdin);
while(1)
{
c=fgetc(fp);
if(c==EOF)
break;
else
printf("%ch",c);
}
I input the data as
bjsa
:wq
The output:
h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h h
What is the problem?
I see two problems
1) Your fgetc assigns to a char point. That is wrong. It shall be an int
2) After writing the file, you should close it and then open it for reading
Something like:
fp=fopen("user1","w+");
char line[1000];
int c; // notice ......
//write on file
while(1)
{
fgets(line,sizeof(line),stdin);
if(strcmp(line,":wq\n")==0) //input ends when user enters :wq
break;
fputs(line,fp);
}
fclose(fp);
//read from file
fp=fopen("user1","r");
while(1)
{
c=fgetc(fp);
if(c==EOF)
break;
printf("%ch",c);
}
fclose(fp);
Related
I've been trying to make a calculator in C and I am having some trouble cause when I said I wanted to choose again the program ends, or sometimes it works.
I tried this:
#include <stdio.h>
int main(void)
{
int xx;
int Y, N;
int a, b, c, d;
int aa, bb, Sum, ee, ff, Multi;
float cc, dd, Sub, gg, hh, Divi;
printf("\n\nC a l c u l a t o r\n\n");
printf("C h o o s e :\n\n");
printf(" S u m ( 1 ) \t");
printf(" S u b t r a c t i o n ( 2 )\n\n");
printf(" M u l t i p l i c a t i o n ( 3 ) \t");
printf(" D i v i s i o n ( 4 )\n\n");
scanf("%d", &xx);
a = 1;
b = 2;
c = 3;
d = 4;
Y = 10;
N = 20;
if (a == xx)
{
printf("\n\nE n t e r F i r s t N u m b e r :\n");
scanf("%d", &aa);
printf("\n\nE n t e r S e c o n d N u m b e r :\n");
scanf("%d", &bb);
Sum = aa + bb;
printf("%d + %d = %d", aa, bb, Sum);
xx = xx - 1;
printf("\n\nC h o o s e a g a i n ?\n");
printf(" ( Y e s = = S a y 1 0 !)\n");
printf(" ( N o = = S a y 2 0 !)\n");
scanf("%d", &xx);
if (Y == xx)
{
printf("\n\nC h o o s e :\n\n");
printf(" S u m ( 1 ) \t");
printf(" S u b t r a c t i o n ( 2 )\n\n");
printf(" M u l t i p l i c a t i o n ( 3 ) \t");
printf(" D i v i s i o n ( 4 )\n\n");
scanf("%d", &xx);
}
if (N == xx)
{
printf("\n\n F I N\n\n");
}
}
if (b == xx)
{
printf("\n\nE n t e r F i r s t N u m b e r :\n");
scanf("%f", &cc);
printf("\n\nE n t e r S e c o n d N u m b e r :\n");
scanf("%f", &dd);
Sub = cc - dd;
printf("%f - %f = %f", cc, dd, Sub);
xx = xx - 2;
printf("\n\nC h o o s e a g a i n ?\n");
printf(" ( Y e s = = S a y 1 0 !)\n");
printf(" ( N o = = S a y 2 0 !)\n");
scanf("%d", &xx);
if (Y == xx)
{
printf("\n\nC h o o s e :\n\n");
printf(" S u m ( 1 ) \t");
printf(" S u b t r a c t i o n ( 2 )\n\n");
printf(" M u l t i p l i c a t i o n ( 3 ) \t");
printf(" D i v i s i o n ( 4 )\n\n");
scanf("%d", &xx);
}
if (N == xx)
{
printf("\n\n F I N\n\n");
}
}
if (c == xx)
{
printf("\n\nE n t e r F i r s t N u m b e r :\n");
scanf("%d", &ee);
printf("\n\nE n t e r S e c o n d N u m b e r :\n");
scanf("%d", &ff);
Multi = ee * ff;
printf("%d x %d = %d", ee, ff, Multi);
xx = xx - 3;
printf("\n\nC h o o s e a g a i n ?\n");
printf(" ( Y e s = = S a y 1 0 !)\n");
printf(" ( N o = = S a y 2 0 !)\n");
scanf("%d", &xx);
if (Y == xx)
{
printf("\n\nC h o o s e :\n\n");
printf(" S u m ( 1 ) \t");
printf(" S u b t r a c t i o n ( 2 )\n\n");
printf(" M u l t i p l i c a t i o n ( 3 ) \t");
printf(" D i v i s i o n ( 4 )\n\n");
scanf("%d", &xx);
}
if (N == xx)
{
printf("\n\n F I N\n\n");
}
}
if (d == xx)
{
printf("\n\nE n t e r F i r s t N u m b e r :\n");
scanf("%f", &gg);
printf("\n\nE n t e r S e c o n d N u m b e r :\n");
scanf("%f", &hh);
Divi = gg / hh;
printf("%f / %f = %f", gg, hh, Divi);
xx = xx - 4;
printf("\n\nC h o o s e a g a i n ?\n");
printf(" ( Y e s = = S a y 1 0 !)\n");
printf(" ( N o = = S a y 2 0 !)\n");
scanf("%d", &xx);
if (Y == xx)
{
printf("\n\nC h o o s e :\n\n");
printf(" S u m ( 1 ) \t");
printf(" S u b t r a c t i o n ( 2 )\n\n");
printf(" M u l t i p l i c a t i o n ( 3 ) \t");
printf(" D i v i s i o n ( 4 )\n\n");
scanf("%d", &xx);
}
if (N == xx)
{
printf("\n\n F I N\n\n");
}
}
}
I've tried a lot of times trying to fix the code but it simply doesn't.
You have a lot of variables and repetition of code for no reason. I realize that my answer behaves differently than original question but looking at the code I don't think you understand what you really want. Start with this:
#include <stdio.h>
enum {
ADD = 1,
SUBTRACT,
MULTIPLY,
DIVIDE,
YES = 10,
NO = 20,
};
int main(void) {
int choice;
double values[2];
for(;;) {
printf(
"\n\nC a l c u l a t o r\n\n"
"C h o o s e :\n\n"
" S u m ( 1 ) \t"
" S u b t r a c t i o n ( 2 )\n\n"
" M u l t i p l i c a t i o n ( 3 ) \t"
" D i v i s i o n ( 4 )\n\n"
);
if(scanf(" %d", &choice) != 1) {
printf("scanf failed\n");
return 1;
}
printf("\n\nE n t e r F i r s t N u m b e r :\n");
if(scanf("%lf", &values[0]) != 1) {
printf("scanf failed\n");
return 1;
}
printf("\n\nE n t e r S e c o n d N u m b e r :\n");
if(scanf("%lf", &values[1]) != 1) {
printf("scanf failed\n");
return 1;
}
if (choice == ADD) {
double result = values[0] + values[1];
printf("%g + %g = %g", values[0], values[1], result);
} else if(choice == SUBTRACT) {
double result = values[0] - values[1];
printf("%g - %g = %g", values[0], values[1], result);
} else if(choice == MULTIPLY) {
double result = values[0] * values[1];
printf("%g * %g = %g", values[0], values[1], result);
} else if(choice == DIVIDE) {
if(values[1] == 0) {
printf("Cannot divide by zero\n");
} else {
double result = values[0] / values[1];
printf("%g / %g = %g", values[0], values[1], result);
}
}
printf("\n\nC h o o s e a g a i n ?\n");
printf(" ( Y e s = = S a y 1 0 !)\n");
printf(" ( N o = = S a y 2 0 !)\n");
if(scanf("%d", &choice) != 1) {
printf("scanf failed\n");
return 1;
}
if(choice == NO)
break;
}
printf("\n\n F I N\n\n");
}
The space between letters makes the prompt unnecessarily hard to read.
Consider changing the values you accept to be '+', '-', '*', '/' for the operators and 'y' and 'n' for the repeat prompts. This would be much easier on for the user of your program.
Should something different happen if either the first or 2nd choice is wrong? For instance, you could loop the prompt till you get a valid choice.
i wrote a code and i dont know how to continue from here .. i want to build an abc pyramide from start to back (a ,aba,abcba..etc) for example
a
a b a
a b c b a
a b c d c b a
etc..
this is my code , thanks :)
void aba(int lines)
{
//int i = 97;
char a = 97;
for (int i = 97;i <= lines + 97;i++)
{
printf("%c",i);
for (int j = 97;j <= lines + 97;j++)
{
if (j == i)
break;
printf("%c%c", j,i);
}
printf("\n");
}
void main()
{
aba(3);
}
If you have problems solving a given task always try to split it into smaller jobs:
Start by printing an a for every line of your pyramid:
void aba(int lines) {
for (int i = 0; i < lines; i++) {
printf("%c\n", a);
}
}
Now you want to have a pyramid with one character in the first line, 3 in the second, 5 in the third and so on. You can produce this sequence using (i * 2) + 1:
void aba(int lines) {
for (int i = 0; i < lines; i++) {
for (int j = 0; j < (i * 2) + 1 ; j++) {
printf("%c", a);
}
printf("\n");
}
}
The last step would be to increase the character in the first half of the line and decrease it in the last half:
void aba(int lines) {
for (int i = 0; i < lines; i++) {
char a = 'a';
for (int j = 0; j < (i * 2) + 1 ; j++) {
printf("%c", a);
if (j <= i - 1)
a += 1;
else
a -= 1;
}
printf("\n");
}
}
As it is homework, I give you a hint, not the solution:
You should observe the pattern: All lines start with a.
When you numerate the lines from top to bottom starting with 0, the line 0 has an a and 0 additional characters.
line 1 starts with the a and has 1 more upcounting character (b) and then 1 downcounting character (a).
line 2 starts with the a and has 2 more upcounting character (b c) and then 2 downcounting character (b a).
...
So, line i starts with the a and has i more upcounting characters (b c d ....) and then i downcounting characters (... c b a).
Now you have to translate that into code.
void aba(int n)
{
for (int i = 0; i < n; i++)
{
//print here what all lines have in common
for (int j = 1; j <= i; j++)
{
//print the upcounting characters
}
for (int j = 1; j <= i; j++)
{
//print the downcounting characters
}
}
}
For starters pay attention to that according to the C Standard the function main without parameters shall be declared like
int main( void )
It is not necessary that lower case letters follow each other without gaps. For example this in not correct for the EBCDIC table.
Here is a demonstrative program that shows how the required output can be obtained.
#include <stdio.h>
int main(void)
{
const char alphabet[] = "abcdefghijklmnopqrstuvwxyz";
const size_t N = sizeof( alphabet ) - 1;
while ( 1 )
{
size_t n = 0;
printf( "Enter a non-negative number not greater than %zu (0 - exit ): ", N );
if ( scanf( "%zu", &n ) != 1 || n == 0 ) break;
n %= N + 1;
putchar( '\n' );
for ( size_t i = 0; i < n; i++ )
{
const char *p = alphabet;
do { printf( "%c ", *p++ ); } while ( p != alphabet + i + 1 );
if ( --p != alphabet )
{
do { printf( "%c ", *--p ); } while ( p != alphabet );
}
putchar( '\n' );
}
putchar( '\n' );
}
return 0;
}
The program output might look like
Enter a non-negative number not greater than 26 (0 - exit ): 26
a
a b a
a b c b a
a b c d c b a
a b c d e d c b a
a b c d e f e d c b a
a b c d e f g f e d c b a
a b c d e f g h g f e d c b a
a b c d e f g h i h g f e d c b a
a b c d e f g h i j i h g f e d c b a
a b c d e f g h i j k j i h g f e d c b a
a b c d e f g h i j k l k j i h g f e d c b a
a b c d e f g h i j k l m l k j i h g f e d c b a
a b c d e f g h i j k l m n m l k j i h g f e d c b a
a b c d e f g h i j k l m n o n m l k j i h g f e d c b a
a b c d e f g h i j k l m n o p o n m l k j i h g f e d c b a
a b c d e f g h i j k l m n o p q p o n m l k j i h g f e d c b a
a b c d e f g h i j k l m n o p q r q p o n m l k j i h g f e d c b a
a b c d e f g h i j k l m n o p q r s r q p o n m l k j i h g f e d c b a
a b c d e f g h i j k l m n o p q r s t s r q p o n m l k j i h g f e d c b a
a b c d e f g h i j k l m n o p q r s t u t s r q p o n m l k j i h g f e d c b a
a b c d e f g h i j k l m n o p q r s t u v u t s r q p o n m l k j i h g f e d c b a
a b c d e f g h i j k l m n o p q r s t u v w v u t s r q p o n m l k j i h g f e d c b a
a b c d e f g h i j k l m n o p q r s t u v w x w v u t s r q p o n m l k j i h g f e d c b a
a b c d e f g h i j k l m n o p q r s t u v w x y x w v u t s r q p o n m l k j i h g f e d c b a
a b c d e f g h i j k l m n o p q r s t u v w x y z y x w v u t s r q p o n m l k j i h g f e d c b a
Enter a non-negative number not greater than 26 (0 - exit ): 10
a
a b a
a b c b a
a b c d c b a
a b c d e d c b a
a b c d e f e d c b a
a b c d e f g f e d c b a
a b c d e f g h g f e d c b a
a b c d e f g h i h g f e d c b a
a b c d e f g h i j i h g f e d c b a
Enter a non-negative number not greater than 26 (0 - exit ): 4
a
a b a
a b c b a
a b c d c b a
Enter a non-negative number not greater than 26 (0 - exit ): 3
a
a b a
a b c b a
Enter a non-negative number not greater than 26 (0 - exit ): 2
a
a b a
Enter a non-negative number not greater than 26 (0 - exit ): 1
a
Enter a non-negative number not greater than 26 (0 - exit ): 0
The part of the program that outputs the pattern can be placed in a separate function such a way that the pattern can be outputted in any file.
Here you are.
#include <stdio.h>
FILE * display_pattern( size_t n, FILE *fp )
{
static const char alphabet[] = "abcdefghijklmnopqrstuvwxyz";
static const size_t N = sizeof( alphabet ) - 1;
n %= N + 1;
for ( size_t i = 0; i < n; i++ )
{
const char *p = alphabet;
do { fprintf( fp, "%c ", *p++ ); } while ( p != alphabet + i + 1 );
if ( --p != alphabet )
{
do { fprintf( fp, "%c ", *--p ); } while ( p != alphabet );
}
fputc( '\n', fp );
}
return fp;
}
int main(void)
{
while ( 1 )
{
size_t n = 0;
printf( "Enter a non-negative number (0 - exit ): " );
if ( scanf( "%zu", &n ) != 1 || n == 0 ) break;
putchar( '\n' );
display_pattern( n, stdout );
putchar( '\n' );
}
return 0;
}
Again the program output might look like
Enter a non-negative number (0 - exit ): 5
a
a b a
a b c b a
a b c d c b a
a b c d e d c b a
Enter a non-negative number (0 - exit ): 4
a
a b a
a b c b a
a b c d c b a
Enter a non-negative number (0 - exit ): 3
a
a b a
a b c b a
Enter a non-negative number (0 - exit ): 2
a
a b a
Enter a non-negative number (0 - exit ): 1
a
Enter a non-negative number (0 - exit ): 0
If actually you want to output indeed a pyramid then the function can look as it is shown in the next demonstrative program.
#include <stdio.h>
FILE * display_pattern( size_t n, FILE *fp )
{
static const char alphabet[] = "abcdefghijklmnopqrstuvwxyz";
static const size_t N = sizeof( alphabet ) - 1;
n %= N + 1;
for ( size_t i = 0; i < n; i++ )
{
const char *p = alphabet;
fprintf( fp, "%*c ", ( int )( 2 * ( n - i) - 1 ), *p++ );
while ( p != alphabet + i + 1 ) fprintf( fp, "%c ", *p++ );
if ( --p != alphabet )
{
do { fprintf( fp, "%c ", *--p ); } while ( p != alphabet );
}
fputc( '\n', fp );
}
return fp;
}
int main(void)
{
while ( 1 )
{
size_t n = 0;
printf( "Enter a non-negative number (0 - exit ): " );
if ( scanf( "%zu", &n ) != 1 || n == 0 ) break;
putchar( '\n' );
display_pattern( n, stdout );
putchar( '\n' );
}
return 0;
}
Now the program output might look like
Enter a non-negative number (0 - exit ): 5
a
a b a
a b c b a
a b c d c b a
a b c d e d c b a
Enter a non-negative number (0 - exit ): 4
a
a b a
a b c b a
a b c d c b a
Enter a non-negative number (0 - exit ): 3
a
a b a
a b c b a
Enter a non-negative number (0 - exit ): 2
a
a b a
Enter a non-negative number (0 - exit ): 1
a
Enter a non-negative number (0 - exit ): 0
Okay. After having completely rewritten this program over in favor of fgets, it mostly reads in the words.
This comes in two pieces, compiled upon a gcc linux machine. However, a redirect statement is required for this.
So once compiled it must be run like this:
./a.out < data1
So here's "data1":
S T E L B M T F E Y D E E P S R T C I A E E
N N E L I T R L B D E T A R E M U N E T Y L
N O I T A N I M I R C N I F L E S S E N T A
A U I D E W A R R A N T N U P R U S S E R P
P G S G E A L P A P B A N P S A S S N M E A
C O N S I T U T I O N D E E C W S O O H P D
S V W D E L A N E E J A M E S M A D I S O N
A E D E S N E G R J C U L T N O H L T I R A
A R C E R R T R E E S B O N E E I D N N P R
S N J U D I C I A L A S S E C O R P E U D I
S M R A R A E B W B E S S M E O A U V P E M
O E O I A I L N O U C D O D S S E N N I G R
L N I D G Y T R C O M P E N S A T I O N N D
D T O Z E H P Y N D R L E E A O H S C O I B
I T P S U E T G O L U Z M M R B E H P I R T
E O I E A R R S U U I B H A Y L L M S T F A
R I N R E E E F U T L V Q U A R T E R I N G
S I D B S R R D I Y E N I G M I A N A T I R
S Q I S E B S C N S P E E C H R O T A E Y N
D L C M I L I T I A F L R N C A T S S P S E
R U T E D Y L E B I L C O H M L E T E S Y Y
L S T R T E W Z L I O S A E N S A E I Y A L
AMENDMENT
ASSEMBLY
BAIL
BEARARMS
CITIZEN
CIVIL
COMPENSATION
CONGRESS
CONSITUTION
CONVENTIONS
DELEGATED
DOUBLEJEOPARDY
DUEPROCESS
ENUMERATED
FREEDOM
GOVERNMENT
ILLEGAL
INDICT
INFRINGED
JAMESMADISON
JUDICIAL
LAWSUIT
LIBEL
LIBERTY
LIFE
MILITIA
MIRANDA
NECESSARY
PEACEABLY
PEERS
PETITION
POWER
PRESS
PROBABLECAUSE
PROPERTY
PUNISHMENTS
QUARTERING
RELIGION
RIGHTS
SEARCH
SECURITY
SEIZURE
SELFINCRIMINATION
SLANDER
SOLDIERS
SPEECH
SPEEDY
TRIAL
UNREASONABLE
WARRANT
WITNESS
Here's the program itself:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ROWS 50
#define COLUMNS 50
#define TR 100
#define TC 100
int main( )
{
int s1 = 0, s2 = 0;
int sizeOfGrid = 0;
int wordCount = 0;
int rowNumber = 0;
int colNumber = 0;
/* */
char tempLetters[ROWS][COLUMNS];
char letters[ROWS][COLUMNS];
char words[ROWS][COLUMNS];
char wordTemp[50];
char firstRow[100], nextRow[100];
/* fgets(stdin); */
char firstRowTemp[100], nextRowTemp[100];
/* output input */
setbuf(stdout, NULL);
for (s2 = 0; s2 < 100; s2++)
{
firstRowTemp[s2] = ' ';
nextRowTemp[s2] = ' ';
if (s2 < 50)
{
wordTemp[s2] = ' ';
for (s1 = 0; s1 < 50; s1++)
{
words[s2][s1] = ' ';
}
}
}
/* Let's attempt to despace the first line, and then count the chars. */
fgets(firstRow,100,stdin);
s1 = 0;
s2 = 0;
for (colNumber = 0; colNumber < strlen(firstRow); colNumber++)
{
if ((firstRow[colNumber] != ' ') && (firstRow[colNumber] != '\n'))
{
firstRowTemp[s1] = firstRow[colNumber];
letters[rowNumber][s2++] = firstRowTemp[s1++];
sizeOfGrid++;
}
}
/* We have now successfully gotten the size of the grid, so lets
* put it to good use within our next loops to read in the rest
* of the lines.
* We take it in a for loop up to sizeOfGrid*2 because right now,
* we still have spaces. Once we get rid of those, it'll be able to utilize
* normal sizeOfGrid count.*/
for (rowNumber = 1; rowNumber < sizeOfGrid*2; rowNumber++)
{
fgets(nextRow, 100, stdin);
s1 = 0;
s2 = 0;
for (colNumber = 0; colNumber < sizeOfGrid*2; colNumber++)
{
if ((nextRow[colNumber] != ' ') && (tempLetters[rowNumber][colNumber] != '\n'))
{
nextRowTemp[s1] = nextRow[colNumber];
letters[rowNumber][s2++] = nextRowTemp[s1++];
}
}
}
/* Next up, it's time to store the words. Scan the rest of the file for words
* and store them as chars. */
rowNumber = 0;
colNumber = 0;
while(fgets(wordTemp,50,stdin) != NULL)
{
for (s1 = 0; s1 < strlen(wordTemp); s1++)
{
if (wordTemp[s1] != '\n')
{
words[rowNumber][colNumber++] = wordTemp[s1];
}
}
colNumber = 0;
wordCount++;
rowNumber++;
}
/* For testing purposes and making sure it receives the grid entirely.*/
for (s2 = 0; s2 < sizeOfGrid; s2++)
{
printf("%c",firstRowTemp[s2]);
}
printf("\nSize of grid is %d\n",sizeOfGrid);
printf("\n");
for (rowNumber = 0; rowNumber < sizeOfGrid; rowNumber++)
{
for (colNumber = 0; colNumber < sizeOfGrid; colNumber++)
{
printf("%c", letters[rowNumber][colNumber]);
}
printf("\n");
}
for (rowNumber = 0; rowNumber < ROWS; rowNumber++)
{
for (colNumber = 0; colNumber < COLUMNS; colNumber++)
{
if ((words[rowNumber][colNumber] != ' ') && (words[rowNumber][colNumber] != '\n'))
printf("%c", words[rowNumber][colNumber]);
else
break;
}
if (colNumber > 1)
printf("\n");
}
/* End print debugging here.*/
return 0;
}
And now for my question itself...
It appears fgets is skipping over a large number of words, starting only at LIBEL instead of running through the top of the list (AMENDMENTS in this case). Where is it going wrong?
In the grid you've shown us, there are spaces between letters horizontally, but no blank lines between the lines of letters, so you need to use sizeOfGrid*2 to loop over the columns, but not the rows.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm trying to get function2() to check the horizontal pairs and function3() to check the vertical pairs and pass both values back into main for function4() to use, I know not naming them properly is bad practice but bear with me...any help would be greatly appreciated...
My question is why I am getting the output of 0 for countX and countY and how to fix it..
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define maxrow 20 //defines maxrow as a constant of 20
#define maxcol 30 //defines maxcol as a constant of 30
void function1(char array[][maxcol]);
int function2(char array[][maxcol]);
int function3(char array[][maxcol]);
void function4(int, int); //function to display the pairs count
int main( void )
{
int countX = 0;
int countY = 0;
srandom( (unsigned) time(NULL) );
char array[maxrow][maxcol];
function1(array);
function2(array);
function3(array);
function4 (countX, countY);
return ( 0 ) ;
}
void function1(char array[][maxcol])
{
int x = 0;
int y = 0;
for (x=0;x<maxrow;x++)
{
for (y=0;y<maxcol;y++)
{
array[x][y] = random() % 26 + 'A';
printf("%c ", array[x][y]);
}
printf("\n");
}
printf("\n");
}
int function2(char array[][maxcol])
{
int col = 0;
int row = 0;
int countX = 0;
for (row=0;row<maxrow-1;row++)
{
for (col=0;col<maxcol; col++)
{
if (array[row][col] == array[row+1][col])
{
countX++;
}
}
}
return(countX);
}
int function3(char array[][maxcol])
{
int col = 0;
int row = 0;
int countY = 0;
for(col=0;col<maxcol-1;col++)
{
for (row=0;row<maxrow;row++)
{
if (array[row][col] == array[row][col+1])
{
countY++;
}
}
}
return(countY);
}
void function4(int countX, int countY)
{
printf("\nNumber of horizontal pairs: %d\n", countX);
printf("\nNumber of vertical pairs: %d\n\n", countY);
}
output:
N E R J B Z Y R I T Y J P P B G K R A Z X O A Y V W S E V V
M L C F U D G S U O L U Z C M C K W T N V T B V T W U L B R
I N C K U Y N A R K Q E G Q J S U T P Q G M J I K E E G P H
X Z W C K Q A Z Q T L H Y S Z H K V A B L J O W R A A X G P
H F R D H B U K A M D O V D G W K S S N U D W K C P K C O Q
U V V L B F M X R O J U E F A K B K F V Z Z B V J D M V F D
L B A I M B N A Y E R K B V P B I S N N O N O R K Z U X U Z
C F D C N P G D S G J J Q K G H N Q C B F S O T J Y S D X M
E Z T H E J Z M M R U V C L I K U V B Y W I Q M C B L W E K
L L M E U Q P V E B O Y Z Q L J D G E G E D O X P S Y A P D
L A Q X G M P W I T Z W T A P F J S L O A R R O O G H N J W
S W Y K V E W K A E F C B Y C Q D M K Q C K I T A W B H L K
F D I F N D K M N M Q U Q T T T L Y F V P H H X C I V D R J
Q X O Y E E C Q Q R D G M V C H O N F V J U E Q T G A R M S
A E R O E V S I M I A R R O M T V D I C Y R X D K S J K J X
E L B V A I R U Q F F S Y Y G K T D N B G M V F R F Z C R J
A W W D R W L K T E P A W P Y D A R I P U O D P V U W V X O
G Z M C E F B S Q U W H U S X S X Z L G O F W U X S Q T P P
H V O V X V B Y N R U J A O D X I B Y V H P D D J A X Z T M
P D H F Y H A Z H N Q C Y T S C S B D R Y M G B R R B P Q V
Number of horizontal pairs: 0
Number of vertical pairs: 0
Here is why:
function2(array); // in main
function3(array); //in main
Both these functions return something but in main you just call them and don't collect the value returned .. Change above to this is main():
countX = function2(array); // this will put the value ( countX ) returned by this function in countX
countY = function3(array); // this will put the value ( countY ) returned by this function in countY
In the functions function2 and function3 the variables countX and countY (respectively) are local variables. Just like countX and countY in main are local inside main.
One way of solving your problem is to make the variables global, but I don't recommend that. Instead I recommend that you return the variables from the function, and assign to them in main.
So e.g. in function2:
int function2(...)
{
...
return countX;
}
And in main:
countX = function2(...);
Make countX and countY globals (and don't redeclare in the functions).
Or better yet - in main():
countX = function2(array);
countY = function3(array);
And a free tip: you don't need () on all the returns...
I am a beginner in C, I am trying to make a program which detects which letter is the most common of max 10 letters.
Here is what I've got so far:
char one = 'a'; //0110 0001
char check[10];
scanf("%s", &check);
char *ptr;
int a = 0;int b = 0;int c = 0;int d = 0;int e = 0;int f = 0;int g = 0;int h = 0;int i = 0;int j = 0;int k = 0;int l = 0;int m = 0;int n = 0;int o = 0;int p = 0;int q = 0;int r = 0;int s = 0;int t = 0;int u = 0;int v = 0;int w = 0;int x = 0;int y = 0;int z = 0;
if (check[0]=='a'){
a += 1;
if (a> b && a> c && a> d && a> e && a> f && a> g && a> h && a> i && a> j && a> k && a> l && a> m && a> n && a> o && a> p && a> q && a> r && a> s && a> t && a> u && a> v && a> x && a> y ){
printf("A is the most common letter);
}
}
The 'if' statement is only for the first letter that is entered and it is only checking the letter a.
Here is where I need help, how do I optimize that? How can I make a loop instead of having all that a>b && a>c ... etc. Also if it is possible to declare a lot of similar variables in a shorter way? Just generally how do I keep short and am I doing something wrong?
Thank you.
Yes you are doing a lot of things wrong.
this part of code
int a = 0;int b = 0;int c = 0;int d = 0;int e = 0;int f = 0;int g = 0;int h = 0;int i = 0;int j = 0;int k = 0;int l = 0;int m = 0;int n = 0;int o = 0;int p = 0;int q = 0;int r = 0;int s = 0;int t = 0;int u = 0;int v = 0;int w = 0;int x = 0;int y = 0;int z = 0;
is something horrific.
Use an array, like that:
int letter[25];
letter[0] will be your a, letter[1] will be your b ... letter[49] will be your z.
this part of code
if (check[0]=='a'){
a += 1;
is a bad way to do what you want.
you should do it like this:
int i;
for(i = 0; i < 10; ++i)
{
if(check[i] >= 'A' && check[i] <= 'Z') // Check if letter is uppercase.
++letter[check[i] - 'A']; // 'A' == 65, But our array is from 0 to 49.
if(check[i] >= 'a' && check[i] <= 'z') // Check if letter is lowercase.
++letter[check[i] - 'a']; // 'a' == 97. Note that 'A' is not 'a'.
}
This will check which character is most common, and stores it in the letter array.
You can certainly do it your way and compare every letter with every other. But usually you do this in two phases
count how often the letters occur
int letters[26];
int i, n = strlen(check), max;
memset(letters, 0, sizeof(letters));
for (i = 0; i < n; ++i) {
char c = tolower(check[i]);
letters[c - 'a']++;
}
pick the highest one
max = 0;
for (i = 1; i < 26; ++i)
if (letters[i] > letters[max])
max = i;
printf("%c is the most common letter\n", max + 'a');
Impressive work :)
int counts[26]; // We are expecting 26 letters
char check[10];
char *ptr;
scanf("%s", check);
memset(counts, 0, sizeof(counts)); // zero all array values
for (ptr = check; *ptr; ptr++)
{
char ch = *ptr;
if (isalpha(ch)) // ignore non-alphas
{
ch = tolower(ch);
counts[ch - 'a']++;
}
}
You can add best index lookup code from dreamzor answer
You need to use loops and arrays. Just store the amount of letters you've got in an array and then compare current the letter amount to best amount:
char check[10];
scanf("%s", &check);
const int checkSize = strlen(check);
int numberOfLetters[26];
for(int i = 0; i < 26; ++i)
numberOfLetters[i] = 0;
int bestLetterIndex = -1;
for(int i = 0; i < checkSize; ++i) {
int letterIndex = check[i] - 'a'; // getting index from ASCII code
numberOfLetters[letterIndex]++;
if(i == 0 || // first letter, index not found yet
numberOfLetters[letterIndex] > numberOfLetters[bestLetterIndex]) {
bestLetterIndex = letterIndex;
}
}
printf("Most common letter is %c", (char)(bestLetterIndex + 'a'));