C File Input-Output

Most of the programs we have seen so far involve static or dynamic memory. One of the features of C programming language is the ability to read and write files.

The information is written to operating system files in binary format and later retrieved in the memory buffer to be read or written. This is done with the help of file pointers and various C library functions.

Learn the basics of C programming before you begin.

File Operations in C

C language allows following file operations in broader sense.

  1. Create new file.
  2. Open existing file.
  3. Read from a file.
  4. Write to a file.
  5. Move to a specific location on file (seek).
  6. Close the File.

The library functions for file operations is stored in stdio.h header file.

See the following example,

Example Program – File Operations

"test.txt"
A Square has 4 equal sides, and a rectangle has 4 sides, but they are not equal.
The triangle has 3 angles and 3 sides.

We now write a program that will use – test.txt.

"Read_file.c"
#include <stdio.h>
int main()
{
     FILE  *file_pointer;
     char ch;
  
     /* use library function fopen() to open and existing file */
     file_pointer = fopen ("test.c", "r");
  
     while(1)
     {
          /*  read each character from file_pointer which is pointing to file - test.c */
          ch = fgetc(file_pointer);
       
          /*  EOF is a macro that signals end-of-file */
          if(ch == EOF)
          break;
          printf("%c", ch);
     }
  
     /* All the character has been read, close the file with library function - fclose() */
     fclose(file_pointer);
  
return 0;
}

Output:

Output-Reading a File
Output-Reading a File

FILE

It is a file control structure that store information about FILE. The description of FILE in Turbo C++ compiler is as follows.

typedef struct {
    short            level;
    unsigned         flags;          
    char             fd;
    unsigned char    hold;          
    short            bsize;          
    unsigned char    *buffer,*curp;
    unsigned         istemp;          
    short            token;
} FILE;

This is hidden from the programmer. The command

FILE *file_pointer;

creates a pointer of type FILE with the ability to hold file information like size, mode of opening, location, etc. provided when the file was opened using fopen() command.

file_pointer = fopen("test.txt", "r");

fopen()

The function fopen() needs two arguments.

  1. file name
  2. opening mode

In the example above, the file name is test.txt and the opening mode is r which stands for read.

What does fopen() do ?

It does three tasks.

  1. Search for the file on the disk.
  2. If found, load the file in memory buffer.
  3. Set a character pointer that points to the first character of the file in buffer.

Since too many disk operations is costly for operating systems. A buffer is needed so that all operations are performed in the buffer and later committed to the file on the disk.

Buffer
Figure 1- Buffer

fgetc()

The file in open in buffer and ready for file operations. The file\_ pointer has a character pointer that points to first character of the file in buffer.

The function fgetc() starts reading each character one at a time and assign to character variable ch, which is printed as output.

ch = fgetc(file_pointer);

fclose()

Once the EOF is reached and file operation is completed, all the reference to the file and file\_ pointer must be removed from buffer. This is done using fclose();.

fclose(file_pointer);

Any further operation required; you have to open the file again using fopen() function.

post

How to Install Turbo C++ Compiler

C compiler is the most important requirement to practice writing programs. In this article, we walk you through the process of installing Turbo C++ 3.2 compiler. Before installation you must complete the following requirements.

Operating System: Windows 7 and above, including Windows 10.
.Net Framework 4.5 : Only for Windows 7, Vista and XP

Steps to Install Turbo C++ 3.2

Follow these steps to do a fresh installation of  Turbo C++ .

Step 1:  Download Turbo C++  3.2.

Step 2:  Extract “Turbo C++ 3.2 zip” file in the same directory.

Extract Turbo C++
Figure 1 – Extract Turbo C++

Step 3: Run “Setup.exe” file and follow the instructions. Make sure that you run setup as administrator.

Run Setup as Administrator
Figure 2 – Run Setup as Administrator

Step 4: You will get the Install Shield Wizard to Turbo C++. Click Next to continue.

Install Shield Wizard
Figure 3 – Install Shield Wizard

Step 5:  You will receive the License Agreement windows, accept the License Agreement and click Next to continue.

Accept License Agreement
Figure 4 – Accept License Agreement

Step 6:  Setup is now ready to install Turbo C++ compiler.

Ready to Install
Figure 5 – Ready to Install

Step 7: Click Install to start the installation.

Setup Continue to Install
Figure 6 – Setup Continue to Install

Step 8: After few minutes the setup completes the installation successfully.

Setup Completed
Figure 7 – Setup Completed

You can now click on Finish and launch the program. The initial screen for Turbo C++ 3.2 look like following.

Turbo C++ Initial Screen
Figure 8 – Turbo C++ Initial Screen

You can now click on “Start Turbo C++” and continue writing programs.

post

C Library String Functions

You can access the builtin C library functions through header files. The string related functions are located in String.h file.

Each function listed below has a specific purpose.

FunctionDescription
strlen()To find the length of a string.
strlwr()Converts a string to lowercase.
strupr()Converts a string to uppercase.
strcat()Add one string to another to make a bigger string.
strncat()Add n character of a string to another string
strcpy()Copies a string to another string replaces any existing.
strcmp()Compare two strings.
strncpy()Copies first n characters of two strings.
strncmp()Compares only first n characters with another string.
stricmp()Compare two strings, disregards case.
strcmpi()Same as stricmp()
strncmp()Compares first n characters of two strings.
strnicmp()Compares first n characters of two strings, disregards case
strdup()Duplicate a string.
strchr()Finds first occurrence of a given character in a string.
strrchr()Finds last occurrence of a given character in a string.
strstr()Finds first occurrence of a given string in another string.
strset()Changes all characters of a string to given character.
strnset()Changes first n char of a string to given character.
strrev()Reverse a given string.

From the above table, strlen(), strcpy(), strcmp() and strcat() are the most frequently used functions.

C Library String Functions Example

You will write a program that implement these 4 built-in functions.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
    char str[] = "Chile";
    char str2[] = "India";
    int len1;
    int len2;
    int boo;
  
/* Implement strlen() function */
    len1 = strlen(str);
    len2 = strlen(str2);
    printf("Length of First String = %d\n",len1);
    printf("Length of Second String = %d\n",len2);
    boo = strcmp(str2,str);
  
    if(boo > 0)
    {
        printf("String Mismatch\n");
    }
    else
    {
        printf("String Matched\n");
    }
  
    strcat(str,str2);
    printf("string cat = %s\n",str);
    strcpy(str,str2);
    printf("string copy = %s\n",str);
  
system("PAUSE"); 
return 0;
}

Output

Your site doesn’t include support for the CodeMirror Blocks block. You can try installing the block, convert it to a Custom HTML block, or remove it entirely.

Install CodeMirror Blocks
Keep as HTML
Length of First String = 5
Length of Second String = 5
String Mismatch
string cat = ChileIndia
string copy = India
Press any key to continue . . . 
post

C Strings And Pointers

In the previous lesson, you learned about C string and how they are important to manipulate text in a C program. In this article, you will learn how strings can be accessed and used with pointers.

Learn C programming basics and pointer concepts before you begin with this lesson. If you are familiar with them, skip and continue reading the next section.

  1. C Program Structure.
  2. C Printing Outputs.
  3. C Reading Input Values.
  4. C Strings.
  5. C Pointers.

Pointer is a special variable that can store the value of string constant, just like character array. But, there are some advantages of using pointers.

Let us see the initialization of string constant.

char manager[20] = "David";
char *p = "Harry";

Both methods is simple and straightforward, but you cannot assign another string to a character array. It is only possible with pointers.

For example,

char manager[20] = "Bruce";
char supervisor[20];
char *p = "Mary";
char *s;
supervisor[20] = manager[20]; /* will give error */
*s = *p;                      /* No error */
*s = "Tang";               /* is valid */
supervisor[20]= "George";  /* Not valid */

Accessing Characters in a String

The most popular method to access individual characters from a string is treating the string like an array and loop through each character.

For example,

int i = 0;
while(name[i] != '\0'){
    printf("%c", name[i]);
}
getch();
return 0;
}

You can do the same with pointers. Consider the pointer version of above.

char *p = "elephant";
int i;
while (*p!= '\0')
{
  printf("%c",*p);
  p++;
}

The output of both is going to be same.

String and Pointer Example Program

The following program does all the string manipulation we discussed in the article.

#include <stdio.h>
#include <stdlib.h>
int main()
{
    char fruit[20] = "APPLE";
    char *p = "ELEPHANT";
    char *s;
    int i;
    s = p;
  
    while (*s!= '\0')
    {
         printf("%c",*s);
         s++;
    }
  
    printf("\n\n");
    /* Standard Array Technique */
    i = 0;
    while( fruit[i] != '\0')
    {
         printf("%c", fruit[i]);
         i++;
    }
    printf("\n\n");
  
system("PAUSE"); 
return 0;
}

Output

ELEPHANT
APPLE 
Press any key to continue . . . 
post

C Strings

A string constant is an array of characters just like an array of integers. It helps to work with words and sentences in C programming. Yet, an array of integers and character array are not the same as strings.

Learn basic of C programming before you begin with strings. If you are familiar with the C basics continue reading.

  1. C Program Structure.
  2. C Printing Output.
  3. C Reading Input Values.
  4. C Data Types.
  5. C Arrays.

What is a String constant?

A string constant is a one-dimensional array of characters with is terminated by \backslash \emptyset, also called a null character.

char firstname[] = { 'P', 'E', 'T', 'E', 'R', '\0'};

The value of a Null character is \backslash \emptyset and each character in the string constant occupy 1 \hspace{2px}byte of memory. The syntax to initialize a string is very simple.

char name[] = "Rajesh";
/*where
  char = data type of string.
  name[]    = indicates that it is a character array or a string.
  "   "   =  double quotes show that the value is a string.
  Rajesh     = actual string value.
  */

The C compiler inserts a \backslash \emptyset automatically, so there is no need to specify null for every string that you create.

String Constant Memory Representation
Figure 1 – String Constant Memory Representation

Reading and Printing String Constant

Reading input and writing out is an important part of the C programming language. To read a string constant use following syntax.

char name[10];
scanf("%s", &name)

You already know that name[10] is declared as a string of type char. The scanf() is a builtin function that read inputs of various data types. To tell scanf() that the input is a string use the modifier “%s”. But, scanf() can only read a single word like “Rajesh”, and not “Rajesh Kumar”.

To read a multi-word string use gets() or do following.

scanf("%[^\n]s", name);

The modifier is used for printing strings. For example,

printf("%s", name);

String Example program

It is time to implement everything you learned so far about strings. In this C program,  you will perform two tasks.

  1. read and print a single word string.
  2. read and print a multi-word string.

Program Code

#include <stdio.h>
#include <string.h>
int main()
{
char input_name[35];
int choice;
/* Menu */
printf("Menu\n\n");
printf("1. Read Single Word\n");
printf("2. Read Multi-Word String\n");
printf("\n\n Enter your Choice:");
scanf("%d",&choice);
switch(choice)
{
case 1: 
    system("cls");
    printf("Enter Single Word:");
    scanf("%s", &input_name);
    printf("%s", input_name);
    break;
case 1:
    system("cls");
    printf("Enter Multi-Word:");
    scanf("%[^\n]s", &input_name);
    printf("%s", input_name);
    break;
}
system("pause");
return 0;
}

Output

Menu
1. Read Single Word
2. Read Multi-Word String
 Enter your Choice:1
Enter Single Word String:Paris
Paris
Press any key to continue . . . 
post

C Assignment Operators

The assignment operators assign values to variables. Once values are assigned the variables are evaluated in expressions and return a single value.

There are three types of assignments as shown below.

1. Variable = Value( e.g., a = 4)
2. Variable = Expression( e.g., a = 3 + b)
3. Variable = Variable <Operator> Value (e.g., a = a + 3 or a += 3)

You can see from the above examples, that there is a left value(L-value) and (R-value). This assignment has a right to left associativity. In other words, right value(L-value) must be unambiguous or known, otherwise assignment will not work.

Precedence of operator

Every operator has a precedence in operators hierarchy, and it is executed in that order in an expression. The assignment operators have the least preference, so it executed last.

How many types of assignment operators

Let’s see how many assignment operators available to us.

OperatorExampleAssociativity
=A = 10 or B = CRight to Left
+=A += 10Right to Left
-=A -= 100Right to Left
/=A /= 12Right to Left
*=A *= 10Right to Left
%=A %= 5Right to Left
&=A &= 10Right to Left
|=A |= 10Right to Left
^=A ^= 4Right to Left
>>=A >>= 4Right to Left
<<=A <<= 3Right to Left

Example Program

This is an example program to demonstrate the effect of each assignment operator. You can run this program in any standard C compiler and it will work.

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main()
{
    int a,b,c,d;
/* simple assignment */
    a = 1000;
    b = 400;
    c = 120;
    printf("\n\n\n\n\n");
    printf("\t\t\ta:=%d\n",a);
    printf("\t\t\tb:=%d\n",b);
    printf("\t\t\tc:=%d\n",c);
/* assignment with arithmetic operators */
    a += b;
    b -= c;
    printf("\t\t\ta += b:=%d\n",a);
    printf("\t\t\tb -= c:=%d\n",b);
    a *= b;
    b /= c;
    printf("\t\t\ta *= b:=%d\n",a);
    printf("\t\t\tb /= c:=%d\n",b);
    a %= b;
    b ^= c;
    printf("\t\t\ta MOD= b:=%d\n",a);
    printf("\t\t\tb ^= c:=%d\n",b);
    a |= b;
    b &= c;
    printf("\t\t\ta |= b:=%d\n",a);
    printf("\t\t\tb &= c:=%d\n",b);
    a >>= 1;
    b <<= 2; printf("\t\t\ta >>= b:=%d\n",a);
    printf("\t\t\tb <<= c:=%d\n",b);
    getch();
    return 0;
}

Output – C Assignment Operators

The output of the above program is given below. Throughout the program, the value of variables a, b and c changes several times.

a:=1000
b:=100
c:=120
a += b:=1400
b -= c:=280
a *= b:=392000
b /= c:=2
a MOD= b:=0
b ^= c:=122
a |= b:=122
b &= c:=120
a >>= b:=120
b <<= c:=480

References

  • Balagurusamy, E. 2000. Programming in ANSI C. Tata McGraw-Hill Education,.
  • Brian W. Kernighan, Dennis M. Ritchie. 1988. C Programming Language, 2nd Edition. Prentice Hall.
  • Kanetkar, Yashavant. 20 November 2002. Let us C. Bpb Publications.
post

C Pointers

Pointer is a difficult concept for beginners of C programming language. Yet, you must master this concept because this is probably the most important concept in C language.

To learn pointers, you must learn – the pointer notations, the pointer syntax, and basic pointer concepts.

What is C pointer?

A normal variable store a value of a specific data type. However, a pointer is a special variable that holds memory address of another variable as a reference.

The main advantages of the pointer are

  • Saves memory
  • Faster Access to variables

Let us briefly explain each of the advantages.

Pointer saves memory

A pointer variable saves memory by creating a reference to a variable that has value, instead of creating a new value and storing it. Creating a reference to another variable is easy and C programming language allow more than one pointers to refer the same variable. This concept is known as “sharing”.

Faster Access to Variables

A pointer is faster that a regular variable when used as parameter to a function. There are two ways to pass parameters to a function – Call-by-value and Call-by-reference.

When a variable is passed as call-by-value method, a copy of the variable is passed as a parameter. This method is slower because it has to copy the variable.

C program for Call-by-Value

The call-by-reference method involves pointers which pass a reference to the original variable. Therefore, using pointer make the program faster.

C program for Call-by-Reference

C Pointer Operators

There are three kinds of operator used while working with pointers. Each of the operators is used in a specific way with pointers as well as other variables.

  • Assignment operator (=): It assigns values to variables.
  • Dereference operator (*): Pointers can access values of variables using this operator.
  • Address-Of operator (&): Unary operator to get access to memory address of a variable.

The operators are part of syntax to define and use pointers.

Syntax for Pointers

Most people do not understand pointers because they do not understand the syntax, what it means to declare pointers, what does it mean to reference a variable.

A visual representation should clear all doubts about the pointer. In this section, you will find syntax and a visual representation of syntax in the memory.

Pointer Declaration

To declare a pointer type variable, you need <data \hspace{3px}type>, followed by * asterisk symbol and a < user \hspace{3px}defined \hspace{3px}variable \hspace{3px}name>.

data_type* user_defined_name;

For example

int* p;
float* p;
Figure 1 - Pointer Declaration
Figure 1 – Pointer Declaration

Note that the asterisk symbol also means a dereferencing operator, so you must be careful in using it. In a different context, it means differently.

Pointer Initialization

A pointer starts out bad, but we need to point it to a variable. Never use a pointer that is not initialized, you will encounter an error. A pointer must always point to something before it is used.

The <user-defined \hspace{3px} pointer \hspace{3px} name> is assigned memory address of a target variable, see the figure below.

user_defined_pointer_name = &variable_name;

for example,

int num = 1100; /* Variable declaration and initialization is must */
int* p; 
p = #
Figure 2 - Pointer Initialization
Figure 2 – Pointer Initialization

The above figure shows that pointer variable p is assigned memory address of variable number. The address-of operator before variable num gives the memory address.

De-referencing pointer

De-referencing means getting access to the values of the variable pointer is pointing to. To do this, you need the dereferencing operator (*).

user_defined_variable_name = *pointer_name;
/* must assign the deference value to another variable or print it as output */

For example

int c, d;
c = 100;
int* p;
p = &c;
d = *p; /* now d is assigned the value of 100 using dereference operator */
Figure3 - De-referencing Pointer
Figure3 – De-referencing Pointer

Bad Pointer Concept

Every pointer that you declare starts out bad, but you must assign an address of a proper variable to the pointer. Until then, it remains a bad pointer. If you get errors in your program that use pointers, check for bad pointers first.

Bad Pointer
Bad Pointer

Different programming constructs behave differently to a bad pointer which points to nothing. Some just halt the program, and others crash the program itself like C/C++.

Null Pointer Concept

The NULL has a default value in every compiler which means No \hspace{2px}Value or sometimes a 0. When the pointer points to NULL then you can say that it points to nothing.

That is the reason, you must never de-reference a NULL pointer because technically, it points to nothing. Sometimes the NULL is assigned a value of 0 or any other constant values. But still, you cannot de-reference the NULL pointer.

Figure 4 - NULL Pointers
Figure 4 – NULL Pointers

Sharing Concept

You can assign one pointer to another pointer. Basically, this will give the second pointer the address of the original variable. See the figure below. In other words, they both share the same value and points to the same variable.

The assignment is quite straightforward, you assign one pointer to another directly like any other variable.

For example

q = p;
Figure 5 - Pointer Sharing
Figure 5 – Pointer Sharing

Example Program – Pointers

#include stdio.h
#include stdlib.h
int main()
{
    int num = 100;
    int* p;
    int* q;
    p = #
    q = p;
    printf("\n\n\n\n");
    printf("\t\t\tAddress of num= %u\n",&num);
    printf("\t\t\tAddress of p = %u\n",&p);
    printf("\t\t\tAddress stored at p = %u\n",p);
    printf("\t\t\tAddress of q = %u\n",&q);
    printf("\t\t\tValue of pointer p= %d\n",*p),
    printf("\t\t\tValue of pointer q = %d\n",*q);
    getch();
    return 0;
}

Output – Pointers

The output of the above program is given below. The program shows address of all the pointers: p, q and variable: num. It also uses the dereferencing operator to retrieve the values for pointers.

Address of num= 2686788
Address of p = 2686784
Address stored at p = 2686788
Address of q = 2686780
Value of pointer p= 100
Value of pointer q = 100

References

  • Balagurusamy, E. 2000. Programming in ANSI C. Tata McGraw-Hill Education,.
  • Brian W. Kernighan, Dennis M. Ritchie. 1988. C Programming Language, 2nd Edition. Prentice Hall.
post

C Functions

The C functions are another important feature in C language which helps in achieving a particular task. There is at least one function in a C program and it’s called the main() function. Without the main, there is no C program.

You cannot delete the main function, but you can delete other user-defined functions.

Why Functions ?

There are two reasons why function exists

  1. Code reuse
  2. Better program management because programming task can be broken and distributed to many functions.

You can repeat the same function by calling instead of writing the whole code again as many times as required in your C programs.

In structured programming practice, the program is broken into manageable tasks and later each task becomes a function with own codes. This is very easy to manage compared to writing whole code into the main() function itself.

Important parts of a C function

Three things are important about a C function

  1. Function declaration
  2. Function definition
  3. Function call

Function Declaration

You can declare function prototype using formal argument in two location in a C program.

  • Global declaration
  • Local declaration

Some declaration is done outside of main() function and those are called the globally declared variables or functions.

There is nothing special about them except that you can call them anywhere in your program or another file in the same program.

The scope of a local variable is inside of main or inside of a user-defined function. It means you cannot call the function outside or main() or another user-defined function.

Syntax: –

data_type function_name (
data_type variable1, 
data_type variable2, 
.
.
data_type variable n);

Example: –

int addition (int a, int b);

Function definition

The function definition is written outside of the main() function and it has all the statements to perform a specific task assigned to that function. You can declare local variables other than function parameters in a function definition.

Syntax:

data_type> function_name (data_type variable1…)
{
    Statement 1;
    Statement 2;
    .
    .
    Statement n;
}

Example:

int addition (int x, int y)
{
    int result = x + y;
    return result;
}

Function Call

You can call a function anywhere you want to use it depending on the scope of the function. You can call a function in three places

  • Inside another function
  • In main() program
  • Another file in the same program

Syntax:

function_name (variable_list);

Example:

addition (a, b);

Function Types

Earlier you learned about the function components inside a C program. There are different types of functions in C language. They are as follows

  1. Function without parameters
  2. Function with parameters
  3. Function with return
  4. Function without return

We will discuss each one of them in more details.

1. Functions without parameters

These type of functions do not take parameters to perform a computation.

Syntax:

data type function_name> ( );

Example:

int addition ( );

Example Program:

#include <stdio.h>
int main ()
{
    int result = 0;
    int addition (); /* function declaration */
    result = addition (); /* function call */
    printf ("Total= %d\n", result);
    getch ();
    return 0;
}
/* function definition */
int addition ()
{
    int a = 10;
    int b = 20;
    int total = 0;
    total = a + b;
    return output;
}

Output

Total = 30

2. Function with parameters

A function with parameter has two important parameter values depending on where it appears.

  1. Formal parameters
  2. Actual parameters

Formal Parameters

The formal parameter appears at the function declaration when you tell the kind of argument is used, especially the data type.

For example

void sum (int x, int y);

and

void sum (int, int);

They are the same type of declarations.

Actual Parameters

The actual parameters are only used in function calls. The things you must know about functions with parameters are

What kind of values they take?

  1. Integer
  2. Float or double
  3. Array
  4. String of characters
  5. Pointers
  6. Memory address

Syntax:

data_type function_name ( variable1 …);

Example:

void multiply (int a, int b);

How to supply parameters for these types of functions during function call?

There is two way to do this

  1. Call-by-Value
  2. Call-by-Reference

If you want to learn the how this works – check examples of both

  1. C program for Call-By-Value
  2. C program for Call-By-Reference

Examples of each input

In this section, we will discuss different calls to functions.

Integer value

Example:

int a, b;
a = b = 10;
/* function declaration */
int addition (int a, int b);
/* function call */
addition (a, b);
/* function definition */
int addition (int a, int b)
{
     do something;
}

Float or Double

Example:

float a, b;
a = b = 10.45;
/* function declaration */
float addition (int a, int b);
/* function call */
addition (a, b);
/* function definition */
float addition (float a, float b)
{
     do something;
}

Character value

Example:

char vote;
vote = 'Y';
/* function declaration */
void opinion (char vote);
/* function call */
opinion (vote);
/* function definition */
void opinion (char vote)
{
    do something;
}

Array value as parameter

An array is a contagious memory location that holds the same type of values, and a subscript helps in identifying the correct location of an array element. There are four notations to access the value from an array.

  1. Array [0] – refers to value of first element of array.
  2. Array – refers to memory address of first element of an array.
  3. *(array + 1) or *(1 + array) – refers to value of second element of an array.
  4. (array + 1) or (1 + array) – refers to memory address of second element of an array.

Note: The notation array [0] is same as i [array] because it means *(array + 1) or *(i + array) which called the commutative property.

When you use an array as a parameter to function.

  • The name of the array ‘array’ is a pointer to the first location in an array. It contains the memory address of the first element in the array.
  • The index or subscript is added to the memory address to find all elements of the array which is much more efficient than copying and passing an entire array and slowing the program.

Since it is not possible to send the entire array as a function argument by call-by-value method, passing a pointer to the first element or passing the address to the first element is easy. Later any element of the array can be accessed using subscript or index value.

Syntax:-

/* Function declaration */
int sum (int arr []);
/*Function call where arr points to the first element of the arr [] */
sum (arr)
/* Function definition */
int sum (int arr []) {
   do something;
}

Pointer value as parameter to function

Pointers do not hold any value, but points to the memory address of a variable that has a value.

There are some rules regarding the pointer.

  1. Pointer contains memory address of variable
  2. Pointer must point to something before you use them.
  3. Pointer is passed as parameter to a function using call-by-reference method.

Here is an example of pointer as function parameter.

Syntax:

/* Function declaration */
    int sum (int *p);
    int a = 10;
    p = &a;
/*Function call where 'p' points memory address of variable 'a' */
    sum (p);
/* Definition of the function*/
    int sum (int *p);
    {
        Do something;
    }

3. Function with return

After completing a specific task some function return a single value to the main function or to a function that called it.

A function with return requires two things.

  1. A return statement using keyword – return.
  2. The return type should match with the return type of function.

Syntax:

data_type function_name ( )
    {
        do something;
        return variable;
    }

Example:-

int sum (int a, int b)
    {
        int sum = 0;
        sum = a + b;
        return sum;
}

Notice that the sum is an integer and returns an integer value which matches with the int sum (int a, int b) function data type. If there is a mismatch you will get an error.

The main function always returns an integer by default, unless it’s specified not to return anything.

4. Function without return

There is a different class of functions that do not return any value. There are two requirements to define such a function.

  1. No return keyword required because function does not return any value.
  2. The function has no data type declared and instead the keyword ‘void’ is used to denote that the function does not return anything.
void sum (int a, int b)
{
    int sum = 0;
    sum = a + b;
    printf ("The sum is %d\n", sum);
}

Example Programs

References

  • Kanetkar, Yashavant. 20 November 2002. Let us C. Bpb Publications.
  • Linden, Peter Van der. 1994. Expert C Programming: Deep C Secrets. Upper Saddle River, NJ, USA: Prentice-Hall, Inc.
post

C Do-While Loop

The  C do-while loop is a different kind of loop which checks for exit conditions instead of entry condition. So it is very useful if you want a loop that keeps iterating until an exit criterion is met.

In a C program, the do-while loop will let you execute your code first and then checks for test condition if it is true to complete the execution.

If the test condition is false, the loop terminates and ignores any computation it may have performed previously.

Diagram for C Do-While Loop

The diagram below is used for a do-while loop when we create a flowchart for the C program.

Flowchart - C Do-While Loop
Figure 1 – Flowchart of C Do-While Loop

Example Program

#include <stdio.h>
int main ()
{
     int i, sum;
     /* Initialization of loop variable 'i' and sum */
     i = 0;
     sum = 0;
  
     /* Do-while loop body execution starts */
     do {
          sum = sum + i;
          /* Increment the loop */
          i++;
        } while (i < 10); /* check for exit condition */
  
    printf ("\n\n\n\n\n");
    printf ("\t\t\tThe sum is %d", sum);
  
getch ();
return 0;
}

Output – C Do-While Loop

sum is 45

Example Explained

In the above example, the do-while is initialized like other loop control structures – for and while loop. The variable sum is also initialized to 0.

i=0;
sum = 0;

Then, the do block is started with executing the following statement. Unlike other loops, the do-while does not check for entry conditions and directly execute the loop body.

sum = sum + i;

Next, the do-while loop is incremented for next iteration.

i++;

When all the tasks in a do block is completed the while condition checks for the Boolean value of the loop and decides to continue if true or terminates the do-while loop if false.

The program then prints the output, when the loop terminates.

printf ("The sum is %d", sum);

and the program ends.

References

  • Balagurusamy, E. 2000. Programming in ANSI C. Tata McGraw-Hill Education,.
  • Kanetkar, Yashavant. 20 November 2002. Let us C. Bpb Publications.
post

C For Loop

The for loop is a simpler version of the while loop that we learned in the previous lesson. It has the same components as while loop.

For Loop Basics

The for loop is more popular because all conditions for loop is declared in one place.

Before the for loop starts.

  1. Loop variable – It is used for initializing the loop, test condition for loop and increment or decrement the loop.
  2. Loop test condition– decide whether to execute the loop body or not.
  3. Loop body – contains statements required for performing a task inside the loop.

Logically while loop and for loop is same but the for loop is lot more simple than the while loop. This is because you can initialize, put test conditions and increment or decrement the for loop in a single line.

for( initialize counter; test condition; increment or decrement counter)
{
   Statements;
}

Flowchart Symbol of ‘for’ loop

The following symbol is used when we draw a flowchart for a C program that make use of a for loop.

Diagram - For Loop
Figure 1 – Diagram – For Loop

Example Program

In this example program, we are going to a number over and over for 10 times and print the result. This program uses a single for loop.

Your site doesn’t include support for the CodeMirror Blocks block. You can try installing the block, convert it to a Custom HTML block, or remove it entirely.

Install CodeMirror Blocks
Keep as HTML
/* C Program to add a number 10 times */
#include <stdio.h>
int main ()
{
     int number, total, i;
     number = 2;
     total = 0;
  
     for (i=0; i<10; i++)
     {
          total = total + number;
     }
  
     printf ("\n\n\n\n");
     printf ("\t\t\tThe total is %d", total);
  
getch ();
return 0;
}

Output

The total is 20

Example Explained

The program has three variables – loop variable i, \hspace{2px} number \hspace{2px} and \hspace{2px}  total and it uses one for loop to repeatedly add the number to sum until the loop terminates.

First the variables number and total are initialized.

total = 0;
number = 2;

The loop variable i is used inside the for loop to initialize the loop, define the test condition and increment the loop.

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

Since the loop starts at i = 0, it will run for 10 iteration because the 10th iteration it will terminate. At each iteration, the loop will check the test condition against the current value of i.

When the condition for loop is ‘true’, the loop body will execute and add value of variable number to total repeatedly.

total = total + number;

The loop adds the number 10 times and when i = 10, it terminates and prints the value of total as output.

printf ("\t\t\t\t The total is %d", total);

The program ends.

References

  • Balagurusamy, E. 2000. Programming in ANSI C. Tata McGraw-Hill Education,.
  • Kanetkar, Yashavant. 20 November 2002. Let us C. Bpb Publications.
post