I want to print function argument in the printf command. Please help to suggest.
void printline(char ch, int len);
value(float, float, int);
main()
{
double amount;
printline('=', 30);
amount = value(500, 0.12, 5); // I want to print argument of function value. please help
printf("The total amount is: %f \n", amount);
//printf("%f\t%f\t%d\t%f \n", 500, 0.12, 5, amount);
printline('=', 30);
_getch();
}
void printline(char ch, int len)
{
int i;
for (i = 0; i < len; i++)
printf("%c", ch);
printf("\n");
}
value(float p, float r, int n)
{
int year;
float sum;
sum = p;
year = 1;
while (year <= 5)
{
sum = sum * (1 + r);
year = year + 1;
}
return(sum);
}
In your printline function you only have one character as an argument. So there is no purpose in iterating through it. If you want to print a string or array of characters you want to use char * or char[] and iterate through it. So your function printline could look like this:
void printline(char *ch, int len)
{
int i;
for (i = 0; i<len; i++)
printf("%c", ch[i]);
printf("\n");
}
just make sure that len isn't bigger then the length of *ch.
Even better solution, where you don't have to worry about the value of len is to print the characters one by one until you come across the \0 character indicating the end of an array.
void printline(char *ch)
{
int i;
for (i = 0; ch[i] != '\0'; ++i)
printf("%c", ch[i]);
printf("\n");
}
Or even better
If the string is null terminated, use printf("%s", ch). If the string is not null terminated but the length is supplied, use printf("%.*s", len, ch). In both cases, there's no loop in the user code; the loop is buried inside the printf() function. Further, since there's a newline printed after the loops, use printf("%s\n", ch) or printf("%.*s\n", len, ch) and skip the extra printf() after the loop.
value(500, 0.12, 5); // I want to print argument of function value. please help
You can add a printf to the beginning of the function:
value(float p, float r, int n)
{
printf("%s(%f, %f, %d)\n", __func__, f, r, n);
Related
I'm trying to write a program that takes a string as an input, and returns any characters in the string which occur more than once, along with how frequently they occur. What I haven't been able to figure out is finding a way to get the program to return "No duplicates found" for strings with no repeating characters.
# include <stdio.h>
# include <stdlib.h>
#include <ctype.h>
# define NO_OF_CHARS 256
char fillCharCounts (unsigned char *str, int *count) {
int i;
for (i = 0; * (str + i); i++)
count[* (str + i)]++;
return 0;
}
void printDups (unsigned char *str) {
int *count = (int *) calloc (NO_OF_CHARS, sizeof (int));
fillCharCounts (str, count);
int i;
for (i = 0; i < NO_OF_CHARS; i++)
if (count[i] > 1)
printf ("\nDuplicate letter: %c, Occurrences: %d", i, count[i]);
/* area of concern */
if (count[i] < 1)
printf ("\nNo duplicates found\n");
exit (0);
printf ("\n");
free (count);
}
int main() {
unsigned char str[15] = "";
printf ("Enter a word>");
scanf ("%s", str);
printDups (str);
getchar();
return 0;
}
The program returns characters that occur more than once along with their frequency, but it always returns "No duplicates found" along with this. How can i fix it so it only returns "No duplicates found" for strings with no repeating characters?
You need to use a flag/counter say dupe_chars to track if one or more duplicate characters were found.
int dupe_chars = 0; // an integer flag/counter
for (int i = 0; i < NO_OF_CHARS; i++)
if (count[i] > 1) {
printf ("\nLetter: %c, Occurrences: %d", i, count[i]);
++dupe_chars; //counting duplicate letters
}
/* area of concern */
if (0 != dupe_chars)
printf ("\nDuplicates of %d chars were found\n", dupe_chars);
else
printf ("\nNo duplicates were found\n");
//exit (0); // not necessary
#include <stdio.h>
int length(char *point)
{
int n=0;
if (*point!='\0')
{
point++;
n++;
}
return n;
}
void main()
{
int m;
char *point;
char chars[80];
printf ("please enter a chars\n");
gets(chars);
point=chars;
m=length(chars);
printf("The length of the chars is %d.\n",m);
}
I want to ask why the "n" can't be added?
I think the problem is about the use of point,but i can't find it.
Thanks.
size_t length(const char *point)
{
size_t n = 0;
while (*point != '\0') // Need to loop to iterate through point
{
point++;
n++;
}
return n;
}
I would use it in the main like that :
int main(void)
{
char chars[80];
printf ("Please enter a chars\n");
scanf("%79s", chars);
// The 79 is there to limit the input to the size you allocated in chars[80]
// Thus avoiding buffer overflow
size_t m = length(chars);
printf("The length of the chars is %zu.\n",m);
return 0;
}
You forget to iterate through the string. You incremented the pointer but that's all. Also, I recommend using strlen() which does exactly what you intend to do.
Using strlen():
int main(void)
{
char chars[80];
printf ("Please enter a chars\n");
scanf("%79s", chars);
size_t m = strlen(chars);
printf("The length of the chars is %zu.\n", m);
return 0;
}
You don't have a loop inside your function length(). The if is only evaluated once.
Add (or replace the if with) a loop statement
/* loop */ {
if (*point!='\0') { /* ... */ }
}
The following code snippet is intended to count all the symbols met in a file after text is entered, next step is counting the occurrences of all characters (For instance 'a' met 3 times, 'b' 0 times etc.). However when I compile the loop goes infinite and the counting is always 0. My question is if it could be fixed or rewritten in another way.
char type, c, text[100]; counts[100];
int count=0, i;
while((type=getchar())!=EOF) {
fputc(type, f); count++;
}
printf("Symbols found: %d", count-1);
rewind(f);
while(fscanf(f, "%s", &text)) {
for (i = 0; i < strlen(text); i++) {
counts[(text[i])]++;
printf("The %d. character has %d occurrences.\n", i, counts[i]);
}
}
You can build your histogram as you read the input. The return value from getchar() is an int, not a char, since it has to represent EOF in addition to the 256 char values. Once the histogram has been built, you can iterate over the buckets and print them. Here, I have assumed that all 256 char values are possible, and included code to display unprintable characters in hex notation.
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main(int argc, char **argv)
{
int c;
int i;
int histogram[256];
int total;
memset(histogram, 0, sizeof(histogram));
total = 0;
while ((c = getchar()) != EOF) {
histogram[c]++;
total++;
}
printf("Symbols found: %d\n", total);
for (i = 0; i < 256; i++) {
if (histogram[i]) {
char repr[5];
sprintf(repr, isprint(i) ? "%c" : "\\x%02x", i);
printf("The '%s'. character has %d occurrences.\n", repr, histogram[i]);
}
}
return 0;
}
Your for loop scans the string with variable i being an index to the character tested, but your printf says i is a symbol accounted.
You should separate counting and printing results:
char * ptr;
while(fscanf(f, "%s", text))
for (ptr = text; * ptr != 0; ptr++)
counts[ (unsigned char)*ptr ]++;
for( i = 0; i < 256; i++)
printf("The %d. character has %d occurrences.\n", i, counts[i]);
Don't forget to declare count[ 256] and note that scanf gets text, not `&text~as a destination.
i'm trying to print a 2d array of string as practice(i'm a newbie) with no success i've tried every combination i could think of still nothing i'm sure i'm doing a silly error somewhere i just can't see it here some of the example:
using a pointer :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define lim 10
#define maxx 25
void print(char *);
int main()
{
int i = 1;
char input[lim][maxx];
char *ps = input;
printf("type the list of %d names or type quit to leave \n", lim);
while (i<lim && gets(input[i]) != NULL && strncmp(input[i], "quit", 4)!=0 ) {
i++;
}
printf("i've counted %d names\n", i);
print("\n");
print(ps);
return 0;
}
void print(char *a)
{
int i=0;
printf("the list of names include : \n");
while(*(a) != '\0') {
printf("%s\n", *(a+i));
i++;
}
}
here's the output:
type a list of %d names or type quit to leave :
bla
bli
blo
quit
i've counted 4 names
the list of names include :
segmentation fault (core duped)
another version of the print function is like this :
void print(char aray[lim][maxx])
{
int i,j;
printf("the list of names include : \n");
for(i = 0; i < lim; i++) {
for(j = 0; j < maxx; j++){
puts(aray[i][j]);
//printf("%s\n", aray[i][j]);
}
}
}
i get the same output, can anyone help me debug this ? and thx in advance
In short, it looks like you need to brush up on your pointers. With your original print function:
void print(char *a)
{
int i=0;
printf("the list of names include : \n");
while(*(a) != '\0') {
printf("%s\n", *(a+i));
i++;
}
}
You are printing the value at a + i every iteration. This might sound like what you want, but what you actually pass to print is a pointer to an array of arrays of char (your compiler should be throwing a warning about incompatible pointer types). That is, the "proper" type of ps is (char *)[]. So in the print function you are only advancing the memory address by sizeof(char) with each iteration, whereas what you actually want is to increment it by sizeof(char) * maxx (the size of your array entries). To implement this change, do the following:
change declaration of print
void print(char (*)[maxx]);
change to proper pointer type
char (*ps)[maxx] = input;
And finally, change print function to something like:
void print(char (*a)[maxx]){
printf("the list of names include : \n");
int i;
for (i = 0; i < lim; i++){
printf("%s\n",*a);
a++;
}
}
You need not use the (a+i) syntax, as just advancing a by one each iteration accomplishes the same thing, and is possibly faster for large i. And of course, as others have mentioned, double check your new line printing, I believe you want printf('\n').
You are adding i as 1 which will not help in case of your two dimensional array as the next element will be at maxx location,so you can do something like this
//here lim and max are defined in your program
void print(char *a){
int i=0;
printf("the list of names include : \n");
while(i<(lim*maxx)){
printf("%s\n",a );
i += maxx;
a = a + maxx;
}
}
and the second variant should be
void print(char aray[lim][maxx])
{
int i,j;
printf("the list of names include : \n");
for(i = 0; i < lim; i++) {
cout<<aray[i]<<"\n";
}
}
You start on index 1 in your 2d array, you should start with index 0
int i=1;
Your print function takes an array of characters and then does a printf string of each character which makes no sense
void print(char *a)
{
int i=0;
printf("the list of names include : \n");
while(*(a)!='\0')
{
printf("%s\n",*(a+i));
i++;
}
}
instead make it look like this
void print(char *a[], int strings)
{
int i = 0;
for (; i < strings; ++i)
{
puts( a[i] );
}
}
and call it with the number of strings you read
print(ps,i);
You would also be better off using fgets() instead of gets(), especially since your strings are max 25 chars so its easy to give a longer string. fgets() lets you specify the max size of the string fgets(input[i],maxx,stdin)
Your other function
void print(char aray[lim][maxx])
{
int i,j;
printf("the list of names include : \n");
for(i = 0; i < lim; i++) {
for(j = 0; j < maxx; j++){
puts(aray[i][j]);
//printf("%s\n", aray[i][j]);
}
}
}
does a similar wrong assumption about the level of indirection
arra[i][j] is one character but puts takes a string argument, so puts( arra[i][j] ); is not correct, you could try fputc( arra[i][j], stdout ) instead since fputc takes one character
fix to
void print(char (*)[maxx]);
int main()
{
int i = 0;//int i = 1;
char input[lim][maxx] = { {'\0'}};
char (*ps)[maxx] = input;
printf("type the list of %d names or type quit to leave \n", lim);
while (i<lim && gets(input[i]) != NULL && strncmp(input[i], "quit", 4)!=0 ) {
i++;
}
printf("i've counted %d names\n", i);
printf("\n");//print("\n");
print(ps);
return 0;
}
void print(char (*a)[maxx])
{
int i=0;
printf("the list of names include : \n");
while(i<lim && a[i][0] != '\0') {
printf("%s\n", a[i]);
i++;
}
}
I have to sort strings in a lexicographical order using the Bubble Sort technique without using any library functions. I have written the following code which is working fine in sorting the strings.
But the problem is that if I give n as the input (say n = 4), I can enter only n-1 strings (only 3 strings).
The problem can be solved by running the for loops from 0 to n, but that isn't a logical solution.
What am I doing wrong here?
#include <stdio.h>
#include <string.h>
#include <malloc.h>
void swap(int indx[], int j)
{
int temp;
temp = indx[j];
indx[j] = indx[j+1];
indx[j+1] = temp;
}
void sort(char **str, int indx[], int n)
{
int i, j, k;
for(i=0; i<n; i++)
{
for(j=0; j<n-i-1; j++)
{
k = 0;
while(str[j][k] != '\0')
{
if((str[indx[j]][k]) > (str[indx[j+1]][k]))
{
swap(indx, j);
break;
}
else if((str[indx[j]][k]) < (str[indx[j+1]][k]))
break;
else
k++;
}
}
}
}
void display(char **str, int indx[], int n)
{
int i;
printf("Sorted strings : ");
for(i=0; i<n; i++)
printf("%s\n", str[indx[i]]);
}
int main(void)
{
char **str;
int n, i, j, *indx;
printf("Enter no. of strings : ");
scanf("%d", &n);
str = (char **) malloc (n * (sizeof(char *)));
indx = (int *) malloc (n * sizeof(int));
for(i=0; i<n; i++)
str[i] = (char *)malloc(10 * sizeof(char));
printf("Enter the strings : ");
for(i=0; i<n; i++)
{
gets(str[i]);
indx[i] = i;
}
sort(str, indx, n);
display(str, indx, n);
}
The problem is your use of scanf(). When you do scanf("%d", &n), the scanf() function reads input until it finds an integer, and puts the value into n. However, when you entered that integer, you didn't just type '4', you typed '4' and pressed Enter. And the newline is still in the input buffer. The gets() function, on the other hand, reads input up to and including the first newline, and the newline character is discarded. So when you're reading the input strings, the gets call to gets() reads the newline, and returns immediately. And then, the first string that you enter is read by the second call to gets()...
Incidentally, The gets() function should never, ever, under any circumstances, ever be used for real programs, because it doesn't allow you to limit input. Better would be to use fgets(). fgets(str[i], BUFFERSIZE-1, stdin).
int main(void)
{
char **str;
int n=4, i, j, *indx;
printf("Enter no. of strings : ");
//scanf("%d", &n);
str = (char **) malloc (n * (sizeof(char *)));
indx = (int *) malloc (n * sizeof(int));
for(i=0; i<n; i++)
str[i] = (char *)malloc(10 * sizeof(char));
printf("Enter the strings : ");
for(i=0; i<n; i++)
{
gets(str[i]);
indx[i] = i;
}
sort(str, indx, n);
display(str, indx, n);
}
//if i comment out scanf and give int the value it works fine //
so the problem is use of fgets just after scanf as scanf leave a newline character in the buffer// so consume it before using fgets
Try this at the line where you have to input the string. Instead of:
gets(str[i]);
type:
scanf("%s",str[i]);