Monday 23 January 2017

Vertical histogram of frequencies of characters in a given string using an example in C programming(c programming examples)(c program examples)

Vertical histogram of frequencies of characters in a given string using an example in C programming

This is an example in C language which is written on the base of basic C programming, if condition and for loop.

If you want to see this code with a perfect indentation, copy the code into "sublime text editor" and make sure that the type of code is set to 'c' at the bottom right of the window. After pasting the code press the command "ctrl+shift+P", you get a search box. Type "indentation" you get an option like this below the search box "Indentation: Reindent lines". Clink on that to get the code with indentation.

Keywords:- vertical histogram in c, vertical histogram of characters in c, program to print a vertical histogram of characters in c.


The program is as follows:

#include <stdio.h>
int main()
{
char string[1000],cc[100],c[100];
int i,j,k,check=0,max=0;
printf("enter any string\n");
gets(string);
for(i=0;string[i]!='\0';i++)
{
for(j=0;j<i;j++)
if(string[i]==string[j])
check++;
if(check==0)
{
cc[k]=string[i];
k++;
}
check=0;
}
cc[k]='\0';
for(i=0;i<k;i++)
{
for(j=0;string[j]!='\0';j++)
{
if(cc[i]==string[j])
check++;
}
c[i]=check;
check=0;
}
c[i]='\0';
for(i=0;cc[i]!='\0';i++)
printf("%c  %d\n",cc[i],c[i] );
for(i=0;c[i]!='\0';i++)
if(max<c[i])
max=c[i];
for(max=max;max>0;max--)
{
for(i=0;c[i]!='\0';i++)
{
if(max!=c[i])
printf("_");
if(max==c[i])
{
printf("*");
c[i]--;
}
}
printf("\n");
}
for(i=0;cc[i]!='\0';i++)
printf("%c",cc[i]);
return 0;
}


The output is as follows:




This is an example in C language which is written on the base of basic C programming, if condition and for loop.


Detailed explanation about the program:

ABOUT STDIO.H
STANDARD INPUT AND OUTPUT HEADER FILE
     'Stdio.h' is a header file. Header files are the files with an extension '.h' after the name of the file.  Header files are the set of defined functions in C source files. These defined functions are very helpful in compiling and execution of the code. Including of these header files is same as copying the functions in the code. But, using of predefined source files with header files is very flexible to understand and write the code. It also helps in debugging also. The following functions are written in the stdio.h file.

printf() :- This function is used to print whatever the user want to print.
scanf() :- This function is used to assign the input value given by the user into a variable or to an array.
getc() :- This function reads a character from the file.
gets() :- This function reads the entire line given by the user.
getchar() :- This function reads the character given by the user.
puts() :- This function prints the line on the output screen.
putchar() :- This function prints a character on the output screen.

clearerr() :- This function clears the error indicators.

--------------------------------------------------------------------------------------------------------------------------


char string[1000],cc[100],c[100];

     Declared three type of strings. The array 'char string[1000]' is used to hold the given input by the user. The array 'cc[100]' is used to store the unique characters in the given input string by the user.  The third array 'c[100]' is used to carry the number of occurrences of each unique character in the string.

 int i,j,k,check=0,max=0;

    We declared integer variables for some operations in the program.  i,j and k are used in for loop for iterations.  Especially the integer variable 'k' is used to know the number of unique characters and the size of the two arrays 'cc[100]' and 'c[100]'. The 'check' variable is used to count the number of occurrences of each unique character in the given string.  The variable 'max' is used to find the maximum number of occurrences among all the characters in the array.

printf("enter any string\n");

    It is the message to the user as a call to enter the input to print the vertical histogram of the individual unique characters in the string.

gets(string);

     This line is to store the given string input by the user into an array 'string[1000]'.

for(i=0;string[i]!='\0';i++)
   {
       for(j=0;j<i;j++)
           if(string[i]==string[j])
            check++;
        if(check==0)
        {
           cc[k]=string[i]; 
           k++; 
       }
       check=0;
   }

Here comes the for loop. The syntax of for loop is as bellow:
for(initiation;codition;increment/decrement)
{
          /*body of loop*/
}

Initiation: i=0
     
     According to arrays the address of each box of an array is addressed by a number. And the first box is addressed as 'string[0]' so, we take '0' as the initiation.

Condition: string[i]!='\0'

    The command gets() stores the each individual character into a box in an array. At the end of the last character, the array is filled with null character.  So, in the condition, we tell the computer to check whether iteration comes to an end or not. At the end, the for loop terminates and the execution carries on to the next line of the program.

Increment/Decrement: i++;

     To check each character stored in string[i] we use an increment of 'i' by one.  

 for(j=0;j<i;j++)

     Inside there is another for loop to check the character is repeated how many times previously.

 if(check==0)
        {
           cc[k]=string[i]; 
           k++; 
       }
If the character is not repeated previously the character is stored in the second array 'cc[100]'.

check=0;

After checking each character the variable is assigned by '0' for the next iteration.

  for(i=0;i<k;i++)
   {
       for(j=0;string[j]!='\0';j++)
       {
           if(cc[i]==string[j])
               check++;
       }
       c[i]=check;
       check=0;
   }

     This for loop is used to find the number of occurrences of each individual character in the given input string.

for(i=0;c[i]!='\0';i++)
       if(max<c[i])
           max=c[i];
       for(max=max;max>0;max--)
       {
           for(i=0;c[i]!='\0';i++)
           {
               if(max!=c[i])
                   printf("_");
               if(max==c[i])
               {
                   printf("*");
                   c[i]--;
               }
           }
           printf("\n");
       }

Here comes the major logic the entire program to print the histogram based on the repetition of the characters in the given string. First, we find the maximum number in the array 'c[100]' and then it prints the character '*' else it prints the character '_'. After completion of all the boxes in the array, it prints new line character '\n'. The max value is decreased by one every time it gets the new line character and the number value is also decresed after printing the character '*'.

for(i=0;cc[i]!='\0';i++)
           printf("%c",cc[i]);

At the end of the histogram, we print the unique characters in the string to represent that the line above each character represents how times it is repeated in the string.


C is a general-purpose programming language. It has been closely associated with the UNIX system where is was developed, since both the system and most of the programs that run on it are written in C. The language, however, is not tied to any one operating system or machine; and although it has been called a “system programming language” because it is useful for writing compilers and operating systems, it has been used equally well to write major programs in many different domains.(c programming examples)(c program examples)
Many of the important ideas of C stem from the language BCPL, developed by Martin Richards. The influence of BCPL on C proceeded indirectly through the language B, which was written by Ken Thompson in 1970 for the first UNIX system on the DEC PDP-7.(c programming examples)
BCPL and B are “typeless” languages. By contrast, C provides a variety of data types. The fundamental types are characters, and integers and floating point numbers of several sizes. In addition, there is a hierarchy of derived data types created with pointers, arrays, structures, and unions. Expressions are formed from operators and operands; any expression, including an assignment or a function call, can be a statement. Pointers provide for machine-independent address arithmetic.(c programming examples)(c program examples)
C provides the fundamental control-flow constructions required for well-structured programs: statement grouping, decision making (if-else), selecting one of a set of possible cases (switch), looping with the termination test at the top (while, for) or at the bottom (do), and early loop exit (break).(c programming examples)(c program examples)
Functions may return values of basic types, structures, unions, or pointers. Any function may be called recursively. Local variables are typically “automatic,” or created anew with each invocation. Function definitions may not be nested but variables may be declared in a block-structured fashion. The functions of a C program may exist I separate source files that are compiled separately. Variables may be internal to a function, external but know only within a single source file, or visible to the entire program.(c programming examples)(c program examples)
A preprocessing step performs macro substitution on program text, inclusion of other source files, conditional compilation.(c programming examples)(c program examples)
C  is a relatively “low level” language. This characterization is not pejorative; it simply means that C deals with the same sort of object that most computers do, namely characters, numbers, and addresses. These may be combined and moved about with the arithmetic and logical operators implemented by real machines.(c programming examples)(c program examples)
C provides no operations to deal directly with composite objects such as character strings, sets, lists, or arrays. There are no operations that manipulate an entire array or string, although structures may be copied as a unit. The language does not define any storage allocation facility other than static definition and the stack discipline provided by the local variables of functions; there is n heap or garbage collection. Finally, C itself provides no input/output facilities; there are no READ or WRITE statements, and no built-in file access methods. All of these higher-level mechanisms must be provided by explicitly called functions. Most C implementations have included a reasonably standard collection of such functions.(c programming examples)(c program examples)


Finding the power of a number from 0 up to its 10th power using a function in a C program (c programming examples)(c program examples)

Finding the power of a number from 0 up to its 10th power using a function in a C program 

The above program is an example which is written on the base of syntaxes of basic C programming, for loop and functions.


If you want to see this code with a perfect indentation, copy the code into "sublime text editor" and make sure that the type of code is set to 'c' at the bottom right of the window. After pasting the code press the command "ctrl+shift+P", you get a search box. Type "indentation" you get an option like this below the search box "Indentation: Reindent lines". Clink on that to get the code with indentation. 


The program is as follows:

#include <stdio.h>
int power(int base, int expo)
{
int product=1;
for(expo=expo;expo>0;expo--)
product=product*base;
return product;
}
int main()
{
int i,a;
printf("enter the number to find its powers upto 10\n");
scanf("%d",&a);
for(i=0;i<10;i++)
printf("%d %10d\n",i,power(a,i));
return 0;
}


The output is as follows:







Entire detail of each step of the program is as follows:

---------------------------------------------------------------------------------
#include <stdio.h>

     In C programming there are header files. Header files are the set of functions written in the C directory to perform certain activities in the code. The '#'  symbol denotes that it isn't a code line. The compiler includes the functions written in that header file. The 'stdio.h' means standard input and output. The functions 'printf' & 'scanf' are included in the process of compilation of the code. After including the 'stdio.h' header file the computer knows to scan the input given by the user by using a function in that header file and printing the output of the result after the compilation by using printf function in the header file.

Here are some of the functions in 'stdio.h' 

     printf(), scanf(), getc(), gets(), getchar(), puts(), putchar()

 In our program we use 'printf()'  and 'scanf()' functions

     printf():- This function is used to print the output.
     scanf():- This function is used to read the input given by user according to the declaration of a type of variable in the code.
--------------------------------------------------------------------------


int power(int base, int expo)
{
int product=1;
for(expo=expo;expo>0;expo--)
product=product*base;
return product;
}

     This is a function and we named it as power. The two arguments represent the type of variables which is taken from the main() function and they names by base and expo.

     The symbol '{' denotes the begin of the body.  The function should return a value and according to the type of variable it returns, we name that type before the function name as 'int power'. 

     'int product=1' this line declares a new variable named as product and assign its value as '1'.

     The next line indicates a loop. Loop is a kind of operation repeated several times as long as the condition is satisfied. 'For loop' contains (declaration;condition;increment or decrement)
Firstly the value expo is taken from the main() function. We do not change the value so is written as expo=expo. Then condition is checked whether the body of loop execute or not. The loop is executed up to the value of 'expo=1'. When expo gets the value 0, the loop terminates and it will enter into the next line of code for execution. After every iteration expo value is decreased by '1'.

      product=product*base;
   
   This line is called logic to get the desired output for a given input. For every iteration, the value of 'product' is multiplied by 'base' and 'product' is assigned the new value. 


     return product;
   
     This line returns the value of the product to main() function.

--------------------------------------------------------------------------
int main()
{
int i,a;
printf("enter the number to find its powers upto 10\n");
scanf("%d",&a);
for(i=0;i<10;i++)
printf("%d %10d\n",i,power(a,i));
return 0;
}

  
      In C programming we use main() function to represent it as the main of the program. The word 'int' defines the variable as an integer type. And those variables take the integer values only.

     Printf statement prints the line "enter the number to find its powers up to 10" and then it waits for the user to enter a value. After entering the value by the user the scanf() function assigns the given value into the variable 'a'  then the execution process enters into the next line.Here again 'for loop' is used to get a series of values as long as the condition is satisfied. In the body of the loop "printf("%d %10d\n",i,power(a,i));" calls the power function by sending the variable values 'a' & 'i' and it gets the returned value from the power function. 
C is a general-purpose programming language. It has been closely associated with the UNIX system where is was developed, since both the system and most of the programs that run on it are written in C. The language, however, is not tied to any one operating system or machine; and although it has been called a “system programming language” because it is useful for writing compilers and operating systems, it has been used equally well to write major programs in many different domains.(c programming examples)(c program examples)
Many of the important ideas of C stem from the language BCPL, developed by Martin Richards. The influence of BCPL on C proceeded indirectly through the language B, which was written by Ken Thompson in 1970 for the first UNIX system on the DEC PDP-7.(c programming examples)
BCPL and B are “typeless” languages. By contrast, C provides a variety of data types. The fundamental types are characters, and integers and floating point numbers of several sizes. In addition, there is a hierarchy of derived data types created with pointers, arrays, structures, and unions. Expressions are formed from operators and operands; any expression, including an assignment or a function call, can be a statement. Pointers provide for machine-independent address arithmetic.(c programming examples)(c program examples)
C provides the fundamental control-flow constructions required for well-structured programs: statement grouping, decision making (if-else), selecting one of a set of possible cases (switch), looping with the termination test at the top (while, for) or at the bottom (do), and early loop exit (break).(c programming examples)(c program examples)
Functions may return values of basic types, structures, unions, or pointers. Any function may be called recursively. Local variables are typically “automatic,” or created anew with each invocation. Function definitions may not be nested but variables may be declared in a block-structured fashion. The functions of a C program may exist I separate source files that are compiled separately. Variables may be internal to a function, external but know only within a single source file, or visible to the entire program.(c programming examples)(c program examples)
A preprocessing step performs macro substitution on program text, inclusion of other source files, conditional compilation.(c programming examples)(c program examples)
C  is a relatively “low level” language. This characterization is not pejorative; it simply means that C deals with the same sort of object that most computers do, namely characters, numbers, and addresses. These may be combined and moved about with the arithmetic and logical operators implemented by real machines.(c programming examples)(c program examples)
C provides no operations to deal directly with composite objects such as character strings, sets, lists, or arrays. There are no operations that manipulate an entire array or string, although structures may be copied as a unit. The language does not define any storage allocation facility other than static definition and the stack discipline provided by the local variables of functions; there is n heap or garbage collection. Finally, C itself provides no input/output facilities; there are no READ or WRITE statements, and no built-in file access methods. All of these higher-level mechanisms must be provided by explicitly called functions. Most C implementations have included a reasonably standard collection of such functions.(c programming examples)(c program examples)
    
Printing a Vertical Histogram of words in a string representing the size of each word using an example in C program

Sunday 22 January 2017

Printing a Vertical Histogram of words in a string representing the size of each word using an example in C program(c programming examples)(c program examples)

Printing a Vertical Histogram of words in a string representing the size of each word using an example in C program

This is an example C program which is written on the base of basic C programming, If condition, for loop.


If you want to see this code with a perfect indentation, copy the code into "sublime text editor" and make sure that the type of code is set to 'c' at the bottom right of the window. After pasting the code press the command "ctrl+shift+P", you get a search box. Type "indentation" you get an option like this below the search box "Indentation: Reindent lines". Clink on that to get the code with indentation. 



The program is as follows:

#include <stdio.h>
#include <string.h>
int main()
{
char string[1000],hist[100];
int i,lc=0,max=0,j=0,nofwrd=1;
printf("enter any string\n");
gets(string);
for(i=0;string[i]!='\0';i++)
if(string[i]!='\n' && string[i]!=' ' && string[i]!='\t')
if(string[i+1]=='\n'||string[i+1]==' '||string[i+1]=='\t')
nofwrd++;
printf("%d\n",nofwrd);
for(i=0;string[i]!='\0';i++)
{
if(string[i]!='\n' && string[i]!=' ' && string[i]!='\t')
lc++;
if(string[i+1]=='\n'||string[i+1]==' '||string[i+1]=='\t')
{
hist[j]=lc;
lc=0;
j++;
}
}
hist[j]=lc;
hist[j+1]='\0';
for(i=0;hist[i]!='\0';i++)
if(max<hist[i])
max=hist[i];
for(max=max;max>0;max--)
{
for(i=0;hist[i]!='\0';i++)
{
if(max!=hist[i])
printf("_");
if(max==hist[i])
{
printf("*");
hist[i]--;
}
}
printf("\n");
}
return 0;
}


The output is as follows:





Detailed explanation about the program:

ABOUT STDIO.H
STANDARD INPUT AND OUTPUT HEADER FILE
     'Stdio.h' is a header file. Header files are the files with an extension '.h' after the name of the file.  Header files are the set of defined functions in C source files. These defined functions are very helpful in compiling and execution of the code. Including of these header files is same as copying the functions in the code. But, using of predefined source files with header files is very flexible to understand and write the code. It also helps in debugging also. The following functions are written in the stdio.h file.

printf (): - This function is used to print whatever the user wants to print.
scanf (): - This function is used to assign the input value given by the user into a variable or to an array.
getc (): - This function reads a character from the file.
Gets (): - This function reads the entire line given by the user.
getchar (): - This function reads the character given by the user.
Puts (): - This function prints the line on the output screen.
putchar (): - This function prints a character on the output screen.

Clearer (): - This function clears the error indicators.



--------------------------------------------------------------------------------------------------------------------------


char string[1000],hist[100];

Declaration of two arrays with sizes 1000 and 100. The first array is to store the string entered by the user. The second array is to store the number of letters in each word in an order from left to right.

int i,lc=0,max=0,j=0,nofwrd=1;

Declaration of integer type variables.  Integer 'i' is used in for loop to control the addressed of the each character in the string. 'lc' is used to find the number of letters in each word.  'j' is used in nested for loop. 'max' is used for finding the maximum value in the array. 'nofwrd' is used to count the number of words in the given string.

printf("enter any string\n");

Message to the user to give input to the program.

gets(string);

Command that stores the given input to the first array.

for(i=0;string[i]!='\0';i++)
       if(string[i]!='\n' && string[i]!=' ' && string[i]!='\t')
           if(string[i+1]=='\n'||string[i+1]==' '||string[i+1]=='\t')

               nofwrd++;

The for loop is to find the number of words in the given string. The conditions in both the if statements are used to find the end of the word and to increase the value of 'nofwrd' by one.

for(i=0;string[i]!='\0';i++)
           {
               if(string[i]!='\n' && string[i]!=' ' && string[i]!='\t')
                   lc++;
               if(string[i+1]=='\n'||string[i+1]==' '||string[i+1]=='\t')
               {
                   hist[j]=lc;
                   lc=0;
                   j++;
               }

           }
This loop is used to fill the second array with the sizes of each word in the given string by the user.  After every iteration the 'lc' value is sent into the second array for further use.  After counting the each word the value of 'lc' is assigned as zero to count from starting of the new word length.

 hist[j]=lc;

The condition we have written fails at the end of string because the end character in a string is null character. The condition fails and the last word length is not entered into the array. So, this line is added to store the length of last word in the string.

hist[j+1]='\0';

This line is to put a null character in the array after filling all the lengths of words in the string.

for(i=0;hist[i]!='\0';i++)
               if(max<hist[i])
                   max=hist[i];

This for loop is to find the maximum value in 'hist[i]'.

 for(max=max;max>0;max--)
               {
                   for(i=0;hist[i]!='\0';i++)
                   {
                       if(max!=hist[i])
                           printf("_");
                       if(max==hist[i])
                       {
                           printf("*");
                           hist[i]--;
                       }
                   }
                   printf("\n");
               }

This for loop is the main logic of the program.  This loop creates the histogram of lengths of words  in the given string.  The condition checks the value in each box of 'hist[]', when the value gets equal to it it prints the character '*' else it leaves a space. After printing the character '*' the value in the box is decreased by one to print the character again at the same place by decreasing the 'max' value by one. After checking all the boxes in 'hist[]' the computer prints a new line to get the picture as a histogram.


C is a general-purpose programming language. It has been closely associated with the UNIX system where is was developed, since both the system and most of the programs that run on it are written in C. The language, however, is not tied to any one operating system or machine; and although it has been called a “system programming language” because it is useful for writing compilers and operating systems, it has been used equally well to write major programs in many different domains.(c programming examples)(c program examples)
Many of the important ideas of C stem from the language BCPL, developed by Martin Richards. The influence of BCPL on C proceeded indirectly through the language B, which was written by Ken Thompson in 1970 for the first UNIX system on the DEC PDP-7.(c programming examples)
BCPL and B are “typeless” languages. By contrast, C provides a variety of data types. The fundamental types are characters, and integers and floating point numbers of several sizes. In addition, there is a hierarchy of derived data types created with pointers, arrays, structures, and unions. Expressions are formed from operators and operands; any expression, including an assignment or a function call, can be a statement. Pointers provide for machine-independent address arithmetic.(c programming examples)(c program examples)
C provides the fundamental control-flow constructions required for well-structured programs: statement grouping, decision making (if-else), selecting one of a set of possible cases (switch), looping with the termination test at the top (while, for) or at the bottom (do), and early loop exit (break).(c programming examples)(c program examples)
Functions may return values of basic types, structures, unions, or pointers. Any function may be called recursively. Local variables are typically “automatic,” or created anew with each invocation. Function definitions may not be nested but variables may be declared in a block-structured fashion. The functions of a C program may exist I separate source files that are compiled separately. Variables may be internal to a function, external but know only within a single source file, or visible to the entire program.(c programming examples)(c program examples)
A preprocessing step performs macro substitution on program text, inclusion of other source files, conditional compilation.(c programming examples)(c program examples)
C  is a relatively “low level” language. This characterization is not pejorative; it simply means that C deals with the same sort of object that most computers do, namely characters, numbers, and addresses. These may be combined and moved about with the arithmetic and logical operators implemented by real machines.(c programming examples)(c program examples)
C provides no operations to deal directly with composite objects such as character strings, sets, lists, or arrays. There are no operations that manipulate an entire array or string, although structures may be copied as a unit. The language does not define any storage allocation facility other than static definition and the stack discipline provided by the local variables of functions; there is n heap or garbage collection. Finally, C itself provides no input/output facilities; there are no READ or WRITE statements, and no built-in file access methods. All of these higher-level mechanisms must be provided by explicitly called functions. Most C implementations have included a reasonably standard collection of such functions.(c programming examples)(c program examples)

Counting the total number of occurrences of a given word in a string using a C program