In C coding: Create 2 functions and 1 test case for each function in main() with
ID: 3826372 • Letter: I
Question
In C coding:
Create 2 functions and 1 test case for each function in main() with expected output listed in comments.
There is a single test case setup in the zylab because it requires at least one test case. You should ignore that test case and produce your own test case and expected output for each function.
function1() - Linked List - Given a reference to a linked list:
(1) print out the number of nodes in the list,
(2) print out the positive values from the list, and
(3) calculate, print out, and return the sum of the negative values from the list.
function2() - pointers - Given a pointer to the first character that is the start of a c-string (remember c-strings end with a ''):
(1) determine and print out the length of the c-string without using strlen (do not use a strlen() for this portion of the code),
(2) print out the lower case characters from the c-string, and
(3) calculate, print out, and return the average number of words that contain the letters of your first name. example: zxcv.
Explanation / Answer
Code:
#include <stdio.h>
int function1(struct node *head)
{
struct node *p;
p = head;
int count = 0, sum = 0;
printf(" The positive values are: ");
//Traversing list.
while(p != NULL)
{
count += 1;
//Printing positive values.
if(p->data >= 0)
printf("%d ", p->data);
else
//Calculating sum of negative numbers.
sum += p->data;
}
printf(" Total number of nodes are: %d", count);
printf(" The sum of negative values: %d", sum);
return sum;
}
int function2(char *p)
{
int i, j, length = 0, flag = 0, words = 0;
char firstname[5] = {'A', 'K', 'A', 'S', 'H'};
printf(" Lower case characters: ");
for(i = 0; p[i] != ''; i++)
{
length++; //Calculating length.
//Checking for lower case letters.
if((int)p[i] >= 97 && (int)p[i] <= 122)
printf("%c ", p[i]);
//Checking for letters in my name.
for(j = 0; j < 5 && flag = 0; j++)
{
if(p[i] == firstname[j] || ((int)p[i] + 32) == firstname[j])
{
flag = 1;
break;
}
}
//Increasing words counter.
//words counter holds no. of words that contain letters of my first name.
if(p[i] == ' ' && flag == 1)
{
flag = 0;
words += 1;
}
}
//Checking for the last word in the string.
if(flag == 1)
words += 1;
printf(" The length of the string is: %d", length);
printf(" The number of words that contain letters of my first name: %d", words);
return words;
}
int main()
{
/*FUNCTION 1 - TEST CASE
*INPUT:
*LINKED LIST: 2 3 -5 -9 8 10 12
*
*EXPECTED OUTPUT:
*The positive values are:
*2 3 8 10 12
*Total number of nodes are: 7
*The sum of negative values: -14
*/
/*FUNCTION 2 - TEST CASE
*INPUT:
*STRING: This is a Cat
*
*EXPECTED OUTPUT:
*Lower case characters:
*h i s i s a a t
*The length of the string is: 13
*The number of words that contain letters of my first name: 4
*/
return 0;
}