Why is my array saving and printing not the chars? - arrays

I want to print random chars and save them all in one array.
But the problem is, the array saves something - but not the chars printed/generated before.
Does anybody know how to fix this?
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
char get_symbol(int m);
int main()
{
srand(time(NULL));
char array[1][5];
char y;
int i;
for(i=0; i<5; i++){
y = get_symbol(rand()%3);
printf("%c", sym);
y = array[i];
}
printf("\n\n");
for(i=0; i<5; i++){
printf("%s", array[i]);
}
}
char get_symbol(int m){
char s;
switch(m){
case 0: s = 'A'; break;
case 1: s = 'B'; break;
case 2: s = 'C'; break;
default: break;
}
return s;
}

You probably want this, explanations are in the comments:
int main()
{
srand(time(NULL));
char array[5]; // you just want an array of 5 chars
char y;
int i;
for (i = 0; i < 5; i++) {
y = get_symbol(rand() % 3);
printf("%c", y); // sym is unknown, you probably wanted to print y
array[i] = y; // you have reversed the assignment
}
printf("\n\n");
for (i = 0; i < 5; i++) {
printf("%c", array[i]); // use %c here, you want to print 5 single chars
} // not 5 strings
fflush(stdout); // flush output buffer. maybe not necessary
}
Bonus:
Your get_symbol function is overly complicated: this does exactly the same:
char get_symbol(int m) {
return 'A' + m % 3;
}
It also does the modulo operation inside the function because (at least in your original function) calling get_symbol with values out side the interval [0..2] will lead to undefined behaviour.

Related

C, dividing a string in half

I am trying to write a function to divide a string in half but after the initial input it does not output anything. My goal is to scan a year and save the first two number and the last two numbers. This is the code:
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char scan_year2() {
char year_number;
scanf("%s", year_number);
return year_number;
return 0;
}
// Function to print n equal parts of str
void divideString(char *str, int n) {
int str_size = strlen(str);
int i;
int part_size;
if (str_size % n != 0) {
printf("Invalid Input: String size");
printf(" is not divisible by n");
return;
}
part_size = str_size / 2;
for (i = 0; i < str_size; i++) {
if (i % part_size == 0)
printf("\n");
printf("%s", str[i]);
}
}
int main() {
char year_number;
scan_year2();
char str = year_number;
divideString(str, 2);
getchar();
return 0;
}
Assuming that a year is at least a 3-digit number, the best way to treat it is to treat it as a number, not as a string:
...
int year;
scanf("%d", &year);
int first = year / 100;
int last = year % 100;
printf("%d %d\n", first, last);
...
dont ignore compiler warnings, it must be complaining at you about this
char scan_year2() {
char year_number;
scanf("%s", year_number);
return year_number;
return 0;
}
you try to return twice.
Also
part_size = str_size / 2;
for (i = 0; i < str_size; i++) {
if (i % part_size == 0)
printf("\n");
printf("%s", str[i]);
}
is not going to give you the correct output. YOu are outputing the string each time. IE if str = "1923" then you will get
1923923
232
You should do
part_size = str_size / 2;
for (i = 0; i < str_size; i++) {
if (i % part_size == 0)
printf("\n");
printf("%c", str[i]);
}
to only output one char at a time

Character Array User Input Scanf

Just started learning programming on my own and whilst trying to create an array of characters from user input, using scanf, have hit the wall; the code is as below:
#include <stdio.h>
#define I 5
int main (void) {
char a[I+1] = {a[I+1] = '\0'}, q;
int i;
for(i = 0; i < I; i++) {
printf("Enter an alphabet:\t");
//scanf("%c", &q);
//scanf("%c*\n", &q);
//scanf("%[^\n]", &q);
//scanf("%[a-z, A-Z]", &q);
scanf("%127[^\n]", &q);
a[i] = q;
}
printf("\n");
for(i = 0; i < I; i++) {
printf("Element a[%d] of a[I]:\t%c\n", i, a[i]);
}
printf("And the a[I] string:\t%s\n", a);
return 0;
}
None of the scanf combinations in the above code works: the program either skips input prompt after the first one or does not store response.
How can this be resolved with scanf?
char a[I+1] = {a[I+1] = '\0'} is not valid. Even if it compiles, it is going out of bounds when assigning the '\0' character. The commonly used convention looks more like this instead:
char a[I+1] = {0};
Or simply:
char a[I+1] = {};
That said, q is only 1 char in size, but your scanf() is trying to read a string up to 127 chars into q. So you are going to trash memory. To read a single char at a time, use %c instead:
#include <stdio.h>
#include <string.h>
#define MAX_INPUT 5
int main (void) {
char a[MAX_INPUT+1];
int i, len;
for(i = 0; i < MAX_INPUT; i++) {
printf("Enter an alphabet:\t");
scanf("%c", &a[i]);
}
a[MAX_INPUT] = '\0';
printf("\n");
len = strlen(a);
for(i = 0; i < len; i++) {
printf("Element a[%d]:\t%c\n", i, a[i]);
}
printf("And the a string:\t%s\n", a);
return 0;
}
Or, you can remove the loop and just use a single call to scanf() using "%5[^\n]" as the format string:
#include <stdio.h>
#include <string.h>
#define MAX_INPUT 5
int main (void) {
char a[MAX_INPUT+1];
char fmt[20];
int i, len;
sprintf(fmt, "%%%d[^\n]", MAX_INPUT);
printf("Enter an alphabet:\t");
scanf(fmt, a);
printf("\n");
len = strlen(a);
for(i = 0; i < len; i++) {
printf("Element a[%d]:\t%c\n", i, a[i]);
}
printf("And the a string:\t%s\n", a);
return 0;
}
This works without any warning or error on Cygwin gcc v7.3 with Wall flag:
#include <stdio.h>
#define I 5
int main (void) {
char a[I+1] = {a[I+1] = '\0'},q;
int i;
for(i = 0; i < I; i++) {
printf("Enter an alphabet:\t");
scanf("%c%*c", &q);
a[i] = q;
}
printf("\n");
for(i = 0; i < I; i++) {
printf("Element a[%d] of a[I]:\t%c\n", i, a[i]);
}
printf("And the string a[I]:\t%s\n", a);
return 0;
}

Find missing lower-case letters that are not in a series of words

As stated in the title I am trying to find all lower-case letters that are not in a series of words. There are no upper-case letters, digits, punctuation, or special symbols.
I need help fixing my code. I am stuck and do not know where to go from here.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void){
int letters[26];
char words[50];
int i = 0, b = 0;
printf("Enter your input : ");
scanf("%s", words);
for(i = 0; i < 26; i++){
letters[i] = 0;
}
while(!feof(stdin)){
for(b = 0; b < strlen(words) - 1; b++){
letters[ words[b] - 'a']++;
scanf("%s", words);
}
}
printf("\nMissing letters : %c ", b + 97);
return 0;
}
My output is giving me some random letter that I do not know where it is coming from.
Here is a working first implementation.
As well as the comments that have already been made, you should use functions wherever possible to separate out the functionality of the program into logical steps. Your main function should then just call the appropriate functions in order to solve the problem. Each function should be something that is self contained and testable.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_INPUT 20 /* Max input to read from user. */
char *readinput(void);
void find_missing_lower_case(char *, int);
int main()
{
char *user_input = readinput();
int len_input = strlen(user_input);
printf("user input: %s\n", user_input);
printf("len input: %d\n", len_input);
find_missing_lower_case(user_input, len_input);
/* Free the memory allocated for 'user_input'. */
free(user_input);
return 0;
}
char *readinput()
{
char a;
char *result = (char *) malloc(MAX_INPUT);
int i;
for(i = 0; i < MAX_INPUT; ++i)
{
scanf("%c", &a);
if( a == '\n')
{
break;
}
*(result + i) = a;
}
*(result + i) = '\0';
return result;
}
void find_missing_lower_case(char *input, int len_input)
{
int a = 97; /* ASCII value of 'a' */
int z = 122; /* ASCII value of 'z' */
int lower_case_chars[26] = {0}; /* Initialise all to value of 0 */
/* Scan through input and if a lower case char is found, set the
* corresponding index of lower_case_chars to 1
*/
for(int i = 0; i < len_input; i++)
{
char c = *(input + i);
if(c >= a && c <= z)
{
lower_case_chars[c - a] = 1;
}
}
/* Iterate through lower_case_chars and print any values that were not set
* to 1 in the above for loop.
*/
printf("Missing lower case characters:\n");
for(int i = 0; i < 26; i++)
{
if(!lower_case_chars[i])
{
printf("%c ", i + a);
}
}
printf("\n");
}
I figured it out and this is the code I used.
int main(void)
{
int array[26];
char w;
int i=0;
for(i=0; i<26; i++) {
array[i]=0; }
printf("Enter your input: ");
scanf("%c", &w);
while(!feof(stdin)) {
array[w-97] = 1;
scanf("%c", &w); }
printf("Missing letters: ");
for(i=0; i<26; i++) {
if(array[i] == 0) {
printf("%c ", i+97); }
}
printf("\n");
return 0;
}

Reading in an array of 12 numbers with spaces in between each number - C programming

I am a new C programming student and am having trouble with a code I am currently working on. I need to ask the user for a 12 number barcode with spaces in between each value. Also, I will need to refer to each individual value in the array later on in the code. For example, if my array is x[12], I need to use x[1], x[2], and all other values to calculate the odd sum, even sum, etc. Below is my first function to read in the bar code using a for loop. Any assistance for the script of this function would help.
#include <stdio.h>
#define ARRAY_SIZE 12
int fill_array() {
int x[ARRAY_SIZE], i;
printf("Enter a bar code to check. Separate digits with a space >\n");
for(i=0; i<ARRAY_SIZE; i++){
scanf("% d", &x);
}
return x;
}
You should pass array to read as the argument and store what is read there.
Also note that % d is a invalid format specifier for scanf().
#include <stdio.h>
#define ARRAY_SIZE 12
/* return 1 if suceeded, 0 if failed */
int fill_array(int* x) {
int i;
printf("Enter a bar code to check. Separate digits with a space >\n");
for(i=0; i<ARRAY_SIZE; i++){
if(scanf("%d", &x[i]) != 1) return 0;
}
return 1;
}
int main(void) {
int bar_code[ARRAY_SIZE];
int i;
if(fill_array(bar_code)) {
for(i=0; i<ARRAY_SIZE; i++) printf("%d,", bar_code[i]);
putchar('\n');
} else {
puts("failed to read");
}
return 0;
}
Alternately, you can allocate an array in the function and return its address.
#include <stdio.h>
#include <stdlib.h>
#define ARRAY_SIZE 12
/* return address of array if succeeded, NULL if failed */
int* fill_array(void) {
int *x, i;
x = malloc(sizeof(int) * ARRAY_SIZE);
if (x == NULL) {
perror("malloc");
return NULL;
}
printf("Enter a bar code to check. Separate digits with a space >\n");
for(i=0; i<ARRAY_SIZE; i++){
if(scanf("%d", &x[i]) != 1) {
free(x);
return NULL;
}
}
return x;
}
int main(void) {
int *bar_code;
int i;
if((bar_code = fill_array()) != NULL) {
for(i=0; i<ARRAY_SIZE; i++) printf("%d,", bar_code[i]);
putchar('\n');
free(bar_code);
} else {
puts("failed to read");
}
return 0;
}

read input character and print the occurrence in graphical format

I am reading the input and trying to print all the input lowercase character in a graphical format, am able to read it and keep track of the number of time each character repeats but not able to print it in a graphical way,can u pls help me out. Here is my code
#include <stdio.h>
#include <ctype.h>
int print_fun(int);
int main() {
int ch = 0, i = 0;
int char_count[26] = {0};
printf("\nNOTE:PRESS * TO EXIT\n");
while((ch = getchar()) != '*') {
if(islower(ch))
char_count[ch - 'a']++;
}
printf("\n");
for(i = 0; i < 26; i++)
//printf("%c:%d\n",'a'+ i, char_count[i]);
//printf("%c:\n", 'a'+ i, print_star(char_count[i]));
printf("%c:\n",print_star(char_count[i]),'a'+ i);
printf("\n");
return 0;
}
int print_star(int value) {
int i = 0;
for(i = 0; i < value; i++)
printf("*");
}
o/p: aaxyyz
a:**
b:
c:
...
...
x:*
y:**
z:*
Your printf call is missing an format argument, you have this:
printf("%d:%c\n",print_star(char_count[i]),'a'+ i);
but you are passing two arguments to printf, as far as I can tell this is what you meant:
printf("%d:%c\n",print_star(char_count[i]),'a'+ i);
Also, print_star has a return value of int but you do not have a return statement, I think you meant to return i and in that case you should add:
return i ;
at the end. The behavior without a return at the end is undefined. Finally, it looks like you have a typo in forward declaration, this:
int print_fun(int);
should be:
int print_star(int value );
#include <stdio.h>
#include <ctype.h>
//int print_fun(int);
void print_star(int);
int main(void){
int ch = 0, i = 0;
int char_count[26] = {0};
printf("\nNOTE:PRESS * TO EXIT\n");
while((ch = getchar()) != '*'){
if(islower(ch))
char_count[ch - 'a']++;
}
printf("\n");
for(i = 0; i < 26; i++){
printf("%c:",'a'+ i);
print_star(char_count[i]);
printf("\n");
}
printf("\n");
return 0;
}
void print_star(int value){
int i = 0;
for(i = 0; i < value; i++)
printf("*");
}

Resources