I have this exercise that i can't understand and i hoped somebody could help me with it.
Develop a function that receives a table of strings, each one
with a maximum of 40 characters, and return the index of the largest of them. Note: The function receives a two-dimensional table, with the first dimension of the table not specified.
My question is how do i use the two dimensional table in this exercise i normally only used the a normal array to do strings, and after that what is exactly the index of a string? Is its lenght? Because if it is i know how to do the problem using the function strlen. I just dont understand how the table will work. If somebody can please help me (sorry for my bad english).
code
This means, your function should work like this:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int func (char table[][40], int numentries) {
...
}
int main (void) {
int index;
char example[][40] = {
"this",
"is",
"an",
"example",
"with",
"seven",
"words"
};
index = func(example, 7);
printf("The longest word has index %d\n", index);
exit(EXIT_SUCCESS);
}
(maybe it should even be 41 instead of 40 to have space for the zero-byte, depending if this is already counted in or not in the specification)
Now, each entry of the table has at most 40 characters, but the number of entries is unspecified and has to be passed in a separate argument.
You can iterate over the table from i = 0 up to numentries and find the element with the greatest length. The corresponding i is the index you have to return.
Here is an example, make sure you understand what was done- if something is unclear- ask. I hope this helps:
Note that if there are multiple max the index returned will be for the first string of that length.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int GetLongestString(char sArr[][40], int row)
{
int i = 0;
int max = 0;
int maxindex = -1;
for(i= 0 ; i< row; ++i) /*to check each row*/
{
if(max < strlen(&sArr[i][0])) /*gives the add of each rows string beginning for
the strlen function */
{
max = strlen(&sArr[i][0]);/*get the max value and store it for later
checks*/
maxindex = i;/* save the index of max length*/
}
}
return maxindex;
}
int main()
{
int res = 0;
char array[2][40] ={"all", "hello"};
char array2[2][40] ={"hello", "all"};
res = GetLongestString(array,2);
printf("%d\n", res);
res = GetLongestString(array2,2);
printf("%d\n", res);
return 0;
}
Good luck!
Related
Write a function common_char that takes two strings as arguments and returns a new string that contains a single copy of all characters that appear in either of the two strings.
For example, string1: hello; string2: world; the new string is : hellowrd (o and l were already in array from hello).
May use string function here.In other words, all characters in string1 are copied into the new string, but characters in string 2 are copied only characters that are not in string1. That is past exam question and the university did not provide answer. Here is my code.
#include <stdio.h>
#include <string.h>
char *common_char(char *string1, char *string2) {
int str_length1 = strlen(string1);
int str_length2 = strlen(string2);
char *new_string = malloc(str_length1+str_length2+1);
for (int index_1 = 0; index_1 < str_length1; index_1++) {
for (int index_2 = 0; index_2 < str_length2; index_2++) {
if (string1[index_1] == string2[index_2]) {
}
}
}
}
int main(void) {
return 0;
}
My idea is to find duplicate characters in string 2 and string 1 according to the nested loop, but there is a problem with the conditional statement, there is red line, also how to copy the character of the non-duplicate string? I know strcopy(), but how to remove the repeated characters?
I've come up with a solution that uses dynamic memory and resizes the result char* each time a new char must be added. There are two loops, the first iterates the b string and the second loop checks that non of char of the b string is repeated in the a string, if it is not repeated, then adds it. Hope you understand the realloc to resize dynamically the char* each time it must be added an element.
Firstly I initialize the result string to the size of string a so it can be all copied inside. The ordering method I think it is called bubble method.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char* common_char(char* a, char* b) {
char* result = (char*)malloc(sizeof(char)*strlen(a)+1);
int i = 0;
int j = 0;
int repeated = 0;
strcpy(result,a);
for(i=0; i<strlen(b); i++) {
for(j=0; j<strlen(result); j++) {
if(b[i] == a[j]) {
repeated = 1;
}
}
if(!repeated) {
result = (char*)realloc(result,strlen(result)+sizeof(char));
result[strlen(result)] = b[i];
result[strlen(result)+1] = '\0';
}
repeated = 0;
}
return result;
}
int main()
{
char a[] = "hello";
char b[] = "world";
char* result = common_char(a,b);
printf("%s", result);
return 0;
}
EDIT: I've modified the code to make it function. About the comment of memory allocation, I've modified the declaration of result to give it space for the '\0'. When doing the realloc, I've already considered that the realloc does not increment the strlen() because strlen() is a counter till the '\0' not of the size of the variable.
I declared a 2d array in main function and I want to get the number of elements in another function.
Let's say my main is like this.
#define col 100
#define row 10
int main(){
array[row][col] = {"abc1", "abc2", "abc3"};
int len = get2DLen(array);
}
and I copied this array in this form (*array)[column]
int get2DLen(char (*array)[col]){
int len;
//some operations..
return len;
}
Questions are..
how can I get col in func? In this case, 10.
how can I get the number of actual elements in the array? In this case, 3.
I'm aware of the fact that array means *array[0] in here.
I tried to iterate all the elements and check if it's '\0' like a normal char array string. But it's just absolutely wrong.. cause it was initialized anyway..
so any help would be appreciated
In C, it's not possible to determine the size of the array. Therefore, you can't get col in the function. You need to pass the dimension of the array to the function parameter.
#include <stdio.h>
#include <stddef.h>
#define col 100
#define row 10
int get2DLen(char (*array)[], size_t arr_row, size_t arr_col)
{
int len = arr_col;
return len;
}
int main()
{
char array[row][col] = {"abc1", "abc2", "abc3"};
int len = get2DLen(array, 3, 4);
printf("%d", len);
}
#include <stdio.h>
int main() {
char usernames[5][10] = {"Lebron","Davis","Schroder","KCP","Gasol"};
int i = 0;
for(i=0; i < 20; i++) {
printf("%s\n",usernames[i][20]);
}}
Hello guys, I'm new at programming and I study for use for loop with char arrays. You can see my code in top. The output I want to print is;
Lebron
Davis
Schroder
KCP
Gasol
I put my i into char's second dimension, is it not true? Basically, I want to print all the elements in my array, how can I do it? Thanks in advance.
Here you are storing data into 2d array. So, each row will store a sequence of char or a string . like usernames[0] = "Lebron" and so on. So, array length will be 5 . But you are trying to print 20 elements. that will give you runtime error.
here is the solution that will work for you.
#include <stdio.h>
int main() {
char usernames[5][10] = {"Lebron","Davis","Schroder","KCP","Gasol"};
int i = 0;
for(i=0; i < 5; i++) {
printf("%s\n",usernames[i]);
}
return 0;
}
I'm tasked with writing a function that will identify all the even numbers in an sample array {10,2,9,3,1,98,8] and place them in an array called EvenNumbers. I have to allow the function so that it works with different combinations of numbers in the array not just the numbers in the sample array above.
I'm wondering is there any way to add numbers to an array that could be different every time? How would I extract the even numbers an place them into an array? Also
for the even array size its giving me an error that the expression must have a constant value but when I use const int it still gives me that error.
Here is the full question.
"Using the array of sample values {10,2,9,3,1,98,8}, write a function that will identify all the even numbers in an array and place it in an array called EvenNumbers. The function must work in all cases, not just in the case of the array shown. Assume that the array size is always available through a global constant called MAX"
Here is what I have so far. I've no idea how I will extract the even numbers from a for loop and place them in an array. I also dont know what the "expression must have a constant value" is about?
#include <stdio.h>
#include <stdlib.h>
void EvenNumber(int Array[], int size);
int main()
{
int array[7] = { 10,2,9,3,1,98,8 };
EvenNumber(array, 7);
}
void EvenNumber(int Array[], int size)
{
int i;
int EvenArraySize;
for (i = 0; i < size; i++)
{
if (Array[i] % 2 == 0)
{
EvenArraySize++;
}
}
int Even[EvenArraySize];
}
The right way to go is to use malloc to allocate just the right amount of memory.
Count the number of even numbers
Allocate the space needed to store them
Copy even numbers in this space
Do whatever you want with these numbers
Free the allocated space
Snippet:
#include <stdio.h>
#include <stdlib.h>
#define MAX 7
int
main()
{
int array[] = {10,2,9,3,1,98,8};
int *even_numbers;
int i, nb_even_numbers;
for (i = 0, nb_even_numbers = 0; i < MAX; i++)
{
if (array[i] % 2 == 0)
nb_even_numbers++;
}
even_numbers = malloc(sizeof(int) * nb_even_numbers);
if (!even_numbers)
{
perror("malloc");
return 1;
}
for (i = 0, nb_even_numbers = 0; i < MAX; i++)
{
if (array[i] % 2 == 0)
even_numbers[nb_even_numbers++] = array[i];
}
/* do your stuff here */
free(even_numbers);
return 0;
}
First, you can never return a statically declared array from a function (even though you don't explicitly try, your Even array is destroyed when EvenNumber returns) Why? The function stack frame for EvenNumber is released for reuse on return and any locally declared arrays are no longer valid.
You either need to pass a second array as a parameter to EvenNumber, or you can dynamically allocate storage for Even in EvenNumber (with, e.g. malloc or calloc or realloc) and return a pointer to the beginning of the array. (you must also have some way to return the size or use a constant for a max size).
There is no need to use % (modulo) to test whether a number is odd/even. All you need to do is look at bit-0 (little endian). If it is 0, then the number is odd, if it is 1, then its even. Much more efficient than calling modulo which incorporates division.
Finally, main is type int and therefore returns a value.
Putting those pieces together, you can do something simple like the following:
#include <stdio.h>
#include <stdlib.h>
void EvenNumber (int *array, int *even, int size, int *esize);
int main (void)
{
int array[] = { 10,2,9,3,1,98,8 },
i, n = sizeof array / sizeof *array,
even[n], /* a VLA of the same size as array is fine here */
esize = 0;
EvenNumber (array, even, n, &esize);
printf ("array: ");
for (i = 0; i < n; i++)
printf (" %2d", array[i]);
printf ("\neven : ");
for (i = 0; i < esize; i++)
printf (" %2d", even[i]);
putchar ('\n');
return 0;
}
void EvenNumber (int *array, int *even, int size, int *esize)
{
int i;
for (i = 0; i < size; i++)
if ((array[i] & 1) == 0) /* simply looking at bit-0 is all you need */
even[(*esize)++] = array[i];
}
Note: esize is passed as a pointer to EvenNumber and updated within the function so that the number of elements in even are available back in the calling function (main() here).
Example Use/Output
$ ./bin/arrayeven
array: 10 2 9 3 1 98 8
even : 10 2 98 8
Let me know if you have any further questions.
I've written code to make a right pyramid out a character.
However, when I execute the program, the last two lines of the pyramid have garbage characters placed after them even when it exceeds the size of the array.
The code is here:
#include <stdio.h>
#include <string.h>
#define ROW 5
int main(void) {
char array[ROW];
int x = 0;
int row = 0;
for (row = 0; row < ROW; row++) {
array[x] = 'a';
if (x < ROW) {
printf("%s\n", dolla);
}
x++;
}
getchar();
}
Where are the garbage characters coming from? It's only on lines after the third.
The problem in your code is that you have not terminated your string with \0 (null) character. Here's a workout for your code:
#include <stdio.h>
#include <string.h>
#define ROW 5
int main(void)
{
char array[ROW];
int x = 0;
int row = 0;
for(row = 0; row < ROW; row++)
{
array[x] = 'a';
if(x < ROW)
{
array[x+1]='\0';
printf("%s\n", array);
}
x++;
}
getchar();
}
I'm no specialist, but I've read the following in many typical C books:
int arrays in C are initialized to 0, while char arrays are initialized to garbage.
And yeah, forgot to mention, it's no dolla, it's array.
char array[ROW+1] = {0}; will help you a lot. You might have assumed array was empty but it was full of random characters. By initializing with {0}, the array starts with all zeroes.
I'm going to assume dolla was a transcription error and that either dolla should be array or that array used to be named dolla.
You are probably exceeding the values in the array to make the pyramid which results in printing out garbage values that were there before you even compiled your code.
When you print the values, rather than printing out whole array ( which means there can be garbage values included ) you can print up to the point where you have valid values and this can be done by introducing a null character '\0' at the end of the array.
Also initializing you array would be a better choice here as then you can debug your code better after seeing the output.