I wrote a simple code that should read an array and print it, but it doesn't print anything.
What I noticed is that, when I make first for loop go to n-1 instead of n (but second loop still goes to n), it actually works. Example:
Input: 1 2 3 4 5 6
Output: 1 2 3 4 5 0
It also works when the second loop goes to n-1, so the mistake is in the first loop or scanf function.
What can I do to make it print whole array?
#include <stdio.h>
#define MAX_LENGTH 50
int main() {
int a[MAX_LENGTH];
int n, i;
printf("Insert the length of array: ");
scanf("%d", &n);
printf("Insert elements of array: ");
for (i = 0; i < n; i++)
scanf("%d ", &a[i]);
for (i = 0; i < n; i++)
printf("%d ", a[i]);
}
The problem is you have a trailing space in the scanf() format: scanf keeps waiting for more input until you enter something that is not white space, newline being white space.
You should just use "%d" as a scanf() format.
Furthermore, you should check the return value of scanf() to avoid undefined behavior upon invalid input.
Here is a corrected version:
#include <stdio.h>
#define MAX_LENGTH 50
int main() {
int a[MAX_LENGTH];
int n, i;
printf("Insert the length of array: ");
if (scanf("%d", &n) != 1)
return 1;
if (n > MAX_LENGTH) {
printf("too many numbers, limiting to %d\n");
n = MAX_LENGTH;
}
printf("Insert elements of array: ");
for (i = 0; i < n; i++) {
if (scanf("%d", &a[i]) != 1)
return 1;
}
for (i = 0; i < n; i++) {
printf("%d ", a[i]);
}
printf("\n");
return 0;
}
Related
I have to code in an array that can count an element. For example, if the user enters a 2, 2, 2, 1,1 then the user wants to count the number 2 then the result will be ELEMENT is 2 and FREQUENCY is 3. but I have a problem with the parts of " ENTER THE NUMBER YOU WANT TO BE COUNTED". I use scanf but when I run it I cannot enter any number.
Here's my code:
void frequency()
{
system("cls");
int num;
int count=0;
printf("Enter a number you want to be count: \n ");
scanf("i%", &num);
printf(" ELEMENT | FREQUENCY \n ");
for (i = 0; i<=n; i++)
{
if (a[i]==a[num])
count++;
}
printf(" \n %i ", num);
printf(" \t\t");
printf("%i \n ", count);
getch();
}
Your program requires understanding on two parts:
Get input and split input by delimiter, which can be done by using strtok.
Algorithm for finding the duplicated elements in an array.
#include <stdio.h>
#include <string.h>
int main() {
frequency();
return 0;
}
void frequency() {
char str[100];
printf("Enter a number you want to be count: \n ");
gets(str);
int init_size = strlen(str);
char delim[] = " ";
char *ptr = strtok(str, delim);
char *pch;
int arr[20];
int count = 0;
int ncount, i, j;
int a[count], Freq[count];
while(ptr != NULL) {
/*printf("'%s'\n", ptr);*/
/*Converts the string argument str to an integer (type int)*/
arr[count] = atoi(ptr);
/*strtok accepts two strings - the first one is the string to split, the second one is a string containing all delimiters*/
ptr = strtok(NULL, delim);
/*Initialize frequency value to -1*/
Freq[count] = -1;
count += 1;
}
/*Count the frequency of each element*/
for (i = 0; i < count; i++) {
ncount = 1;
for(j = i + 1; j < count; j++) {
/*Part to perform checking for duplicate elements*/
if(arr[i] == arr[j]) {
ncount++;
/*Make sure not to count frequency of same element again*/
Freq[j] = 0;
}
}
/*If frequency of current element is not counted*/
if(Freq[i] != 0) {
Freq[i] = ncount;
}
}
printf(" ELEMENT | FREQUENCY \n");
printf("-------------------------\n");
for (i = 0; i < count; i++) {
if(Freq[i] != 0) {
printf("\t%d\t\t\t%d\n", arr[i], Freq[i]);
}
}
}
Also, from your code:
You did not define i and n, which is required by your for loop. Also, since your for loop is for (i = 0; i<=n; i++), you have to define the value of n, which is the length of elements inputted by the user, in order to loop through the number of elements you expected.
int i, n, num;
...
...
for (i = 0; i<=num; i++)
Your scanf("i%", &num); should be scanf("%i", &num); instead.
You did not initialize your array a. You should have this line of code before assigning values to your array a. The value 20 can be adjusted by yourself depending on how many inputs are expected. Also, it can be coded in a flexible way instead of hardcoded as 20.
...
int i, num;
int count=0;
int a[20];
...
...
Lastly, it is a good practice to include the function's library before using it. In your case, you should include #include <conio.h> to use the getch() function.
so i'm a beginner and trying to solve a small project about making fibonacci number.
The code essentially is about typing n (the sequence) and it will show you what value of fibonacci number in that n-sequence.
but of course the code went wrong, the code just stop until i type the n-sequence, and nothing being printed after that. Can anybody check my code pls?
#include <stdio.h>
int main(){
int n;
int seq[n];
int i;
printf("number of sequence for the fibonacci number that you want to find out (from 0)= ");
scanf("%d", &n);
for(i = 0; i <= n; i++){
if(i == 0){
seq[i] = 0;
}
else if(i == 1){
seq[i] = 1;
}
else if(i > 1){
seq[i] = seq[i-1] + seq[i-2];
}
}
if(i == n){
printf("the value in sequence %d is %d", n, seq[n]);
}
return 0;
}
You need to declare the variable length array seq after you entered its size
For example
int n;
int i;
printf("number of sequence for the fibonacci number that you want to find out (from 0)= ");
scanf("%d", &n);
int seq[n + 1];
The size of the array is specified as n + 1 because the user is asked to enter the fibonacci number starting from 0.
Also this for loop will be correct provided that the array has n + 1 elements.
for(i = 0; i <= n; i++){
It is better to write it like
for(i = 0; i < n + 1; i++){
And this if statement
if(i == n){
does not make a sense. Just output the value of the array element seq[n].
apparently, in the loop, you set the boarder as i<=n while the array seq[n] is with the size of n. So i must be less than n.
n is uninitialized. It contains a garbage value.
Don't use scanf() for reading user input. It is very error-prone. Just try typing some string and see what happens. Better use fgets() in combination with sscanf().
int n;
char input[255];
printf("Number of sequence: ");
fgets(input, sizeof input, stdin);
input[strcspn(input, "\n")] = '\0';
if (sscanf(input, "%d", &n) != 1) {
// Handle input error
}
int seq[n+1]; // Edited: n+1 because fib starts from 0
int i;
for (i = 0; i < n+1; i++) {
if (i == 0 || i == 1)
seq[i] = i;
else
seq[i] = seq[i-1] + seq[i-2];
}
I'm having trouble outputting an invalid statement if the user inputs a letter instead of a number into a 2D array.
I tried using the isalpha function to check if the input is a number or a letter, but it gives me a segmentation fault. Not sure what's wrong any tips?
the following code is just the part that assigns the elements of the matrix.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX 10
void display(int matrix[][MAX], int size);
int main() {
int n, degree;
int matrix[MAX][MAX];
printf("Enter the size of the matrix: "); // assigning size of the matrix
scanf("%d", &n);
if (n <= 1 || n >= 11) { // can't be bigger than a 10x10 matrix
printf("Invalid input.");
return 0;
}
for (int i = 0; i < n; ++i) { // assigning the elements of matrix
printf("Enter the row %d of the matrix: ", i);
for (int j = 0; j < n; ++j) {
scanf("%d", &matrix[i][j]);
if (!isalpha(matrix[i][j])) { // portion I'm having trouble with
continue;
} else {
printf("Invalid input.");
return 0;
}
}
}
...
As the value of n will be number, we can solve it using string instead of int.
char num[10];
int n;
scanf("%s", num);
if(num[0] < '0' || num[0] > '9' || strlen(num) > 2){
printf("invalid\n");
}
if(strlen(num) == 1) n = num[0] - '0';
if(strlen(num) == 2 && num[0] != 1 && num[1] != 0) printf("invalid\n");
else n = 10;
Also we can use strtol() function to convert the input string to number and then check for validity.You can check the following code for it. I have skipped the string input part. Also you have to add #include<stdlib.h> at the start for the strtol() function to work.
char *check;
long val = strtol (num, &check, 10);
if ((next == num) || (*check != '\0')) {
printf ("invalid\n");
}
if(val > 10 || val < 0) printf("invalid\n");
n = (int)val; //typecasting as strtol return long
You must check the return value of scanf(): It will tell you if the input was correctly converted according to the format string. scanf() returns the number of successful conversions, which should be 1 in your case. If the user types a letter, scanf() will return 0 and the target value will be left uninitialized. Detecting this situation and either aborting or restarting input is the callers responsibility.
Here is a modified version of your code that illustrates both possibilities:
#include <stdio.h>
#define MAX 10
void display(int matrix[][MAX], int size);
int main(void) {
int n, degree;
int matrix[MAX][MAX];
printf("Enter the size of the matrix: "); // assigning size of the matrix
if (scanf("%d", &n) != 1 || n < 2 || n > 10) {
// can't be bigger than a 10x10 matrix nor smaller than 2x2
// aborting on invalid input
printf("Invalid input.");
return 1;
}
for (int i = 0; i < n; i++) { // assigning the elements of matrix
printf("Enter the row %d of the matrix: ", i);
for (int j = 0; j < n; j++) {
if (scanf("%d", &matrix[i][j]) != 1) {
// restarting on invalid input
int c;
while ((c = getchar()) != '\n') {
if (c == EOF) {
printf("unexpected end of file\n");
return 1;
}
}
printf("invalid input, try again.\n");
j--;
}
}
}
...
The isdigit() library function of stdlib in c can be used to check if the condition can be checked.
Try this:
if (isalpha (matrix[i][j])) {
printf ("Invalid input.");
return 0;
}
So if anyone in the future wants to know what I did. here is the code I used to fix the if statement. I am not expecting to put any elements greater than 10000 so if a letter or punctuation is inputted the number generated will be larger than this number. Hence the if (matrix[i][j] > 10000). May not be the fanciest way to do this, but it works and it's simple.
for (int i = 0; i < n; ++i) { // assigning the elements of matrix
printf("Enter the row %d of the matrix: ", i);
for (int j = 0; j < n; ++j) {
scanf("%d", &matrix[i][j]);
if (matrix[i][j] > 10000) { // portion "fixed"
printf("Invlaid input");
return 0;
}
}
}
I used a print statement to check the outputs of several letter and character inputs. The lowest out put is around and above 30000. So 10000 I think is a safe condition.
I am new to C programming so please do forgive my naivety. The following program when outputted fails to print the last character of the input string as the first character of the output string.
For example:
Enter no. of elements: 5
Enter string: hello
The reversed string is: lleh
Why is the o not printing?
#include <stdio.h>
int main() {
printf("Enter no. of elements: ");
int n;
scanf("%d", &n);
char string[10000];
printf("Enter string: ");
for (int i = 0; i < n; i++) {
scanf("%c", &string[i]);
}
printf("The reversed string is: ");
for (int i = (n - 1); i >= 0; i--) {
printf("%c", string[i]);
}
printf("\n");
return 0;
}
There is a side effect you take care of:
After scanf("%d", &n);, there is a pending newline in the input stream buffer.
When you later input n characters, scanf("%c", &string[i]) first reads the pending newline, then the n-1 first characters you type and the remainder of your input stays in the input buffer.
scanf() is a very clunky function. It is difficult to use properly.
Here is a way to fix your problem:
#include <stdio.h>
int main() {
char string[10000];
int i, n, c;
printf("Enter no. of elements: ");
if (scanf("%d", &n) != 1 || n < 0 || n > 10000)
return 1;
// read and discard pending input
while ((c = getchar()) != '\n' && c != EOF)
continue;
printf("Enter string: ");
for (i = 0; i < n; i++) {
if (scanf("%c", &string[i]) != 1)
break;
}
// the above loop could be replaced with a single call to fread:
// i = fread(string, 1, n, stdin);
printf("The reversed string is: ");
while (i-- > 0) {
printf("%c", string[i]);
}
printf("\n");
return 0;
}
Your scanf() should start with a space( more info about that ). Here is the code:
#include <stdio.h>
int main() {
printf("Enter no. of elements: ");
int n;
scanf(" %d", &n);
char string[10000];
printf("Enter string: ");
for (int i = 0; i < n; i++) {
scanf(" %c", &string[i]);
}
/* Just to be safer. */
string[n] = '\0';
printf("The reversed string is: ");
for (int i = (n-1); i >= 0; i--) {
printf("%c", string[i]);
}
printf("\n");
return 0;
}
Adding the space to the format string enables scanf to consume the
newline character from the input that happens everytime you press
return. Without the space, string[i] will receive the
char '\n'
So, merely one space is put before format specifier %c at line 11.
scanf(" %c", &string[i]);
Forgive me, I'm a C programming rookie. What I need to do is take values from standard input and store them in an array which is to be sorted later on down the line.
The method of entry for the user is one number on one line at a time (i.e. enter a number, press enter, enter number, press enter, etc..). When the user is done entering numbers, they press ENTER without providing a number.
My code for accepting the values and storing them is as follows. You'll probably see the issue immediately, but I'm not seeing it.
#include <stdio.h>
#define MAX 100
int main()
{
int n, i, array[MAX];
printf("Enter a list of integers\n");
for(i = 0; i <= MAX; ++i){
printf("> ");
if (scanf("%d", &n) == -1)
break;
else
scanf("%d", &n);
array[i] = n;
}
printf("The array is %d", *array);
return 0;
}
The picture below is how the program should run. I have the sort code already, and it seems to work quite well. Your help is greatly appreciated.
You have it doing what you want, you just need a few tweaks. First, enter doesn't return -1, to keep it simple you need to enter ctrl+d to stop input. After your final input, just hit ctrl+d. Take a look:
#include <stdio.h>
#define MAX 100
int main()
{
int n, i, array[MAX];
printf("Enter a list of integers [ctrl+d] to end\n");
for(i = 0; i <= MAX; ++i){
printf("> ");
if (scanf("%d", &n) == -1)
break;
array[i] = n;
}
puts ("");
int z;
for (z = 0; z < i; z++)
printf("The array is %d\n", array[z]);
return 0;
}
output:
Enter a list of integers [ctrl+d] to end
> 1
> 2
> 3
> 4
> 5
>
The array is 1
The array is 2
The array is 3
The array is 4
The array is 5
Here is the updated previous answer to exit on enter.
#include <stdio.h>
#define MAX 100
int main()
{
int n, i, array[MAX];
char num[MAX];
int res;
printf("Enter a list of integers [ctrl+d] to end\n");
for(i = 0; i <= MAX; ++i){
printf("> ");
fgets(num, sizeof(num), stdin);
res = sscanf(num, "%d", &n);
if(res != 1)
break;
n = atoi(num);
array[i] = n;
}
puts ("");
int z;
for (z = 0; z < i; z++)
printf("The array is %d\n", array[z]);
return 0;
}