I wrote the following code to solve the readability lab.
It is compiling well with no problem.
The problem is in the results, as for an unknown reason it always calculates s_avg as zero.
s_avg is the average number of sentences in 100 words.
#include <ctype.h>
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
//prototypes
int count_letters (string text);
int count_words(string text);
int count_sent(string text);
int main(void)
{
// get the user to prompt part of the story
string story = get_string("Text: \n");
//variables
int letters = count_letters(story);
int words = count_words(story);
int sentences = count_sent(story);
//show results
printf("%i letter(s)\n",letters);
printf("%i word(s)\n",words);
printf("%i sentence(s)\n",sentences);
// Calculate average number of letters & sentences per 100 words
int l_avg = (letters/words)*100;
int s_avg = (sentences/words)*100;
// Calculate Coleman-Liau index
int index = round(0.0588 * l_avg - 0.296 * s_avg - 15.8);
// check grade level
if(index<1)
{
printf("Before Grade 1\n");
}
else if(index>16)
{
printf("Grade 16+\n");
}
else
{
printf("Grade %i\n",index);
}
}
//count the number of letters
int count_letters (string text)
{
int l = 0;
for(int i=0,n=strlen(text); i<n; i++)
{
if((text[i]>=97 && text[i]<=122)||(text[i]>=65 && text[i]<=90))
{
l++ ;
}
}
return l;
}
//count the number of words
int count_words(string text)
{
int w = 1;
for(int i=0,n=strlen(text); i<n; i++)
{
if (text[i]==32)
{
w++ ;
}
}
return w ;
}
//count the number of sentences
int count_sent(string text)
{
int s=0;
for(int i=0,n=strlen(text); i<n; i++)
{
if ((text[i]==46) || (text[i]==33) || (text[i]==63))
{
s++ ;
}
}
return s;
}
I don't know why it keeps calculating int s_avg = (sentences/words)*100; as zero.
I realized that using the debug50 tool.
For calculating average number of letters & sentences, use double type variables instead.
double l_avg = ((double)letters / (double)words)*100;
double s_avg = ((double)sentences / (double)words)*100;
Integer division in C results in an integer, not a float. You have to explicitly cast the dividend and the divisor to float:
int i = 5 / 4;
printf("%d", i); // prints 1
float f = (float)5 / (float)4;
printf("%f", f); // prints 1.250000
So, int s_avg = (sentences/words)*100 should be:
float s_avg = (float)sentences / (float)words * 100;
Related
Please help me with the appropriate C algorithm without using arrays.
Example:
Input
123456789
2037
Output
Common figures are 2, 3, 7.
My failed attempt:
long a, b, original_a, original_b;
int i, j, figure_a, figure_b;
printf("a=");
scanf_s("%li", &a);
printf("b=");
scanf_s("%li", &b);
original_a = a;
original_b = b;
for (i = 0; i <= 9; i++)
for (j = 0; j <= 9; j++){
a = original_a;
b = original_b;
while (a||b){
figure_a = a % 10;
figure_b = b % 10;
a /= 10;
b /= 10;
if (i == figure_a && j == figure_b && i == j)
printf("%d, ", i);
}
}
You can convert both the integers to strings and then compare each character of the first string with the second one to check whether any of them matches or not. I've used nested for loops for comparing.
I've used strings because comparing each character of two strings is a lot easier than comparing each digit of two integers.
#include <stdio.h>
int main()
{
long int a,b;
int i,j;
scanf("%ld %ld",&a,&b); //taking both inputs
char temp_a[50],temp_b[50];
sprintf(temp_a, "%ld", a); //converting the first integer to a string
sprintf(temp_b, "%ld", b); //converting the second integer to a string
int length_a=strlen(temp_a); //length of first string
int length_b=strlen(temp_b); //length of second string
// matching whether any character is in common using nested for-loops
// printing the character as soon as it matches
// if a character matches, the loop breaks.
for(i=0 ; i<length_a ; i++)
{
for(j=0 ; j<length_b ; j++)
{
if(temp_a[i]==temp_b[j])
{
printf("%c",temp_a[i]);
break;
}
}
}
}
This is a fun little problem.
I threw together a quick, simple solution:
#include <stdio.h>
int main(void)
{
int a, b;
int d[10]={0};
scanf("%d %d", &a, &b);
while(a)
{
d[a%10] = 1;
a /= 10;
}
while(b)
{
if (d[b%10]) d[b%10]=2;
b /= 10;
}
for(a=0;a<10;++a) if (d[a]==2) printf("%d ", a);
return 0;
}
Link to IDE One code
Here's a short version that does not use arrays:
#include <stdio.h>
int main(void)
{
int a, b, c;
scanf("%d %d", &a, &b);
while(a)
{
c = b;
while(c)
{
if (c%10 == a%10)
{
printf("%d ", c%10);
break;
}
c /= 10;
}
a /= 10;
}
return 0;
}
This version runs slower than my first one, and does not print out the numbers in ascending order.
May it helps:
#include <stdio.h>
int original_a, original_b, i;
short digit_a, digit_b, digit_common;
short find_digit(int num);
int main()
{
printf("Insert 2 numbers a and b\n");
scanf("%d %d", &original_a, &original_b);
digit_a = find_digit(original_a);
digit_b = find_digit(original_b);
digit_common = digit_a & digit_b;
printf("digit_common: %x\n", digit_common);
printf("Common digits of a and b\n");
for(i = 0; i < 10; i++){
if(digit_common & (1<<i)){
printf("%d",i);
}
}
return 0;
}
short find_digit(int num){
short result = 0;
while(num>0){
result |= (1 << (num%10));
num /= 10;
}
return result;
}
This code is designed to find the sum of digits of 100!. I get the correct ouput in ideone but the wrong one in codeblocks. Please help.
#include <stdio.h>
#include <stdlib.h>
#define size_of_number 160
#define question 100
//Function Prototypes
void initialise(int[]);
int sum_of_digits(int[]);
void factorial(int[],int);
int main()
{
int number[size_of_number];
int sum;
initialise(number);
factorial(number, question);
//Getting the sum of the digits of the number
sum = sum_of_digits(number);
printf("The sum of the digits of %d! is %d.\n",question, sum);
return 0;
}
//Initially, the number is 0 so all it's digits are set to zero.
void initialise(int number[])
{
int i;
for(i = 0; i < size_of_number; i++)
{
number[i] = 0;
}
}
//Finding the factorial by multiplying the digits
void factorial(int number[], int num)
{
int i, first_digit;
int carry, replace, product;
first_digit = 0;
number[first_digit] = 1;
while(num != 1)
{
carry = 0;
for(i = 0; i <= first_digit; i++)
{
product = num*number[i] + carry;
replace = product%10;
carry = product/10;
number[i] = replace;
if( (i == first_digit) && (carry > 0) )
{
first_digit++;
}
}
num--;
}
}
//Finding the sum of all digits
int sum_of_digits(int number[])
{
int i, sum;
for(i = 0; i < size_of_number; i++)
{
sum = sum + number[i];
}
return sum;
}
I had problems with some other programs too. Why s Codeblocks not giving the correct output which is 648 ?
You don't initialize sum in the function sum_of_digits. Normal local variables don't automatically get a starting value in C, so your program has what the C standard calls undefined behaviour. Anything can happen, but what typically does happen is that the variable starts with whatever data happened to be in the place in memory where the variable happened to be located.
I need to make a function that sums my array, which is filled with random values. My function only returns 0 and not an actual summation of the array. I don't have much experience with arrays or random values, how can I code my arrSum function to give me the sum of the array when called?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 1000
int arrSum(int arr[SIZE], int b) {
if (b < 0) {
return 0;
} else {
return arr[b] + arrSum(arr, b - 1);
}
}
int main() {
int inputNum;
int i;
int arr1[SIZE];
int sum;
srand(time(0));
printf("Enter an integer between 0 and 1000: ");
scanf("%d", &inputNum);
sum = arrSum(arr1, inputNum);
printf("sum: %6d\n\n", sum );
printf(" Pos | Val\n");
printf("-------------\n");
for (i = 0; i < inputNum; i++) {
printf("%4d |%4d\n", i, rand() % 1001);
}
return 0;
}
The reason is initially there are no values in the array. But only 0.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 1000
int arrSum(int arr[SIZE], int b){
if (b < 0) return 0;
else return arr[b] + arrSum(arr, b-1);
}
int main(){
int inputNum;
int i,q;
int arr1[SIZE] = {0};
int sum;
srand(time(0));
printf("Enter an integer between 0 and 1000: ");
scanf("%d",&inputNum);
for(q=0;q<inputNum;q++){
arr1[q] = rand() % 1001;
}
sum = arrSum(arr1, inputNum);
printf("sum: %6d\n\n", sum );
printf(" Pos | Val\n");
printf("-------------\n");
for (i = 0; i < inputNum; i++){
printf("%4d |%4d\n", i,arr1[i]);
}
return 0;
}
The logic behind finding the sum inside the function is correct, assuming that b is within the range of the array indices. The real problem is that your array is not filled with random numbers - it is filled with zeros.
When you do
int arr1[SIZE] = {0};
you are initializing each element to 0, and are not changing it at any point during the program. So, your function returns the sum from indices 0 to b, but this turns out to be 0.
I need in c code that generates two numbers in horizontally...so that i can get token numbers for my login system.
I need that i get this:
token=0.152644,0.429187
so in example i have token= and random generated numbers that have at beginning 0. and then 6 random generated numbers separated with , sign.
How to get get this in C?
I have try this code but it does not give me what i want_
#include <stdio.h>
#include <string.h>
typedef
union
{
char tmp[sizeof(unsigned long long)];
unsigned long long myll;
} ll_t;
unsigned long long llrand(void)
{
FILE *in=fopen("/dev/urandom", "r");
ll_t ll_u;
fread(ll_u.tmp, sizeof(ll_u.tmp), 1, in);
fclose(in);
return ll_u.myll;
}
int main()
{
char tmp1[64]={0x0};
char working[64]={0x0};
int i=0;
for(i=0; i< 1; i++)
{
while(strlen(tmp1) < 6)
{
sprintf(working, "%lu", llrand() );
strcat(tmp1, working);
}
tmp1[6]=0x0;
printf("%s\n", tmp1);
*tmp1=0x0;
}
return 0;
}
From output i get this:
747563
102595
Can code be simple and short?
You can use rand() function:
#include <stdio.h> /* printf, scanf, puts, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
int randomNumber(int min, int max)
{
/* generate secret number between min and max: */
int res = rand() % (max-min+1) + min;
return res;
}
int main()
{
int i = 0;
srand (time(NULL));
for (i=0; i<100; i++)
printf("%d ", randomNumber(10, 1000000));
return 0;
}
That is full detail for rand():
http://www.cplusplus.com/reference/cstdlib/rand/
Here is the code that is working perfect:
#include <stdio.h>
#include <stdlib.h>
int main() {
int n1, n2;
time_t t;
srand((unsigned) time(&t));
n1 = rand() % 1000000 + 1;
n2 = rand() % 1000000 + 1;
printf("token=0.%d,0.%d\n", n1, n2);
return 0;
}
And output is:
token=0.289384,0.930887
A propose a different approach. Instead of generating 2 numbers and format them into the output string, generate 12 different digits and put them directly in place.
srand(time(0));
char output[] = "taken=0.XXXXXX,0.YYYYYY";
for (int n = 0; n < 2; n++) {
for (int k = 0; k < 6; k++) {
output[9 * n + 8 + k] = rand() % 10 + '0';
// you might want to write a function that deals with rand() bias
}
}
puts(output);
I'm stuck on Euler#4 which is to calculate the highest palindrome number by product of two 3-digit numbers. The answer I'm getting is always 0. Evidently help is required.
#include <stdio.h>
#include <conio.h>
int main()
{
int i,j,h=0,m=0,p=0;
clrscr();
for(i=100;i<1000;i++)
{
for(j=100;j<1000;j++)
{
p=i*j;
h=p/100000;
m=p%10;
if(h==m)
{
h=(p/10000)%10;
m=(p/10)%10;
if(h==m)
{
h=(p/1000)%10;
m=(p%1000)/100;
if(h==p)
{
printf("%d\n",p);
}
}
}
}
}
return 0;
}
Its wrong to do this, but still dont make it a habit. I think one can solve first 50 question with ease.
#include <stdio.h>
static int is_palindromic(unsigned int n);
int main(void)
{
unsigned int i, j, max = 0;
for (i = 100; i <= 999; i++) {
for (j = 100; j <= 999; j++) {
unsigned int p = i*j;
if (is_palindromic(p) && p > max) {
max = p;
}
}
}
printf("%u\n", max);
return 0;
}
int is_palindromic(unsigned int n)
{
unsigned int reversed = 0, t = n;
while (t) {
reversed = 10*reversed + (t % 10);
t /= 10;
}
return reversed == n;
}