C Primer Plus chapter 6 programming exercise 1 - c

I worked out this problem using what I learned from chapter 6 (current program). My original idea was to print and scan the values into the array with a loop and them print the values of the array, but I have not been able to make it work (commented section under main function). The program just prints newlines (the program prints the letter but I have to press enter to get the next letter). The commented section in the program within the main function is the idea of what I want to do. I included the program below and I thank you in advance for your help.
//This is a program to create an array of 26 elements, store
//26 lowercase letters starting with a, and to print them.
//C Primer Plus Chapter 6 programming exercise 1
#include <stdio.h>
#define SIZE 26
int main(void)
{
char array[SIZE];
char ch;
int index;
printf("Please enter letters a to z.\n");
for(index = 0; index < SIZE; index++)
scanf("%c", &array[index]);
for(index = 0; index < SIZE; index++)
printf("%c", array[index]);
//for(ch = 'a', index = 0; ch < ('a' + SIZE); ch++, index++)
//{ printf("%c", ch);
// scanf("%c", &array[index]);
//}
//for(index = 0; index < SIZE; index++)
// printf("%c", array[index]);
return 0;
}

The problem here is that
When you enter the character and then you press enter, you input two characters. One is the alphabetic character you enter and the other is the \n. That's why you get what you see. Solution is to consume the white space charcaters ..which is done by putting the ' ' in the scanf.
scanf(" %c", &array[index]);
^
Why it works?
Quoting the standard- 7.21.6.2
A directive composed of white-space character(s) is executed by
reading input up to the first non-white-space character (which remains
unread), or until no more characters can be read. The directive never
fails.
Example code:
#include <stdio.h>
#include <stdlib.h>
#define SIZE 6
int main(void)
{
char array[SIZE];
int index;
printf("Please enter letters a to z.\n");
for(index = 0; index < SIZE; index++)
if( scanf(" %c", &array[index]) != 1){
fprintf(stderr,"%s\n","Error in input");
exit(1);
}
else {
printf("read: %c\n",array[index]);
}
for(index = 0; index < SIZE; index++)
printf("%c", array[index]);
putchar('\n');
return 0;
}

Related

printing characters using array in c language?

I tried to scan and print the characters of array using below code but input characters are not matching with output characters
#include <stdio.h>
int main() {
char s[10];
int i, n;
printf("enter the value of n:\n");
scanf("%d", &n);
printf("start entering the characters:\n");
for (i = 0; i < n; i++) {
scanf("%c", &s[i]);
}
for (i = 0; i < n; i++) {
printf("%c", s[i]);
}
return 0;
}
OUTPUT
enter the value of n:
5
start entering the characters:
ABCDE(scanf values)
ABCD(printf values)
Can anyone please clarify my doubt why is the output not matching with input
Since you are wanting to read data into a character array with "scanf" you probably could just reference the string identifier instead and simplify things. Following are a few tweaks to your code that still inputs the data and prints it back out.
#include <stdio.h>
#include <string.h>
int main()
{
char s[10];
int i, n;
printf("enter the value of n:\n");
scanf("%d", &n);
printf("start entering the characters:\n");
scanf("%s", s); /* In lieu of using a loop */
if (strlen(s) < n) /* Just in case less characters are entered than was noted */
n = strlen(s);
for (i = 0; i < n; i++)
{
printf("%c", s[i]);
}
printf("\n");
return 0;
}
The program just scans in the complete string instead of a character at a time. Also, I included the "<string.h> file so as to use functions such as "strlen" (get the length of the string) to provide a bit more robustness to the code. Running the program netted the same character set that was entered.
:~/C_Programs/Console/InputOutput/bin/Release$ ./InputOutput
enter the value of n:
7
start entering the characters:
ABCDEFG
ABCDEFG
You might give that a try.
Regards.

I want to print out the text with the most number of times entered

#include <stdio.h>
#include <string.h>
int main() {
char str[100];
int h[26]={0};
int i, j, count, tmp=0;
scanf("%s", str);
count=strlen(str);
for(i=0; i<count; i++) {
h[str[i]-97]++;
}
for(j=0; j<25; j++) {
if(h[j]<h[j+1]) {
tmp=j+1;
}
}
printf("%c", (char)tmp+97);
}
I want to output the most frequently entered lowercase letters, but how can I change it by output the strange values?
Try input this code "aaaabbbbsefa", then the "s" will be output.
Your code has a lot of problems. And a good bit of traps.
scanf("%s", str);
What if the input is longer than str can hold?
count=strlen(str);
This is a waste of cpu cycles. You don't need the length of a string to loop through it, you can simply check if the current element of the string is a \0
for(i=0; i<count; i++) {
h[str[i]-97]++;
}
This is problematic, what if the input contained some other character than lower case characters, this could easily cause out of bounds reading.
for(j=0; j<25; j++) {
if(h[j]<h[j+1]) {
tmp=j+1;
}
}
Firstly, this loop stops before 25, but it should stop before 26
Secondly, this definitely does not do what you think it does.
If you want to print the most frequent lower case character from in your input, this is how the flow should look like-
Take the string input and store it into a char array, make sure it can actually hold it
Declare a variable to keep track of the number of occurrences for each lowercase alphabet
Loop through the input string
Check if the current element is lowercase - if it is, add to the counter - if it isn't, do nothing
Loop through the occurrences record, check if the current occurrence is higher than the highest record (which is set to 0 before the loop) - if it higher, change the highest record to it and store the character - if it isn't, move on
Print the resulting character
This is how that'd look like in C-
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define ALPHABET_COUNT 26
#define MAX_LEN 100
int main()
{
char str[MAX_LEN];
int occurrences[ALPHABET_COUNT] = { 0 };
if (!fgets(str, MAX_LEN, stdin))
{
// Something went wrong, error handling here
return 1;
}
for (int i = 0; str[i] != '\0'; i++)
{
if (islower(str[i]))
{
occurrences[str[i] - 'a']++;
}
}
int highest_occurrence = 0;
char highest_occurring_char;
for (int i = 0; i < ALPHABET_COUNT; i++)
{
if (occurrences [i] > highest_occurrence)
{
highest_occurrence = occurrences[i];
// Convert the current index to its corresponding lowercase alphabet
highest_occurring_char = (char) (i + 'a');
}
}
printf("Highest occurring character: %c\n", highest_occurring_char);
}

Runtime initialization of character array in C using for loop

While initializing the character array at runtime using for loop statement inside are executed twice like printf function meanwhile character array of 6 size taking only 3 inputs:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main() {
int i = 0;
char name[6];
for (int i = 0; i < 5; ++i)
{
printf("Enter the character in name array");
scanf("%c", &name[i]);
}
printf("%s", name);
return 0;
}
when you define an array of characters ,in the last element of array you should place \0 to terminate string. so you can scan 5 characters as you do ,but you should add \0 at the end of your string.
also you should add space to your scanf like this scanf(" %c", &name[i]); ,otherwise you will take \n as a character of your string after each time you use enter.(that is reason of problem you explained)
look
int main() {
int i = 0;
char name[6];
for (i = 0; i < 5; ++i)
{
printf("Enter the character in name array");
scanf(" %c", &name[i]);
}
name[i] = '\0';
printf("%s", name);
return 0;
}
also note that ,I have removed int i from here for (int i = 0; i < 5; ++i) , otherwise this i would be only visible in for loop block and out side of it, because of int i = 0; \0 would be placed in name[0] ,and string would be lost.
or use scanf("%6s", name) as #Eraklon said in comments.

Using scanf for character input, but the do-while loop wont stop at the null character

I'm completely new to programming (1st term in uni) and I can't keep up with my lecturer. At the moment I'm stuck on this exercise (for much more time than I'm willing to admit). I've tried to find help on the internet (in this site and others as well), but I can't, since our lecturer has us use a very simple form of c. I'm not asking necessarily for a complete answer. I'd really appreaciate even some hints about where I'm on the wrong. I understand that it might be really simple for some, that the question might seem ignorant or stupid and I feel bad for not getting what's wrong, but I need to try to understand.
So, what I'm trying to do is use scanf and a do while loop so the user can input characters in an array. But I don't understand why the loop won't stop when the user presses ENTER. There's more to the code, but I'm trying to take it slowly, step by step. (I'm not allowed to use pointers and getchar etc).
#include <stdio.h>
main()
{
char a[50];
int i;
printf("Give max 50 characters\n");
i=0;
do
{
scanf("%c", &a[i]);
i=i+1;
}
while((i<=50) && (a[i-1]!='\0'));
for(i=0; i<50; i++)
printf("%c", a[i]);
}
There aren't any nul-terminated strings here, but only string arrays.
So, when pressing enter, a[i-1] is \n not \0 (scanf with %c as parameter doesn't nul-terminate the strings, and ENTER is just a non-nul character with code 10 AKA \n)
Then don't print the rest of the string because you'll get junk, just reuse i when printing the string back:
#include <stdio.h>
main()
{
char a[50];
int i;
printf("Give max 50 characters\n");
i=0;
do
{
scanf("%c", &a[i]);
i=i+1;
}
while((i<sizeof(a)) && (a[i-1]!='\n')); // \n not \0
int j;
for(j=0; j<i; j++) // stop at i
printf("%c", a[j]); // output is flushed when \n is printed
}
Also test with i<50 not i<=50 because a[50] is outside the array bounds (I've generalized to sizeof(a))
Here is another way you can do this.
#include <stdio.h>
// define Start
#define ARRAY_SIZE 50
// define End
// Function Prototypes Start
void array_reader(char array[]);
void array_printer(char array[]);
// Function Prototypes End
int main(void) {
char user_input[ARRAY_SIZE];
printf("Please enter some characters (50 max)!\n");
array_reader(user_input);
printf("Here is what you said:\n");
array_printer(user_input);
return 0;
}
// Scans in characters into an array. Stops scanning if
// 50 characters have been scanned in or if it reads a
// new line.
void array_reader(char array[]) {
scanf("%c", &array[0]);
int i = 0;
while (
(array[i] != '\n') &&
(i < ARRAY_SIZE)
) {
i++;
scanf("%c", &array[i]);
}
array[i + 1] = '\0';
}
// Prints out an array of characters until it reaches
// the null terminator
void array_printer(char array[]) {
int i = 0;
while (array[i] != '\0') {
printf("%c", array[i]);
i++;
}
}
You may try with this code:
#include <stdio.h>
main()
{
char a[50];
int i;
printf("Give max 50 characters\n");
i=0;
do {
scanf("%c", &a[i]);
i=i+1;
} while(i<50 && a[i-1] != '\n');
a[i] = 0;
for(i=0; a[i] != 0; i++)
printf("%c", a[i]);
}
The function scanf("%c", pointer) will read one character at a time and place it at the pointer location. You are looking for '\0', which is a valid string terminator, but the newline character you get when you press ENTER and that you should be looking for is '\n'.
Also, it is a good idea to terminate the string you have read by adding a '\0' at the end (really a zero). Then use it to stop printing or you may print the "rest" of the contents of an uninitialized char array.

Program won't store characters in 2d array in c

I am creating a program where I insert a number of sentences and the program outputs them in order. I have finished the program, but when I run it it seems like the characters I input into the array aren't displayed or stored correctly, getting as a result random letters instead of the full sentence. Here is the code of the program:
char ch;
int i,j,k;
int nothing = 0;
int count = 1;
char lines[5][256];
int length[256];
int main() {
printf("Please insert up to a max of 5 lines of text (Press enter to go to next line and twice enter to stop the program):\n");
i = 0;
while (i<5){
j = 0;
ch = getche();
if (ch == '\r'){
if(i!= 0){
break;
}
printf("You have not inserted anything, please insert a line:");
i=-1;
}
if(ch != '\r'){
lines[i][j]=ch;
while (ch!='\r'){
ch = getche();
lines[i][j] = ch;
j++;
}
}
printf("\n");
i++;
}
for (k=i ; k > 0; k--){
printf("\tphrase %i :", count);
for ( j =0 ; j <= length[k]; j++){
printf("%c",lines[j][k]);
}
count++;
printf("\n");
}
return 0;
}
How can I get the characters to be stored and displayed correctly? Any help is appreciated, thank you!!
There are numerous problems with your code. I'll try and summarise here, and give you improved code.
Fist, some changes that I made to get this to compile on my system:
Changed getche() to getchar() (getche() does not appear to be available on Ubuntu).
I took out the section about re-entering a string, and just focused on the rest (since the logic there was slightly broken, and not relevant to your question). It will still check for at least one line though, before it will continue.
I had to change the check for \r to \n.
I changed your length array to size 5, since you'll only have the lengths of maximum 5 strings (not 256).
Some problems in your code:
You never updated the length[] array in the main while loop, so the program never knew how many characters to print.
Arrays are zero indexed, so your final printing loops would have skipped characters. I changed the for parameters to start at zero, and work up to k < i, since you update i after your last character in the previous loop. The same with j.
Your reference to the array in the printing loop was the wrong way around (so you would've printed from random areas in memory). Changed lines[j][k] to lines[k][j].
No need for a separate count variable - just use k. Removed count.
The nothing variable does not get used - removed it.
#include <stdlib.h>
#include <stdio.h>
char ch;
int i,j,k;
char lines[5][256];
int length[5];
int main()
{
printf("Please insert up to a max of 5 lines of text (Press enter to go to the next line and twice enter to stop the program):\n");
i = 0;
while (i<5)
{
j = 0;
ch = getchar();
if ((ch == '\n') && (j == 0) && (i > 0))
{
break;
}
if (ch != '\n')
{
while (ch != '\n')
{
lines[i][j] = ch;
j++;
ch = getchar();
}
}
length[i] = j;
printf("\n");
i++;
}
for (k = 0; k < i; k++)
{
printf("\tPhrase %i : ", k);
for (j = 0; j < length[k]; j++)
{
printf("%c", lines[k][j]);
}
printf("\n");
}
return 0;
}

Resources