• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » C » C Programming Basic

C Program HSC mark list for a single student

By Dinesh Thakur

In the HSC examination, there are six subjects each having a maximum of 100 marks. To pass the examination, a student has to score at least 35 marks in each subject. If a student passes, total marks and percentage marks are calculated and a class is awarded based on the percentage marks (perce)as follows:

75 < perce < 100     First class with Distinction

60 < perce < 75      First class

50 < perce < 60      Second class

35 < perce < 50

Let us use a one-dimensional integer array marks having six elements to store the marks obtained by a student in six subjects, variables total of type int and perce of type float to store total marks and percentage marks, respectively, and variable result of type char to store the examination result. The strings representing the result and class obtained by a student are not stored in any variables. Instead, they are printed directly on the screen. The algorithm for this program is given below.

Read marks in six subjects

Determine result (‘P’ or ‘F’)

if (result== ‘P’) {

Calculate total and perce

Determine class

Print total,perce,result and class

else print result

We can determine the result and total marks using the statements given below.

if (marks[O] >= 35 && marks[l) >= 35 && marks[2) >= 35 && marks[3) >= 35 && marks[4] >= 35 && marks[5] >= 35)

result = ‘P’;

else result= ‘F’;

total= marks[O] + marks[l] + marks[2] + marks[3) + marks[4] + marks[S];

However, it is much more convenient to use the for loop to determine the result and total marks as shown in the program given below.

/* HSC marknlist program */

#include <stdio.h>

void main ()

{

        int marks[6], total;    /* marks in 6 subjects and total marks *!

        float perce;               /* percentage marks */

        char result;               /* char indicating result (Pass/Fail) */

        int i;

        clrscr();

        /* accept marks */

        printf(“Enter marks in six subjects: “);

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

             scanf(“%d”, &marks[i]);

             /* determine result */

             result= ‘P’; /*assume student has passed*/

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

            {

                 if (marks[i] < 35)

                   {

                        result = ‘F’;

                        break;

                    }

             }

             if (result == ‘P’)

          {

                /* Student has passed: calc total marks and percentage marks */

                total = 0;

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

                  total+= marks[i];

                  float perce = total / 6.0;

                  /* print result, total marks and percentage marks */

                  printf (“Result: Pass\n”);

                  printf(“Total marks: %d\n”, total);

                  printf(“Percentage marks: %5.2f\n”, perce);

                  /* determine and print class */

                  if (perce >= 75.0)

                      printf(“Class: First with distinction\n”);

                  else if (perce >= 60.0)

                      printf(“Class: First\n”);

                  else if (perce >= 50.0)

                      printf(“Class: Second\n”);

                  else printf(“Class: —\n”);

            }

                  else printf(“Result: Fail\n”);

                  getch();

}

Enter marks in six subjects: 40 50 60 70 80 90

Result: Pass

Total marks: 390

Percentage marks: 65.00

Class: First

Enter marks in six subjects: 40 50 60 70 80 30

Result: Fail

C Program to Calculate the Mean and Standard Deviation

By Dinesh Thakur

For a list of numbers x whose elements are referred to as x0, x1,……, xn-1, the mean bar x and the standard deviation a are defined as [Read more…] about C Program to Calculate the Mean and Standard Deviation

C program to add two vectors of size n

By Dinesh Thakur

For two vectors a and b having n elements each, the addition operation yields a vector (say c) of size n. The ith element of the result vector is obtained by adding the corresponding vector elements, i.e., ci =ai+ bi. The algorithm to perform the desired addition is given below. [Read more…] about C program to add two vectors of size n

C Program Print a list of numbers in reverse order

By Dinesh Thakur

In this program, an array num of type int is used to store the given integer numbers and variable nelem to store their count. First, the value of nelem is read. Then a for loop is used to read the given numbers and store them in array num. Finally, another for loop is used to print the given numbers in reverse order. [Read more…] about C Program Print a list of numbers in reverse order

Static Arrays in C

By Dinesh Thakur

This feature can be used with arrays as well. A static array has the following characteristics: [Read more…] about Static Arrays in C

const Vectors in C

By Dinesh Thakur

If we desire that the elements of a vector should not be modified, we can declare that vector as a const vector. However, we must initialize this vector when it is declared, as it is not possible to modify it subsequently. Thus, a const vector can be declared and initialized as shown below.

const int mdays[] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30,31, 30, 31};

If we subsequently modify any element of this vector, the compiler gives an error. The compiler also gives a warning when this array is passed to a function that accepts a non const vector.

Now we need to understand the use of const arrays as function parameters. As we know, the use of the pass by reference mechanism makes an array parameter an input-output parameter. Modifications to an array parameter actually causes the corresponding array argument in the calling function to be modified. This may not be desirable in some situations.

In several situations we do not want a function to modify the given array argument. This can of course be written as a comment at the beginning of the function. However, it does not guarantee that we (or some one else) will not modify the array inside the function. To avoid any inadvertent modification to the argument array, we should use a const array. For example, the ivec_print function (Example 9.6a) used to print the elements of a given array does not and inadvertently should not modify the given array. Thus, we can use a const array as shown below (function body is omitted to save space):

void ivec_print(const int x[], int n) { … }

Now if the function inadvertently modifies one or more array elements (directly or through some function call), the compiler will be able to catch the error. This feature is very useful and prevents the occurrence of several hard to trace bugs.

Note that as in case of a scalar variable, we can pass a const or non-const array as an argument where a const array parameter is expected. However, the compiler gives a warning when we pass a const array where a non-canst array parameter is expected.

Finally note that while using a non-const array parameter, if we wish to modify the elements of the parameter array within a function without affecting the argument array, we will need to use a local copy of the array in the called function.

Arrays as Function Parameters in C

By Dinesh Thakur

We can pass an array (one, two or multidimensional) as an argument to a function. The C language allows us to define functions that have one or more arrays as parameters. These parameters can be of different types and sizes. Moreover, we can mix scalar and array parameters. A function that uses a single one-dimensional array as a parameter can be defined as shown below. [Read more…] about Arrays as Function Parameters in C

C – Storage Classes

By Dinesh Thakur

Every variable has a type associated with it which decides the values that can be assigned to it and the operations that can be performed on it. In addition, we can specify a storage class for a variable which decides the following:

1. The type of storage to be used (either memory or CPU registers)

2. The scope or the part of the program from which that variable can be accessed

3. The lifetime, i. e., how long the variable will continue to live or exist

4. The default initial value, i. e., the value assigned to the variable if it is not explicitly initialized.

The C language provides four storage classes, namely, automatic, register, static and external. The keywords for these storage classes are auto, register, static and extern, respectively. The characteristics of the storage classes are summarized in Table

Storage class

Storage

Scope

Lifetime

Default initial value

Register

CPU Registers

Local to block in

which variable is

defined

Till control remains

within the block in

which variable is

defined

Garbage

Automatic

Memory

Static

External

Global

Till the end of program execution

0 for arithmetic types;

NULL for pointers

A storage class is specified for a variable using the general format shown below.

storage_class data_type varl, var2, …;

The order of the storage class and data type can be altered and the int data type can be omitted. Consider the example given below.

auto int a, b;

register int i, j;

static float p, q;

extern char x, y;

This example declares a and b as automatic variables of type int, i and j as register variables of type int, p and q as static variables of type float and x and y as external variables of type char.

Note that if we do not specify the storage class for a variable, the defaults are applicable. Thus, a variable defined within a block without any storage class is an automatic variable and a variable defined outside any function without any storage class is an external variable. We can use any storage class while defining a variable within a block. However, for the variables defined outside any function, the storage class can be static or be omitted. The compiler will give an error if we use auto or register class for such variables defined outside any function.

Automatic Storage Class

As mentioned earlier, if we do not specify a storage class while defining a variable inside a block, the automatic storage class is assumed. However, we can use the auto keyword to explicitly specify the automatic storage class for such variables.

As we know, automatic variables are not initialized to any specific value by default. Thus, if we do not initialize an automatic variable when it is defined, it will have a garbage value, i. e., a random, unpredictable value which is likely to change each time the program is executed. Automatic variables are stored in memory. Their scope is local to the block in which they are defined, from the point of definition to the end of that block. Thus, once a variable is defined, it can be used in any subsequent part of that block including the blocks nested within it. However, it cannot be used outside that block.

An automatic variable is created every time control enters the block in which it is defined and it lives until control remains in that block. It is destroyed when control leaves that block. Note that irrespective of the storage class used, the variable names must be unique within a block. Thus, we cannot redefine a variable within the same block with a different type and/or storage class. However, it is possible to reuse that variable name for other variables of any data type and/or storage class defined within other blocks including the contained blocks. When we access such a variable from within a block, the local variables (i. e., the variables defined in that block) are given preference. However, if the accessed variable is not defined in that block, variable access refers to the definition in the nearest outer block in which this block is contained. To understand this concept clearly, study the example given below.

int main()

{

    int x = 1;

    clrscr();

    printf(“%d “, x);               /* prints 1 */

     {

         printf(“%d “, x);          /* prints 1 */

           {

                int x = 2;            /* variable name x reused */        

                printf(“%d “, x);  /* prints 2 */

           }

           printf(“%d “, x);       /* prints 1 */

      }

       printf(“%d “, x);          /* prints 1 */

       return 0;

}

The comments after the printf statements specify the values printed by these statements. The code is easy to understand and its output is given below.

1 1 2 1 1

Now consider another example given below

void show_result(int marks)

{

       char result[10];

       if (marks >= 40)

       {

          char result[] = “Pass”;

       }

       else {

                    char result[] = “Fail”;

                    printf(“Result: %s”, result);

             }

             printf(“Result: %s”, result);

}

In this function, the variable result is first declared as a char array. Then this variable is reused to define and initialize two char arrays (with values “Pass” and “Fail”)within the if block and else block of an if-else statement. Depending on the outcome of the condition in the if statement, one of these arrays will be created. However, it will be destroyed as soon as control leaves that block. Thus, the printf statement will print the value of the result array defined in the beginning of this function. As this is an automatic array, its elements are not initialized with any specific value and thus have garbage values. When this function was called in Code::Blocks (with value of marks as 50), the output was displayed as shown below.

Register Storage Class

CPU registers are much faster than memory. Thus, if we store frequently used variables in CPU registers, the program will run faster. We can request the C compiler to store one or more variables in CPU registers by specifying the register storage class when these variables are defined. However, note that a CPU has a limited number of registers. Hence, it may not be possible for the compiler to honor all requests for allocation of CPU registers. If the compiler is not in a position to allocate a CPU register for a requested variable, that variable is stored in memory and is treated as an automatic variable.

Apart from the storage location, register variables are similar to automatic variables. Thus, they have scope local to the block in which they are defined, they are destroyed when control leaves that block and the compiler does not initialize them with any specific values (they have garbage values), if we do not explicitly initialize them.

The register storage class should be used for frequently used variables, e. g., control variables in loops. Consider the example given below.

int sum(int n)

{

    register int i, sum;

    sum = 0;

    for(i = 1; i <= n; i++)

        sum += i·;

        return sum;

}

This code segment defines variables i as well as sum as register variables in an attempt to speed up program execution.

Note that whether a variable will be stored in a CPU register or not depends, besides the availability of a CPU register, on the possibility of accommodating that variable in the CPU register. As modem CPUs have 64 bit registers, it is possible to allocate CPU registers for variables of basic data types (char, int, float and double) as well as pointer variables. Remember that we should not request a register storage class for bigger data objects such as arrays or large structures. However, if we do so, the compiler will ignore the request and treat those variables as automatic variables, as mentioned earlier:

Static Storage Class

Like automatic variables, static variables are also stored in memory and have local scope. However, they differ in two respects, lifetime and default initial values.

Static variables come into existence when the execution of the block in which they are defined begins for the first time and they are not destroyed when control leaves that block. Thus, they live till the end of program execution. Note that the values assigned to these variables are available the next time that block is executed. Thus, static variables can be used to remember data values in a function across function calls.

If we do not explicitly initialize a static variable when it is defined, the compiler initializes it with the default initial value, which is zero for arithmetic types and NULL for pointers. This initialization is done only once, the first time control reaches that block. Initialization is not done in subsequent executions of that block.

To further understand the concept of static variables, consider the program given below.

#include <stdio.h>

void func(void)

int main ()

{

   func () ;

   func ();

   func ();

   return 0;

}

void func (void)

{

    static int x = 100;

    printf(“%d “, x++);

}

In this example, the function func is called three times from the main function. This function defines a static variable x with initial value 100. This value is printed and then incremented in a printf statement.

The first time the function func is called, variable x is initialized to 100. The printf statement prints this value and increments it to l 01. When control leaves function func,x isnot destroyed as it is a static variable and its value is preserved for use in subsequent calls to the function.

When the function func is called a second time, x is not initialized again. Thus, the printf statement prints the value of x (101) and increments it to 102. Finally, the third call to function func prints the value 102 (and increments it to 103). The output of the program is given below.

101 102 103

What would program output be if we declare variable x in function func as shown below?

static int x;

External Storage Class

External variables, as the name indicates, are defined outside any function. These variables are similar to static variables in terms of storage location, lifetime and default initial values.

External variables are stored in memory. They come to existence when program execution begins and live till the end of program execution. Also, the compiler initializes them with default initial values (0 for arithmetic types and NULL for pointers), if they are not explicitly initialized.

However, unlike all other variables (automatic, register and static which have local scope), external variables have global scope. Hence, these variables are also called global variables. They can be accessed in all parts of the program including all the functions in the same program file as well as other program files in a multi-file C program. Thus, they provide an easy mechanism to share data between different functions without explicitly passing them around. This is particularly useful if a large number of variables are shared by multiple functions. It is a convention to define the external variables at the beginning of a program file, as illustrated below.

#include <stdio.h>

int x = 10;

int y;

void func(void);

int main()

{

    printf(“%d %d “, x, y);

    x = 100, y = 200;

    func ();

    printf(“%d %d “, x, y);

    return 0;

}

void func(void)

{

             printf (“%d %d “, x, y);      /* global x and y */

            {

                 int x = 5, y = 2;

                 printf(“%d %d “, x , y); /*local x and y */

            }

                 x = 50, y = 60;

}

In this program, the variables x and y are external variables initialized to 10 and 0 (default value), respectively. These variables are global and are accessible in both the functions, main and func. The main function first prints their values and assigns new values to them (100 and 200). The func function is then called which first prints these values. A block in the func function reuses these variable names to define local variables x and y with values 5 and 2, respectively, and prints them. As local variables get preference over global variables, the values are printed as 5 and 2. The func function then assigns new values (50 and 60) to variables x and y (global variables) outside the block. Finally, control returns to the main function where the values of x and y (global variables) are printed again as 50 and 60. The program output is given below.

10 0 100 200 5 2 50 60

You have probably noticed that the extern keyword was not used in the previous program.  This keyword declares that a variable is external, i. e., its definition is provided in some other part of the program. By default, an external variable is accessible from the point of its definition till the end of that file. However, if we wish to access an external variable in a file before it is declared, we need to use the extern declaration, as illustrated below.

#include <stdio.h>

void func(void);

int main()

{

      extern int x;             /* declaration */

      printf(“%d “, x);

      x = 20;

      func ();

      printf(“%d “, x);

      return 0;

}

      int x = 10;      /* definition */

      void func(void)

      {

               printf(“%d “, x);

               x = 30;

       }

In this example, variable x is defined as an external variable with value 10 after the main function. Thus, it is not accessible in the main function and an extern declaration is required to enable this. However, x is accessible from function func as it is defined before that function. Thus, explicit declaration of variable x is not required in function func. When this program is executed, the external variable x is first initialized to 10. The main function prints its value and assigns a new value (20) to it. Then it calls function func where this value of x is printed; new value (30) is then assigned. Control then returns to the main function where this value of x is printed again. Thus, the output of the program is

10 20 30

Note that the extern declaration of a variable should match with its definition with regard to data type, type modifier and storage class; otherwise, the compiler will report an error. The extern declaration does not create variable and it can be specified any number of times, even within the same scope.

Finally note that the C language allows a program to be split into multiple program files (. c files) and header files (. h files). To access an external variable defined in another file, we need to declare that variable using an extern declaration in files where that variable is to be accessed. Consider the program given below.

main. c file:                                                      func. c file:

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

                                                                             extern int x;

int x = 10;                                                         void funcl (void)

int y = 20;                                                       {

                                                                               printf(“%d “, x};

int main ()                                                              x = 100;

{                                                                         }

   funcl();                                                           void func2 (void)

   func2 ();                                                         {

   printf(“%d %d ” ,x,y);                                          extern int x, y;

   return 0;                                                                  printf(“%d %d “,x,y);                               

}                                                                                     x = 200, y = 300;

                                                                             }

                                                                                                      

The main. c file defines two external variables, x and y, with initial values 10 and 20, respectively. The main function in this file calls two functions, funcl and func2, which are defined in another file, func. c and then prints the values of x and y.

The func. c file declares x as an external variable at the beginning. Thus, x in this file refers to variable x defined in the main. c file. The function func 1 prints the value of x (10) and assigns it a new value (100). The function func2 declares x and y as external variables. Thus, these variables refer to variables x and y defined in the main. c file. The function func2 then prints the values of x (100) and y (20) and then assigns them new values (200 and 300, respectively). These modified values are printed by the printf statement in the main function. The program output is given below.

10 100 20 200 300

Note that variable x is declared twice in the func. c file. An external variable can be declared any number of times. However, it can be defined only once.

const Parameters in C

By Dinesh Thakur

Sometimes we may want that a function should not modify the value of a parameter passed to it, either directly within that function or indirectly in some other function called form it. This can be achieved using const parameters. Consider, for example, the function given below to calculate the sum of the first n integer numbers. [Read more…] about const Parameters in C

C Program Function Parameter as a Loop Variable

By Dinesh Thakur

We know that the C language uses the call by value mechanism to pass parameters and that a function parameter is a copy of the argument specified in the function call.

 

Thus, a function parameter can be modified without affecting the corresponding argument in the calling function. This fact can often be used effectively to save some memory. Consider function fact given below to determine the factorial of an integer number.

#include <stdio.h>

#include <conio.h>

void main ()

{

           int a;

           long f,fact();

           clrscr();

           printf (“\n Enter a Number : “);

           scanf (“%d”,&a);

           f=fact(a);

           printf (“\n The Factorial of %d is : %ld”,a,f);

           getch();

}

       long int fact(int n)

{

     int i;

     int fact = 1;

     for (i = n; i > 1; i–)

     fact *= i;

     return fact;

}

       Function Parameter as a Loop Variable

C Program Tower of Hanoi

By Dinesh Thakur

The Tower of Hanoi problem consists of three poles, left, middle, and right. One of the poles (say, the left) contains n disks of different sizes placed on each other, as shown in Fig. The objective of the problem is to transfer all the disks from the left pole to right pole such that only one disk can be moved at a time (to any pole) and a larger  disk cannot be placed on top of a smaller disk. [Read more…] about C Program Tower of Hanoi

C Program Calculate area and circumference of a circle using functions

By Dinesh Thakur

Let us write a program to calculate the area and circumference of a circle using user-defined functions. A function area_circum to accept the radius of a circle and print its area and circumference is given in Example. However, rather than printing the results in a function, it is good practice to return the results to the calling function, where they can be printed or used for further processing, if required. Hence, let us return the results (area and circumference) to the calling function. [Read more…] about C Program Calculate area and circumference of a circle using functions

Function Declaration or Prototype in C

By Dinesh Thakur

Before a function is called in a program, the system should know where to look for the function definition. In case of functions belonging to C standard library we include the relevant header files in which the function is defined. This is done above the main() function. In case of user-defined functions, a function may be defined above or below the main function, because, a function cannot be defined inside another function. If a function is defined above the main function, there is no need of a separate declaration of function. However, if the function is defined below the main function, it is a good programming practice to declare the functions being used above the main. A function declaration may be done by the function header or by its prototype.

If a function call precedes its definition in a program, we should declare the function before the call. A function declaration takes the following general form:

ret_ type func_ name ( param_type_list ) ;

For example, the prototypes of the three functions Area_rect, Area_ circle and Display may be written as.

  int Area_rect(int, int);

  double Area_circle( float);

  void Display ();

where func _name is the name of the function, ret_type is the type of the return value and param_type_list is a comma-separated list of function parameter types. Note that this format is similar to the function definition except that the parameter declaration list is replaced by the parameter type list and the function body is replaced by a semicolon. Also note that formal parameter names may be included in a function declaration and are treated as comments. They may be replaced with other names as well. Thus, to include a function declaration in a program, we can simply copy the first line of the function definition (and insert a semicolon after it).

Function declarations are usually written at the beginning of a program, before the main function. Such declarations outside any function are called global declarations. A function may also be declared within the function from which it is called. The problem with such a local declaration is that its scope is restricted to the function in which it is declared, i. e., it is available only within that function. Thus, if this locally declared function is also called from some other function, we must provide its declaration in that function as well.

Although a program can contain only one definition of a function, there is no restriction on the number of declarations. A function may be declared more than once within the same scope. However, note that each declaration must be consistent with its definition with regard to the number of parameters, their types and the return type.

A function declaration provides valuable information (function name, number and type of parameters and return type) to the compiler. The compiler uses this information to ensure that the function call is consistent with its definition. Thus, the compiler can check that the number of arguments in a function call and the types of arguments are as per the requirements of the function and that the function call is consistent with respect to the type of the value returned by the function. The compiler can report errors or warnings when a function call is not consistent with its definition. Note that if a function definition precedes its calls, the compiler obtains the necessary information from the function definition itself thereby eliminating the need for a function declaration. However, this is not good programming practice.

If the type of an argument in a function call is different from the type of the corresponding parameter in function definition, automatic conversion is applied if possible, to convert the argument to the type of the parameter. If automatic conversion is not possible, the compiler will report an error. Also note that if a function declaration or definition is not available to a compiler before the function call is encountered, the compiler can neither perform such automatic conversions nor it can report any errors if such conversions are not possible. The compiler may, however, give a warning that a function call is encountered without a function prototype. The compiler assumes that this function returns a value of type int. Thus, if the function actually returns a different type of value, the compiler can report an error or warning.

Illustrates the declaration of prototypes

#include<stdio.h> 
float Volume(float,float,float); //function prototype
float Surface_area (float,float,float); //function prototype
void main()
{
   float x,y,z, V, S ;
   clrscr();
   printf("Write three dimensions of a cubical object: ");
   scanf ("%f%f%f",&x, &y, &z);
   V = Volume(x,y,z);
   S = Surface_area(x,y,z);
   printf("Volume = %f,\t Surface area= %f\n", V, S);
}
  float Volume ( float a,float b,float c) /*function definition*/
   {return a*b*c;}
  float Surface_area( float a, float b, float c) //Definition
{
   return 2*( a*b +b*c+c*a);
}

The expected output of the above program is written as follows:

  

C Program function to return the maximum of three numbers

By Dinesh Thakur

It accepts three parameters  x,y, and z, each of type double and returns a value of type double. [Read more…] about C Program function to return the maximum of three numbers

return Statement in C Language

By Dinesh Thakur

The return statement is used to terminate the execution of a function and transfer program control back to the calling function. In addition, it can specify a value to be returned by the function. A function may contain one or more return statements. The general format of the return statement is given below. [Read more…] about return Statement in C Language

C Program Function to Print a Line of a given character

By Dinesh Thakur

We may often require a horizontal line of a dash, underline or some other character to be printed, particularly when printing results in a tabular format. Consider a situation in which we require a line containing a fixed number of a specific character (e.g., 65 dash characters) to be printed several times.

 

The function print_65_dash_line does not have any parameter and it does not return any value. The body of the function first declares index variable i. Then it prints a line containing 65 dashes followed by a newline character. Although we could have used a single printf statement to print the desired line of dashes, the for loop allows us to quickly change the line length. However, if we require lines of different lengths to be printed, it is better to pass the line length as a parameter to this function.

We can define a function to print such a line, as shown below:

#include <stdio.h>

void main ()

{

      char i;

      clrscr();

      printf(“Print a Line of a given character:\n”);

      i=print_65_dash_line();

      printf(“%c”,i);

      getch();

}

print_65_dash_line()

{

      int i;

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

           putchar ( ‘-‘ ) ;

               putchar (‘\n’) ;

               return 0;

} 

        C Program Function to Print a Line of a given character

User-defined Functions in C

By Dinesh Thakur

C allows programmers to define their own functions. Such functions are called user defined functions. In fact, the main function that must be present in every C program is a user-defined function. A programmer may define additional functions in the following situations:

1. The required functionality is not available as a library function either in the standard C library or in the additional libraries supplied with the C compiler.

2. Some functionality or code is repeated in a program with little or no modification.

3. An existing function is quite large. It is a good idea to divide such functions, if possible, into smaller ones.

Function Definition

The general format to define a function is as follows:

ret_type func_ name ( param _list )

{

    declarations

    executable_statements

}

where funv_ name is the name of the function being defined, ret_type is the type of value returned by the function (also called function type) and param_list is a comma-separated list of function parameters. For each parameter, we must specify the type of the parameter followed by its name. Thus, the param _list takes the following form:

type1 param1, type2 param2, … , type_n param_n

where type I, type2, … are the types of parameters paraml, param2, … , respectively. Note that the rules for naming these parameters (as well as the function name) are the same as those for a variable name and that the type has to be specified separately for each parameter, even if consecutive formal parameters in param _list are of the same type.

A function may not have any parameters. This is indicated by using the keyword void in place of param _list in the function definition. However, void may also be omitted in such cases.

ret_type is the type of the value returned by a function. A function can return only one value or none at all. If a function does not return a value, it is indicated by writing the keyword void in place of ret_type. Also note that ret_type may be omitted, in which case, the function is assumed to return a value of type int.

The body of a function consists of declarations followed by executable statements enclosed within braces ‘{‘ and ‘}’. The entities declared within the function body, which are usually variables, are local to the function being defined, i. e., they are accessible only within the function body and not outside it. We can declare a local variable (or some other entity) with the same name as that of a function. The formal parameters of a function are treated as local variables declared in the beginning of the function body.

The executable statements in the definition of a function can be one or more valid C statements. When a function is called, these statements are executed until a return statement is encountered or all the executable statements are executed.

Advantages of Functions in C

By Dinesh Thakur

Recall that a function call takes the form [Read more…] about Advantages of Functions in C

C Program Prints Prime Numbers in a given range m to n

By Dinesh Thakur

The outer for loop is set up to process each number in the given range. Each number is tested within this loop using the simplified code. The break statement’s execution causes the inner for loop to terminate as it is the nearest loop enclosing the break statement. If the inner for loop is entirely executed, i. e., if condition d == num is true, num is printed as a prime number. [Read more…] about C Program Prints Prime Numbers in a given range m to n

break Statement in C Language

By Dinesh Thakur

We have seen that a break statement is usually used in a switch statement after the statements in each case. The execution of such a break statement causes the execution of the switch statement to be terminated and the control to be transferred to the statement following the switch statement. [Read more…] about break Statement in C Language

C Program print a given integer number in words

By Dinesh Thakur

Consider that we wish to print a given positive integer number in words, as a sequence of digit strings. For example, number 123 should be printed as One Two Three. This might be required in financial applications, for example, to print the cheque amount in words. [Read more…] about C Program print a given integer number in words

C Program Print Pythagorean triplets

By Dinesh Thakur

Three positive integer numbers a, band c, such that a<b<c form a Pythagorean triplet if c2= a2 +b2 , i. e,, a, b and c form the sides of a right-angled triangle. To select the values of a and b such that a < b and a, b < max, we can use nested for loops as shown below: [Read more…] about C Program Print Pythagorean triplets

C Program Prime factors of a given number

By Dinesh Thakur

As the name indicates, the prime factors of a given number are its factors that are also prime numbers, e.g., prime factors of 30 are 2, 3 and 5 but not 1, 6, 10, 15 and 30. One or more prime factors of a given number may repeat, e. g., prime factors of 120 are 2, 2, 2, 3 and 5. [Read more…] about C Program Prime factors of a given number

C Program Sum of digits of number repeatedly to obtain a single-digit number

By Dinesh Thakur

The program segment given below determines the sum of digits of a given number repeatedly until a single digit number is obtained. For example, 5985 => 27 => 9, where symbol => indicates a digit sum operation. Thus, if digit sum exceeds 9, it is used as a number for subsequent digit sum operations. [Read more…] about C Program Sum of digits of number repeatedly to obtain a single-digit number

Nested Loops in C

By Dinesh Thakur

The C language provides three loops (for,while and do …while). As contained statement in the body of the loop can be any valid C statement, we can obtain several nested-loop structures by replacing this statement with another loop statement. Thus, if we replace the statement in a for loop with another for loop, we will get a two-level nested for loop as [Read more…] about Nested Loops in C

C Program Data entry Validation

By Dinesh Thakur

The program segment given below reads a number from the keyboard (in variable num of type float) and prints its square root. However, as the sqrt function requires a non-negative argument, the program uses a do ..while loop to read the data until valid data is entered. [Read more…] about C Program Data entry Validation

C Program Count Number of odd and even digits in a given integer number

By Dinesh Thakur

This program segment below uses a straight-forward approach to count the number of odd and even digits in a given integer number(num).

[Read more…] about C Program Count Number of odd and even digits in a given integer number

C Program Four digit special perfect square numbers

By Dinesh Thakur

The program segment given below prints four-digit special perfect square numbers in which the upper and lower two-digit numbers are perfect squares as well. [Read more…] about C Program Four digit special perfect square numbers

C Program Date is Valid or Not

By Dinesh Thakur

Let us use variables dd,mm and yy (all of type int)to represent the day, month and year in a given date. The given date is valid only if year (yy)is non-zero, month (mm)is in the range 1 to 12 and day of month (dd) is in the range 1 to mdays, the number of days in a given month mm. An algorithm to determine the validity of a given date is given below. [Read more…] about C Program Date is Valid or Not

C Program Print Odd Numbers in a given range m to n

By Dinesh Thakur

In this example, a for loop is set up with values of loop variable num from m to n. The if statement is executed for each value of num and if nums an odd number (num%2 equals 1), it is printed using the printf statement. The output of this code is given below for m = 20 and n = 40. [Read more…] about C Program Print Odd Numbers in a given range m to n

« Previous Page
Next Page »

Primary Sidebar

C Programming

C Programming Tutorials

  • C - History
  • C - Anatomy
  • C - Constants
  • C - Identifiers
  • C - Data Types
  • C - Libraries File
  • C - Header Files
  • C - Basic Language
  • C - Data Types Sizes
  • C - Header Files Importance
  • C - Escape Sequences
  • C - Main() Purpose
  • C - Program Procedure
  • C - Control Statements
  • C - Enumeration Constant
  • C - Add numbers
  • C - Return Statement
  • C - Avoid Goto
  • C - Command Line Arguments
  • C - Switch Case
  • C - Switch Case Limitations
  • C - getchar() and putchar()
  • C - Iteration Statements
  • C - Pass by Value and Reference
  • C - Structures and Unions
  • C - Structure
  • C - Dynamic Memory
  • C - Fgets and Fputs Functions
  • C - Gets() and Puts() Functions
  • C - Armstrong Number
  • C - Storage Classes
  • C - Fibonacci Series
  • C - Precision Setting
  • C - const Parameters

C - Variable & It's Type

  • C - Variables
  • C - Variable Lifetime
  • C - Static Variable
  • C - Register Variable
  • C - Global Variables
  • C - Auto Variables
  • C - Local Variables

C - Operator & Expressions

  • C - Operator
  • C - Boolean Operators
  • C - Bitwise Operator
  • C - Arithmetic Operators
  • C - Modulus Operator
  • C - Ternary Operator
  • C - Expressions
  • C - Arithmetic Expressions

C - Array

  • C - Arrays
  • C - Array Types
  • C - Array Characteristics
  • C - Static Arrays
  • C - Global Arrays
  • C - 3D Arrays
  • C - Dynamic Arrays
  • C - Pointer to 3D Arrays
  • C - Array Elements Hold
  • C - Arrays as Function Parameters
  • C - Accessing Matrix Elements
  • C - File Handling
  • C - Matrix Multiplication
  • C - Dynamic Memory Allocation

C - Searching & Sorting

  • C - Data Structures
  • C - Linear Search
  • C - Bubble Sort
  • C - Merge Sort
  • C - Linked List
  • C - Insertion Sort
  • C - Binary Search
  • C - Selection Sort
  • C - Quick Sort

C - Functions

  • C - Functions
  • C - Functions Advantages
  • C - Void Functions
  • C - Function Call
  • C - Default Return Value
  • C - String functions

C - Pointer

  • C - Pointers
  • C - Type Casting Of Pointers
  • C - Pointer Advantages
  • C - Pointers Initialization
  • C - Vectors and Pointers

C - Differences

  • C - C Vs C++
  • C - Formal Args. Vs Actual Args.
  • C - Keywords Vs Identifiers
  • C - Strings Vs Character Arrays
  • C - Address Vs Dereference Operator
  • C - Goto Vs longjmp
  • C - Declaring Vs Defining Variable
  • C - String Vs Array
  • C - Call by Value Vs Reference
  • C - Structure Vs Union
  • C - For Vs While loops
  • C - Compiler Vs Interpreter

C - Programs

  • C Program Standard Deviation
  • C Program Calculate Tax
  • C Program Sum Series
  • C Program Merge Arrays
  • C Program Euclid’s Algorithm
  • C Program Print Weekdays
  • C Program Sum of Digits
  • C Program Print a list
  • C Program Print Pythagorean
  • C Program Quiz program
  • C Program Display Table
  • C Program Print Comma-Separated
  • C Program Prints Prime Numbers
  • C Program for Print Integer
  • C Program Count Number
  • C Program Print Color Name
  • C Program Print Odd Numbers
  • C Program Calculate area
  • C Program for a Menu
  • C Program Add Two Vectors
  • C Program Array Addresses
  • C Program Division by Zero Error
  • C Program Compare two Dates
  • C Program Tower of Hanoi
  • C Program return 3 Numbers
  • C Program for Prime Numbers
  • C Program for Factorial
  • C Program for Palindrome

Other Links

  • C Programming - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW