Issues while dealing with an array in C - c

iI'm trying to understand how to properly use arrays in C and tried to write a simple program, which is supposed to take a 5-integers array and eliminate zeroes to the left. This is my attempt:
#include <stdio.h>
int main() {
int seq[5];
int i;
int cor[5];
int counter;
printf("Type the 5 numbers: ");
scanf("%s", &seq);
for (i=0; i<5; i++){
if (seq[i] != 0) {
for (counter=0; counter<5-i; counter++){
cor[counter]=seq[i+counter];
}
break;
}
}
printf("%s", cor);
return 0;
}
The idea was that when something such as 00101 was entered, the program would look at each entry and check whether it is 0. If it isn't, at the position i, it would write a new array in which the 0-th position is assigned the value of the original array at i, the 1-th position would be assigned the value at i+1 and so on, and then it would print this new array, which should have no useless zeroes to the left. But it just prints the original array. What is wrong? Sorry for the begginner's question.

You have two ways to do what you want.
using chars :
#include <stdio.h>
int main() {
char seq[6]; /* reserve one place for terminating null */
int i;
char cor[5];
int counter;
printf("Type the 5 digits : ");
scanf("%5s", seq); /* limit to 5 chars and seq is already an array : ne & */
for (i=0; i<5; i++){
/* should control seq[i] >= '0' && seq[i] <= '9' */
if (seq[i] != '0') {
for (counter=0; counter<6-i; counter++){ /* also copy terminating null */
cor[counter]=seq[i+counter];
}
break;
}
}
printf("%s", cor);
return 0;
}
but user could give you chars that are not digits.
using ints :
#include <stdio.h>
int main() {
int seq[5];
int i;
int cor[5];
int counter;
printf("Type the 5 numbers: ");
i = scanf("%d%d%d%d%d", seq, seq+1, seq+2, seq+3, seq+4); /* seq+i = &(seq[i]) */
/* should control i == 5 */
for (i=0; i<5; i++){
if (seq[i] != 0) {
for (counter=0; counter<5-i; counter++){
cor[counter]=seq[i+counter];
}
break;
}
}
printf("%d%d%d%d%d", cor[0], cor[1], cor[2], cor[3], cor[4]);
return 0;
}

You cannot store a string in an integer array. You have to store strings in character arrays.

Related

Digit Frequency calculating code in C not working

So, I was writing this code for counting the digit frequency i.e. the number of times the digits from 0-9 has appeared in a user inputted string(alphanumeric). So, I took the string, converted into integer and tried to store the frequency in "count" and print it but when I run the code, count is never getting incremented and the output comes all 0s. Would be grateful if anyone points out in which part my logic went wrong.
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
// takes string input
char *s;
s = malloc(1024 * sizeof(char));
scanf("%[^\n]", s);
s = realloc(s, strlen(s) + 1);
//turns the string to int
int x = atoi(s);
int temp = x, len = 0;
//calculates string length
while (x != 0) {
x = x / 10;
len++;
}
x = temp;
//parses through the string and matches digits with each number
for (int j = 0; j < 10; j++){
int count = 0;
for(int i = 0; i < len; i++){
if(x % 10 == j){
count++;
}
x = x / 10;
}
x = temp;
printf("%d ", count);
}
return 0;
}
To write a correct and reasonable digit-counting program:
Do not allocate any buffer for this.
Create an array to count the number of times each digit occurs. The array should have ten elements, one for each digit.
Initialize the array to zero in each element.
In a loop, read one character at a time.
Leave the loop when the read routine (such as getchar) indicates end-of-file or a problem, or, if desired, returns a new-line or other character you wish to use as an end-of-input indication.
Inside the loop, check whether the character read is a digit. If the character read is a digit, increment the corresponding element of the array.
After the loop, execute a new loop to iterate through the digits.
Inside that loop, for each digit, print the count from the array element for that digit.
Your approach is way to complicated for a very easy task. This will do:
void numberOfDigits(const char *s, int hist[10]) {
while(*s) {
if(isdigit(*s))
hist[*s - '0']++;
s++;
}
}
It can be used like this:
int main(void) {
char buf[1024];
int hist[10];
fgets(buf, sizeof buf, stdin);
numberOfDigits(s, hist);
for(int i=0; i<10; i++)
printf("Digit %d occurs %d times\n", i, hist[i]);
}
This can also be quite easily achieved without a buffer if desired:
int ch;
int hist[10];
while((ch = getchar()) != EOF) {
if(isdigit(ch))
hist[ch - '0']++;
}
#include <stdio.h>
int main(void) {
int input = 1223330;
int freq[10] = {0};
input = abs(input);
while(input)
{
freq[input%10]++;
input /= 10;
}
for(int i=0; i<10; ++i)
{
printf("%d: %.*s\n", i, freq[i], "*************************************************");
}
return 0;
}
Output:
Success #stdin #stdout 0s 5668KB
0: *
1: *
2: **
3: ***
4:
5:
6:
7:
8:
9:
This app is currently limited by the size of an int (approximately 9 or 10 digits).
You can update it to use a long long easily, which will get you to about 19 digits.

How to sort array of strings in ascending order in C

Problem
I have made sorting program which is similiar to other found at
https://beginnersbook.com/2015/02/c-program-to-sort-set-of-strings-in-alphabetical-order/
but program which i made is not working.
I think both are same but my program giving me waste output.
Also i want to know in other program count is set to 5 for example and it should take 6 input starting from 0 but it is getting only 5,How?
My Program
#include <string.h>
#include <stdio.h>
int main() {
char str[4][10],temp[10];
int i,j;
printf("Enter strings one by one : \n");
for(i=0;i<5;i++)
scanf("%s",str[i]);
for(i=0;i<5;i++)
for(j=i+1;j<5;j++)
if(strcmp(str[i],str[j])>0){
strcpy(temp,str[i]);
strcpy(str[i],str[j]);
strcpy(str[j],temp);
}
printf("\nSorted List : ");
for(i=0;i<5;i++)
printf("\n%s",str[i]);
printf("\n\n");
return 0;
}
Use qsort().
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int pstrcmp( const void* a, const void* b )
{
return strcmp( *(const char**)a, *(const char**)b );
}
int main()
{
const char* xs[] =
{
"Korra",
"Zhu Li",
"Asami",
"Mako",
"Bolin",
"Tenzin",
"Varrick",
};
const size_t N = sizeof(xs) / sizeof(xs[0]);
puts( "(unsorted)" );
for (int n = 0; n < N; n++)
puts( xs[ n ] );
// Do the thing!
qsort( xs, N, sizeof(xs[0]), pstrcmp );
puts( "\n(sorted)" );
for (int n = 0; n < N; n++)
puts( xs[ n ] );
}
Please don’t use bubble sort. In C, you really do not have to write your own sorting algorithm outside of specialized needs.
Here is a program which will sort and print your inputted strings. Answering a little late, but just in case others have a similar question.
// This program will sort strings into either ascending or descending order
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 1000
#define EQUAL 0
#define ASCENDING 0
#define DESCENDING 1
// Function prototypes
void swap_str(char str1[], char str2[]);
void sort_strings(char str[MAX_SIZE][MAX_SIZE], int len, int order_type);
void print_2d_array(char str[MAX_SIZE][MAX_SIZE], int len);
int main(void) {
int order_type;
char str[MAX_SIZE][MAX_SIZE];
// User selecting the order type
printf("-----------[Order Type]-----------\n");
printf("Sort your strings in ascending or descending order?\n");
printf("0 = Ascending | 1 = descending\n");
scanf("%d", &order_type);
if (order_type != ASCENDING && order_type != DESCENDING) {
printf("Please enter 0 or 1\n");
exit(1);
}
// User inputting their strings
printf("---------[Enter Strings]----------\n");
printf("Enter Strings one by one.\n");
printf("Max Strings: %d | Max String Len: %d\n", MAX_SIZE, MAX_SIZE);
int i = 0;
while ((i < MAX_SIZE) && (scanf("%s", str[i]) == 1)) i++;
if (i == MAX_SIZE) printf("You reached the maximum strings allowed\n");
// Program output of the sorted strings
printf("---------[Sorted Strings]---------\n");
sort_strings(str, i, ASCENDING);
print_2d_array(str, i);
return 0;
}
// Swaps two strings (assuming memory allocation is already correct)
void swap_str(char str1[], char str2[]) {
char temp[MAX_SIZE];
strcpy(temp, str1);
strcpy(str1, str2);
strcpy(str2, temp);
}
// Will sort a 2D array in either descending or ascending order,
// depending on the flag you give it
void sort_strings(char str[MAX_SIZE][MAX_SIZE], int len, int order_type) {
int i = 0;
while (i < len) {
int j = 0;
while (j < len) {
if ((order_type == ASCENDING) &&
(strcmp(str[i], str[j]) < EQUAL)) {
swap_str(str[i], str[j]);
} else if ((order_type == DESCENDING) &&
(strcmp(str[i], str[j]) > EQUAL)) {
swap_str(str[i], str[j]);
}
j++;
}
i++;
}
}
// Will print out all the strings 2d array
void print_2d_array(char str[MAX_SIZE][MAX_SIZE], int len) {
int i = 0;
while (i < len) {
printf("%s\n", str[i]);
i++;
}
}
Example (Ascending order):
-----------[Order Type]-----------
Sort your strings in ascending or descending order?
0 = Ascending | 1 = descending
0
---------[Enter Strings]----------
Enter Strings one by one.
Max Strings: 1000 | Max String Len: 1000
Mango
Watermelon
Apple
Banana
Orange
// I pressed CTRL+D here (Linux) or CTRL+Z then enter (on Windows). Essentially triggering EOF. If you typed the MAX_SIZE it would automatically stop.
---------[Sorted Strings]---------
Apple
Banana
Mango
Orange
Watermelon
it should take 6 input starting from 0 but it is getting only 5,How?
This loop
for(i=0;i<5;i++)
scanf("%s",str[i]);
execute for i being 0, 1, 2, 3, 4 so it loops 5 times.
If you want 6 loops do
for(i=0;i<=5;i++)
^
Notice
or
for(i=0;i<6;i++)
^
Notice
Also notice this line
char str[6][10],temp[10];
^
Notice
so that you reserve memory for 6 strings
This is not an answer, but some criticism of the code you refer to:
#include<stdio.h>
#include<string.h>
int main(){
int i,j,count;
char str[25][25],temp[25];
puts("How many strings u are going to enter?: ");
scanf("%d",&count); // (1)
puts("Enter Strings one by one: ");
for(i=0;i<=count;i++) // (2)
gets(str[i]);
for(i=0;i<=count;i++)
for(j=i+1;j<=count;j++){
if(strcmp(str[i],str[j])>0){
strcpy(temp,str[i]);
strcpy(str[i],str[j]);
strcpy(str[j],temp);
}
}
printf("Order of Sorted Strings:"); // (3)
for(i=0;i<=count;i++)
puts(str[i]);
return 0;
}
And the criticism:
(1) scanf("%d",&count); reads a number into count, and returns after that. It does not consume the line break(!)
(2) this loop does not print anything, just reads. However if you put
for(i=0;i<=count;i++){
printf("%d:",i);
gets(str[i]);
}
in its place, you will suddenly see that it asks for names 0...5, just skips the 0 automatically. That is where the line break is consumed, it reads an empty string. You can also make it appear, if instead of putting 5 into the initial question, you put 5 anmoloo7.
(3) in the printout the names appear below the title Order of Sorted Strings. But there is no linebreak in that printf. The thing is that the empty string is "smaller" than any other string, so it gets to the front of the list, and that is printed there first. If you do the 'trick' of appending a name after the initial number, the output will look different, there will be 6 names, and one of them appended directly to the title.
Plus there is the thing what you probably get from your compiler too: gets is a deadly function, forget its existence and use fgets with stdin as appears in other answers.
I have this sample that I made:
#include <stdio.h>
#include <string.h>
void main()
{
char str[100],ch;
int i,j,l;
printf("\n\nSort a string array in ascending order :\n");
printf("--------------------------------------------\n");
printf("Input the string : ");
fgets(str, sizeof str, stdin);
l=strlen(str);
/* sorting process */
for(i=1;i<l;i++)
for(j=0;j<l-i;j++)
if(str[j]>str[j+1])
{
ch=str[j];
str[j] = str[j+1];
str[j+1]=ch;
}
printf("After sorting the string appears like : \n");
printf("%s\n\n",str);
}
#include <stdio.h>
#include <string.h>
#define STRING_MAX_WIDTH 255
void sort_strings(char str_arr[][STRING_MAX_WIDTH],int len){
char temp[STRING_MAX_WIDTH];
for(int i=0;i<len-1;i++){
if(strcmp(&str_arr[i][0],&str_arr[i+1][0])>0){
strcpy(temp, str_arr[i+1]);
strcpy(str_arr[i+1],str_arr[i]);
strcpy(str_arr[i],temp);
sort_strings(str_arr, len);
}
}
}
int main(){
char str_arr[][STRING_MAX_WIDTH] = {"Test", "Fine", "Verb", "Ven", "Zoo Keeper", "Annie"};
int len = sizeof(str_arr)/STRING_MAX_WIDTH;
sort_strings(str_arr, len);
for(int i=0;i<len;i++){
printf("%s\r\n", str_arr[i]);
}
}

Comparing digits of two inputs to see if they are the same

I am currently trying to finish a code where a user inputs two 5 digit long numbers. The code then checks to see if there are any identical numbers in the same spot for the two numbers and displays how many identical numbers there are in the same spot of the two inputs. (ex. comparing 56789 and 94712 there would be one similar digit, the 7 in the 3rd digit place.) As of now I have been able to break down the inputs into the digits in each spot, I just need help comparing them. Originally I thought I could just create an int that would serve as a counter and use modulus or division to output a 1 whenever the digits were the same, but I have been unable to put together a formula that outputs a 1 or 0 depending on if the digits are alike or not.
suppose you know the length of strings n (as a condition you would need them to be equal, if they differ in length other validation is needed)
//n is the length of string
for(int i=0;i<n;i++)
{
if(string1[i]==string2[i])
{
//do something, make a counter that increments here...
//also save index i, so you can tell the position when a match occured
}else
{
//do something else if you need to do something when chars didnt match
}
}
Here you when i=0, you are comparing string1[0] with string2[0], when i=1, you compare string1[1] with string2[1] and so on.....
I'd recommend reading the two in as strings or converting to strings if you have the ability to. From there it's a simple string compare with a counter. Something like this:
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int is_numeric(char *str)
{
while (*str)
if (!isdigit(*str++))
return (0);
return (1);
}
int main(void)
{
char num1[32];
char num2[32];
int count = 0;
printf("Digit 1\n>> ");
if (scanf("%5s", num1) != 1 || !is_numeric(num1))
return (0);
printf("Digit 2\n>> ");
if (scanf("%5s", num2) != 1 || !is_numeric(num2))
return (0);
if (strlen(num1) != 5 || strlen(num2) != 5)
return (0);
for (int i=0; i<5; ++i)
if (num1[i] == num2[i])
++count;
printf("%d\n", count);
return (0);
}
You can do it very easy using modulo (%) and divide (/). First you do % 10 to get the least significant digit and do the compare. Then you do / 10 to remove the least significant digit. Like:
#include <stdio.h>
#include <string.h>
int main(void) {
unsigned int i1, i2;
int i;
int cnt = 0;
printf("Input first 5 digit number:\n");
if (scanf(" %u", &i1) != 1 || i1 < 10000 || i1 > 99999) // Get integer input and check the range
{
printf("input error\n");
return 0;
}
printf("Input second 5 digit number:\n");
if (scanf(" %u", &i2) != 1 || i2 < 10000 || i2 > 99999) // Get integer input and check the range
{
printf("input error\n");
return 0;
}
for (i=0; i<5; ++i)
{
if ((i1 % 10) == (i2 % 10)) ++cnt; // Compare the digits
i1 = i1 / 10;
i2 = i2 / 10;
}
printf("Matching digits %d\n", cnt); // Print the result
return 0;
}
It can also be done using strings. Read the input as unsigned int and then convert the value to a string using snprintf and finally compare the two strings character by character.
Something like:
#include <stdio.h>
#include <string.h>
int main(void) {
char str1[32];
char str2[32];
unsigned int i1, i2;
int i;
int cnt = 0;
printf("Input first 5 digit number:\n");
if (scanf(" %u", &i1) != 1) // Get integer input
{
printf("input error\n");
return 0;
}
snprintf(str1, 32, "%u", i1);
if (strlen(str1) != 5) // Convert to string
{
printf("input error - not 5 digits\n");
return 0;
}
printf("Input second 5 digit number:\n");
if (scanf(" %u", &i2) != 1) // Get integer input
{
printf("input error\n");
return 0;
}
snprintf(str2, 32, "%u", i2); // Convert to string
if (strlen(str2) != 5)
{
printf("input error - not 5 digits\n");
return 0;
}
for (i=0; i<5; ++i)
{
if (str1[i] == str2[i]) ++cnt; // Compare the characters
}
printf("Matching digits %d\n", cnt); // Print the result
return 0;
}
The reason for taking the input into a unsigned int instead of directly to a string is that by doing that I don't have to check that the string are actually valid numbers (e.g. the user type 12W34). scanf did that for me.

How do you count the number of occurences of a letter in a given word?

Hi how would you count the number of occurences in the given word like shown below because with the program I have right now it doesn't seem to room correctly.
#include <stdio.h>
int main(void)
{
char a;
char lang[] = "pneumonoultramicroscopicsilicovolcanoconiosis";
char i = 0;
char count = 0;
printf("pneumonoultramicroscopicsilicovolcanoconiosis\n");
printf("\nEnter the letter you want to find the number of\n");
scanf("%c", &lang);
for (i = 0; i <= 46; i++)
if (a == lang[i]) {
count++;
}
printf("Number of %c is %d..\n", a, count);
return 0;
Your scanf is the problem.
Try:
scanf("%c",&a);
declare count as int instead of char
also change scanf to take input a
#include <stdio.h>
int main(void)
{
char a;
char lang[] = "pneumonoultramicroscopicsilicovolcanoconiosis";
char i = 0;
int count = 0;
printf("pneumonoultramicroscopicsilicovolcanoconiosis\n");
printf("\nEnter the letter you want to find the number of\n");
scanf("%c", &a);
for (i = 0; i <= 46; i++)
if (a == lang[i]) {
count++;
}
printf("Number of %c is %d..\n", a, count);
return 0;
}
You probably shouldn't hard code the max length of the string (46) if at all possible in case you are given a longer string, but assuming it's an assigned assignment that is set it shouldn't be a problem.
i and count should also be ints if possible for a bigger size count. And &lang should be &a since lang is already assigned while a is your checker.

storing integer and char in an array

Objective:-To print A3B5 as shown below..
AAABBBBB
I have achieved this through following code:-
#include <stdio.h>
#include <conio.h>
void main(){
char char1[2],*ptr_char,c;
int number[2],*ptr_number,i,j=0,k=0;
ptr_char = char1;
ptr_number = number;
printf("Enter character string\n");
for(i=0;i<2;i++)
scanf("%c",&char1[i]);
printf("Enter number array\n");
for(i=0;i<2;i++)
scanf("%d",&number[i]);
for(i=0;i<ptr_number[j];i++)
printf("%c",ptr_char[k]);
j++;
k++;
for(i=0;i<ptr_number[j];i++)
printf("%c",ptr_char[k]);
getch();
}
///////////////////////////////////////////////////////////
Now i have to take a single array in which my A3B5 can be taken instead of taking two array.
But i am unable to take array like that.
I want to take A3B5 in single array .
Is this possible?
You can say:
char csrc[]= "A3B5" ;
The issue here is that 3 and 5 are not numbers, they are characters. So you will have to convert from "3" to 3. You have several options for that, including sscanf and atoi. As others have suggested, read in the entire string at once, and it will be in the char array, and then decompose it into the separate parts you want.
check this code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int count = 0, i = 0;
char temp = 0;
char ip[16] = {0};
char filter[8] = {0};
int num[8] = {0};
printf("Enter input :\t");
scanf("%s", ip);
for (count = 0, i =0; count < strlen(ip); count++, i++)
{
filter[i] = ip[count]; //take out the character to print
count++;
temp = ip[count]; //read the number of print iteration as a character
num[i] = atoi(&temp); // convert "n" [charater] to n [int]
}
for (count = 0; count < strlen(ip)/2 ; count++)
{ //print loop
for (i = 0; i < num[count]; i++)
printf("%c\t", filter[count]);
printf("\n\n");
}
return 0;
}
Sample run and o/p
[sourav#localhost test]$ ./a.out
Enter input : S2G5
S S
G G G G G
[sourav#localhost test]$

Resources