print int value or convert int to string in C language - c

I tried to print integer value, But It's print only result is
#include <stdio.h>
int main()
{
for (int i = 0; i < 10; i++){
if(i % 2 == 0){
printf("result is \n","%d",i);
}
}
return 0;
}
I tried this way. It's not print anything
int main()
{
char buffer[10];
for (int i = 0; i < 10; i++){
if(i % 2 == 0){
snprintf(buffer, sizeof(buffer), "%d", i);
}
}
return 0;
}

%d should not be a separate parameter to printf but part of the template.
Try
printf("result is %d\n",i);
With your second example, you use:
snprintf(buffer, sizeof(buffer), "%d", i);
It works by wiring the integer as a string to your buffer char array, not to the console (as per documentation).
Adding the line after the snprintf line:
printf("%s\n", buffer);
You could print the content of your buffer to the screen.

Related

Why is my program returning the wrong value?

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

For loop in c returning wrong value

image of issue with output
I'm reading a set of numbers from a file (1 2 3 4 5 6 7) and when I print them out in the while loop it returns the correct numbers. In the for loop directly below it, it's returning random numbers (under loop through array). Anyone know what is going on?
#include <stdio.h>
int main(int argc, char* argv[])
{
if(argc != 2){
printf("%s\n", "Wrong number of arguments");
}
else{
char* filename = argv[1];
printf("%s\n", filename);
FILE* fp = fopen(filename, "r");
int arrSize;
int array[arrSize];
int i = 0;
fscanf(fp, "%d\n", &arrSize);
printf("%d\n", arrSize);
while (fscanf(fp, "%d", &array[i]) == 1) {
printf("%d\n", array[i]);
i = i+1;
}
printf("%s\n", "Loop through array");
for (int j = 0; j < arrSize; j++) {
printf("%d", array[j]);
printf("\n");
}
fclose(fp);
}
}
You have:
int arrSize;
int array[arrSize];
int i = 0;
fscanf(fp, "%d\n", &arrSize);
When you define array, you have no idea what value is in arrSize; it is uninitialized.
You need:
int arrSize;
int i = 0;
fscanf(fp, "%d\n", &arrSize);
if (arrSize <= 0 || arrSize > MAX_ARRAY_SIZE)
…deal with error condition…
int array[arrSize];
You might want to think about writing the first loop as:
for (int i = 0; i < arrSize && fscanf(fp, "%d", &array[i]) == 1; i++)
printf("%d\n", array[i]);
This avoids overflowing the bounds of the array you have allocated. You then don't need the separate declaration of i either. The braces are optional; I wouldn't use them for a single, simple statement like the printf() call, but many people always use them. The braces become necessary, of course, if the loop is revised to:
for (int i = 0; i < arrSize; i++)
{
if (fscanf(fp, "%d", &array[i]) != 1)
break;
printf("%d\n", array[i]);
}
It's good that you test for fscanf(…) == 1; people often mistakenly test against EOF.
Look at this piece of code.
int arrSize;
int array[arrSize];
int i = 0;
fscanf(fp, "%d\n", &arrSize);
What do you think what will happen?
You are declaring an array without defining its size.
int arrSize;
fscanf(fp, "%d\n", &arrSize);
int array[arrSize];

C, dividing a string in half

I am trying to write a function to divide a string in half but after the initial input it does not output anything. My goal is to scan a year and save the first two number and the last two numbers. This is the code:
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char scan_year2() {
char year_number;
scanf("%s", year_number);
return year_number;
return 0;
}
// Function to print n equal parts of str
void divideString(char *str, int n) {
int str_size = strlen(str);
int i;
int part_size;
if (str_size % n != 0) {
printf("Invalid Input: String size");
printf(" is not divisible by n");
return;
}
part_size = str_size / 2;
for (i = 0; i < str_size; i++) {
if (i % part_size == 0)
printf("\n");
printf("%s", str[i]);
}
}
int main() {
char year_number;
scan_year2();
char str = year_number;
divideString(str, 2);
getchar();
return 0;
}
Assuming that a year is at least a 3-digit number, the best way to treat it is to treat it as a number, not as a string:
...
int year;
scanf("%d", &year);
int first = year / 100;
int last = year % 100;
printf("%d %d\n", first, last);
...
dont ignore compiler warnings, it must be complaining at you about this
char scan_year2() {
char year_number;
scanf("%s", year_number);
return year_number;
return 0;
}
you try to return twice.
Also
part_size = str_size / 2;
for (i = 0; i < str_size; i++) {
if (i % part_size == 0)
printf("\n");
printf("%s", str[i]);
}
is not going to give you the correct output. YOu are outputing the string each time. IE if str = "1923" then you will get
1923923
232
You should do
part_size = str_size / 2;
for (i = 0; i < str_size; i++) {
if (i % part_size == 0)
printf("\n");
printf("%c", str[i]);
}
to only output one char at a time

C Reading numbers from file into array

hey so i m trying to read numbers from text file and put them into an array but ive been getting weird numbers when i try to print them. text file looks like:
45
77
8
...
i guess theres something wrong with the loop i m using but i cant seem to find out what.
thanks for your help!
code:
#define MAX_ARRAY_SIZE 20
int main(int argc, char * argv[])
{
FILE *myFile;
int myArray[MAX_ARRAY_SIZE];
//char filename[32];
//printf("enter filename\n");
//scanf("%s", filename);
myFile = fopen("asdf.txt", "r");
if (!myFile) {
printf("cant open file\n");
return 1;
}
int status;
int i = 0;
while ((status = fscanf(myFile, "%2d", &myArray[i])) == 1 && i < MAX_ARRAY_SIZE - 1) {
++i;
}
fclose(myFile);
int a;
for (a = 0; i < MAX_ARRAY_SIZE; ++i) {
printf("%d ", myArray[i]);
}
printf("\n");
return 0;
}
The problem is in your print loop:
for (a = 0; i < MAX_ARRAY_SIZE; ++i)
There is no guarantee you are reading MAX_ARRAY_SIZE values. Also, if you ar using 'a' as your loop iterator, then you need to use 'a'. Your loop should be:
for (a = 0; a < i; ++a)
printf("%d ", myArray[a]);
You also do not need a field-width in your format-specifier, fscanf(myFile, " %d", &myArray[i])) will do.
Try this
while ((status = fscanf(myFile, "%d\n", &myArray[i])) == 1 && i < MAX_ARRAY_SIZE - 1) {
++i;
}
True... I have not seen print loop code.. Sorry.
Problem is in print loop not fscan, please ignore my answer

Count all character occurrences in a text file

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.

Resources