Category Archives: C Tutorial

C Nested Switch Case Statement

C Nested Switch Case Statement

In C programming, when there is a switch case statement inside another switch case statement then it is known as a nested switch case statement.

It is possible to have a switch case statement as a part of another switch case statement.

Nested Switch Case Statement Syntax

Below is the general syntax of nested switch case statement in c programming:

Syntax:-

Nested Switch Case Statement Example

Below is a simple example to demonstrate the use of nested switch case statement in c programming:

Example:-

When we run the above C program, will see the following output –

Output:-

c-nested-switch-case-statement

C Switch Case Statement

In C programming, It evaluates an expression against multiple cases in order to identify the block of code to be executed. A switch case statement is a simplified form of the Nested if-else statement, it helps to avoid a long chain of if..else if..else statements.

Flow Diagram

c-switch-case-statement-flowchart

C Switch Case Statement Syntax

Below is the general syntax of switch case in c programming:

Syntax:-

Example of Switch Case

Below is a simple example to demonstrate the use of the present statement in c programming:

Example:-

In the above program, we have an integer variable dayOfWeek with an initial value of 5, and we pass this variable as an expression to the following switch statement, value of dayOfWeek is tested with multiple cases to identify the block of code to be executed. When we run the above C program, will see the following output –

Output:-

c-switch-case-statement

C Nested If Else Statement

C Nested If else statement

In C programming, when there is an if statement inside another if statement then it is known as a nested if-else statement. Nested if-else can also be simplified using C Switch Case Statement.

Nested If else statement Syntax

Below is the general syntax of nested if-else statements in c programming:

Syntax:-

Nested If else statement Example

Below is a simple example to demonstrate the use of a nested if-else statement in c programming:

Example:-

When we run the above c program, will see the following output –

Output:-

c-nested-if-else-statement

C if else if Statement

C if else if Statement

In C programming, the if-else if statement allows us to add an alternative set of test conditions in the if..else statement using else-if and single else statements for the if condition. In such way if..else.if statement is used to select one among several blocks of code to be executed.

C if..else..if Statement Flow Diagram

c-if-else-if-statement

c-if-else-if-statement

if else if Statement Syntax

Below is the general syntax of the if-else if statement in c programming:

Syntax:-

if-else if Statement Example

Below is a simple example to demonstrate the use of if-else if statement in c programming:

Example:-

Output:-

c-if-else-if-statement

C If Else Statement

C if-else Statement

The c if-else statement is an extended version of the If statement. When we want to execute a block of code when the if the condition is true and another block of code when the if the condition is false, In such a case we use the if-else statement. The statements inside the “if” body only execute if the given condition returns true. If the condition returns false then the statements inside the “else” body are executed.

But what if we want to do something else if the condition is false. Here comes the C else statement. We can use the else statement with the if statement to execute a block of code when the condition is false.

C If else Statement flowchart

dart-if-else-flowchart

if-else Statement Syntax

The general syntax of if-else statement is as follows:

Syntax:-

Working of if-else Statement

Here, the if statement evaluates the test condition inside the parenthesis (). The Condition is a Boolean expression that results in either True or False. if it results in True then statements inside if the body is executed, if it results in False then statements inside else body is executed.

C if-else Example

Below is a simple example to demonstrate the use of if-else in c programming:

Example:-

Output:-

C If else Statement

C if Statement

C if Statement

The c If a statement is a decision-making statement. It allows a block of code to be executed only when a specified condition is true. If a statement evaluates a boolean expression followed by one or more statements. The given boolean expression results in a boolean value that can only be either true or false. If the statement is always used with a condition. The condition is evaluated first before executing any statement inside the body of If. The statements inside the “if” body only execute if the given condition returns true. If the condition returns false then the statements inside “if” body are skipped

Need of If Statement In C

When we want to execute a block of code only when a given condition is true then we use if statement. It is one of the most simple decision-making statements.

Types of if Statement In C

The if statement can be used in many forms depending on the situation and complexity. There are following four different types of if statements:

If Statement Flowchart

The flowchart image illustrates the working of if statement:

c-if-statement

if Statement Syntax

Below is the general syntax of if statement in c programming:

Syntax:-

Working Of if Statement

Here, the if statement evaluates the test condition inside the parenthesis (). The Condition is a Boolean expression that results in either True or False. If it results in True then statements inside if the body is executed. If it results in False then execution is skipped from if body.

if Statement Example

Below is a simple example to demonstrate the use of if in c programming:

Example:-

The condition (num > 50) specified in the “if” returns true for the value of num, so the statement inside the if the body is executed. Then we would see the following output.

Output:-

c_if_statement

Multiple Conditions In if Statement

Multiple conditions in an if statement can be added using either logical AND (&&) and/or OR(||) operators. If we are using logical AND (&&) operator then the if statement will be executed if both the conditions are true. And if we are using logical OR(||) operator then the if statement will be executed if either of those conditions is true.

Example 1:-

Here, if statement will be executed if both the conditions are true. But, if the first condition is false it will not test the second condition and directly execute the else statement if provided. It will test the second condition only when the first condition is true.

Example 2:-

Here, if statement will be executed if either of those conditions is true. But, if the first condition is true it will not test the second condition and execute the if part. It will test the second condition only when the first condition is false.

Relational Operators In if Statement

Relational operators can be used for making a decision and testing conditions, which returns true or false. C has a set of relational operators that can be used in test expression.

  • < less than
  • <= less than or equal to
  • > greater than
  • >= greater than or equal to
  • == equal to
  • != not equal to

Notice:- The equal to (==) is different from the assignment operator (=). The equal to (==) operator is used to test if two values are equal to each other.

C Bit Fields

In C Programming Language we have the option to store integer members into memory spaces smaller than the compiler would ordinarily allow. These can be achieved using the space-saving structure members are called bit fields, and their width in bits can be explicitly declared.

This is very useful especially when memory or data storage is at a premium. A bit field is set up with a structure declaration that labels each field and determines its width.

Bit Field Declaration

A bit-field declaration contains a type specifier followed by an optional member_name, a colon, a constant integer expression that indicates the field width in bits, and a semicolon.

Bit fields with a width of 0 must be unnamed. Unnamed bit-fields cannot be referenced or initialized. If a series of bit fields do not makeup up the size of an int, padding can take place.

The following example demonstrates padding. Suppose that an int occupies 4 bytes. The example declares the identifier room to be of type struct app_state:

The structure room contains eight members with a width of 16 bytes. The following table describes the storage that each member occupies:

Member Name Storage Occupied
light 1 bit
fan 1 bit
(padding — 30 bits) To the next int boundary
count The size of an int (4 bytes)
ac 4 bits
(unnamed field) 4 bits
clock 1 bit
(padding — 23 bits) To the next int boundary (unnamed field)
flag 1 bit
(padding — 31 bits) To the next int boundary

You can not access the field by direct its name.

Syntax:

We can access the member “light” as “room. light”, The following expression sets the light field to 1

When you assign to a bit field a value that is out of its range, the bit pattern is preserved and the appropriate bits are assigned. The following expression sets the “fan” field of the room structure to a 0 (zero) because only the least significant bit is assigned to the fan field:

Note:- The maximum bit field length is 64 bits. For portability, do not use bit fields greater than 32 bits in size.

 

C typedef

In C programming language typedef ( type definition ) is a keyword that allows us to create an alias for existing data types. Once, we have created a type definition, then we can declare a variable using the alias we created. This alias is equivalent to the data type for which it is created. Remember that, in addition to the type definition or alias we are always free to use the original keyword to define variables of any data type.

Syntax:

It is easy to create the alias, put the typedef keyword followed by the existing type name and the new name for that type.

Let’s take look at the example below:

We have created the alias for integer data type as “my_type”, now my_type behaves the same as an integer.

Advantages of C Typedef

  • It makes the program more portable.
  • typedef makes complex declarations easier to understand.

typedef with a struct

Take a look at below structure declaration

As we can see we have to include keyword struct every time you declare a new variable, but if we use typedef then the declaration will be as easy as below

this way c typedef makes your declaration simpler.

C Typedef with Union

typedef with enum

 

 

C Input & Output

Input & Output is the way general-purpose computers can communicate or interact with the outside world. In C Programming Language input & output is the way a program can read in or write out data streams. Streams can be used for both un-formatted and formatted input and output.

To perform standard input and output, we need to include the following preprocessor directive into our files.

There are three standard streams are available to all c programs –

  • stdin (standard input)
  • stdout (standard output)
  • stderr (standard error)

Reading and writing single characters

getchar() function is used to read a single character from the “stdin” data stream, it returns the EOF (end of file) if there are no more characters to read or when you hit the end of a file or when the user types the end of the file.

putchar() function is used to write a single character to the “stdout” data stream. It puts a single character at a time, we can loop it for writing multiple characters.

Example:

Reading and writing string

The gets() function reads the input data stream until the EOF is determined, while the puts() function is used to write a string to the “stdout” stream until a newline character is detected.

Syntax:

Example:

Formatted I/O

The printf() function

The printf() function is used for writing formatted out to the “stdout” stream. This way it allows us to print values and variables to the standard output stream (in most cases, the screen).

Syntax:

Example:

The above printf statement contains two sets of arguments: the control string enclosed in double-quotes, and identifiers to specify the value to be printed. The control string contains text, conversion specifiers, or both.

Below is the list of some common conversion specifiers –

format string input type
%c character
%d digit (integer)
%f float
%lf double
%u unsigned
%s string

The scanf() function

The scanf() function is used for reading formatted input from the “stdin” data stream. It reads the string as per the format specified.

Syntax:

Example:

C File Handling

A file is a collection of streamed bytes stored on a secondary storage device. This streamed byte can be interpreted as characters, words, lines, paragraphs, and pages of a textual document; fields and records belonging to a database; or pixels from a graphical image. Through the file handling function, we can create, modify, move or delete files on the system. In every programming language, it is important to implement a file handling function. In C Programming Language a Special set of functions have been designed for c file handling operations.

Some of the basic file handling operations are-

  • Open & Close files
  • Read from & Write to files
  • Delete files.

Functions for all of the above operations are available in the stdio.h header file.

C File HandlingOperations:

Opening & Closing Files (fopen() and fclose())

In C Programming Language before we perform any operations on a file, we must open it first, this can be done using the fopen function, which returns the pointer to the required. If the file cannot be opened for any reason then the value NULL will be returned.

Syntax:

The fopen() function is used to open a file and associate an I/O stream with it.  C file handling function takes two arguments. The first argument is a pointer to a string containing the name of the file to be opened while the second argument is the mode in which the file is to be opened. The mode can be :

r Open for reading
r+ Open for reading and writing
w Open for writing and create the file if it does not exist. If the file exists then make it blank.
w+ Open for reading and writing and create the file if it does not exist. If the file exists then make it blank.
a Open for appending(writing at the end of the file) and create the file if it does not exist.
a+ Open for reading and appending and create the file if it does not exist.

Below is the code snippet for opening and closing a file –

The fclose() function is used for closing opened files.

Syntax:

The only argument it accepts is the file pointer. If a program terminates, it automatically closes all opened files. Upon successful completion, this function returns 0 else end of the file (eof) is returned. In case of failure, if the stream is accessed further then the behavior remains undefined. But it is a good programming habit to close any file once it is no longer needed. C file handling helps in better utilization of system resources and is very useful when you are working on numerous files simultaneously. Some operating systems place a limit on the number of files that can be open at any given point in time.

Read from & Write to files

Once a file is open, we can read from it or write into it in the following ways –

Character Input and Output – fgetc() and fputc()

fgetc() – Function fgetc() reads a single character from the file which has previously been opened using a function like fopen().

Syntax:

fp – file pointer

fputc() – Functionf putc() does the opposite, it writes a character to the file identified by its second argument.

Syntax:

The second argument in the putc() function must be a file opened in either write or append mode.

Example:

Formatted Input Output – fprintf() and fscanf()

fprintf – The fprintf() function is used for formatted write to file. It returns a number of characters printed or a negative number on error.

Syntax:

fscanf– The fscanf() function is used for formatted read from files. It returns a number of values read successfully.

Syntax:

Example:

Binary File Input Output – fread() and fwrite()

fread() – It reads from binary file.

Syntax:

buffer – stores the value read, size – the size of the buffer, num – number of blocks to be read, ptr – file pointer

If it encounters an error or end-of-file, it returns a zero, you have to use feof() or ferror() to distinguish between these two.

fwrite() – It write to a binary file.

Syntax:

buffer – stores the value read, size – the size of the buffer, num – number of blocks to be read, ptr – file pointer

It returns the number of items written to ptr.

fseek() – It moves the file pointer by the given offset.

Syntax:

ptr – file pointer, offset – offset in bytes from third parameter

whence(SEEK_SET – from the beginning of the file, SEEK_CUR – from the current position, SEEK_END – from the end of file)

It returns a zero on success and a non-zero on failure.

ftell() – It tells the position of the file pointer.

syntax:

ptr – FILE pointer

It returns the position of the pointer on success or -1 on error.

Example:

rewind() – It sets the file pointer to the beginning of the file.

Syntax:

ptr – FILE pointer

Example:

EOF (The End of File Marker)

EOF is a character that indicates the end of a file. It is returned by reading commands when they try to read beyond the end of a file.

C Preprocessors

Preprocessor Directives extend the power of the C programming language. C Preprocessors Directives is a special set of instructions in the program which is processed before handing over the program to the compiler. These instructions are always preceded by a pound sign (#) and NOT terminated by a semicolon. The preprocessor directives are executed before the actual compilation of code begins. Different preprocessor directives (commands) tell the preprocessor to perform different actions. We can categorize the Preprocessor Directives as follows:

  • File inclusion directives
  • Macro substitution directives
  • Conditional compilation directives

Advantages:

  • It makes program development easy
  • It enhances the readability of the program
  • It makes modification easy
  • It increases the transportability of the program between different machine architectures.

File inclusion directives

The file inclusion directive is used to include files into the current file. When c preprocessors encounters an #include directive it replaces it with the entire content of the specified file. The file inclusion directive (#include) can be used in the following two ways:

  • #include “file-name”
  • #include <file-name>

We can see that #include can be used in two ways angular brackets (<>)and inverted commas (“”). The only difference between both expressions is the location (directories) where the compiler is going to look for the file. In the first case where the file name is specified between double-quotes, the compiler will look for the in the current directory that includes the file containing the directive. In case it is not there the compiler will look at the file in the default including directories where it is configured to look for the standard header files. When #include is written with <> it means the file is searched directly where the compiler is configured to look for the standard header files. Therefore, standard header files are usually included in angle brackets, while other specific header files are included using quotes.

Take a look at the below example program. Save the following code in a file called main.c:

Then save the code below in a file called head. hand places it in the same directory as the main.c:

The variable is declared in the head.h file will be available in main.c, now we can use the variable in main().

 

Macro substitution directives

Macro substitution directives are used to define an identifier that is being replaced by a pre-defined string in the program. Macro substitution is a process in which the preprocessor replaces identifiers with one, or more program statements (like functions) and they are expanded inline.

There are two directives for Macro Definition:

  • #define – Used to define a macro
  • #undef – Used to undefine a macro

#define c preprocessors

To define preprocessor macros we can use #define.

Syntax:

Example:

The token string in above line 3.14 is replaced in every occurrence of symbolic constant PI.

C Program to find the area of a circle.

Output:

Conditional compilation directives(#ifdef, #ifndef, #if, #endif, #else and #elif)

Conditional Compilation Directives allows you to include or exclude certain part of code only when certain condition are met. These macros are evaluated on compile time.

The following directives are included in this category:

  • #if
  • #elif
  • #endif
  • #ifdef
  • #ifndef

Line control (#line) directive:

The #line directive gives us a way to control or set the value of the __LINE__ and __FILE__ macros. (Note: the filename is optional.) The __LINE__ and __FILE__ macros represent the current line being read and the current file being read.

Syntax:

Error directive (#error)

Error directive allows to aborts the compilation process when it is found, ant reports a fatal error that can be specified as its parameter.

Pragma directive (#pragma)

The #pragma directive is a compiler-specific directive used for the suppression of specific error messages.

Predefined Macros
__LINE__

It represents the line number of the current source file being compiled.

__FILE__

It represents the name of the source file being compiled.

__DATE__

It returns the date, in the form “Mmm dd yyyy”, when the compilation process began.

__TIME__

A string literal in the form “hh:mm: ss” containing the time at which the compilation process began.

__STDC__

Forces the use of standard C/CPP codes only in the program.

 

C Header Files

In C Programming Language Header Files gives us a way to reuse the external declarations, functions, or macro definition and allows us to share between other source files. When you include a header file, the compiler adds the functions, data types, and other information in the header file to the list of reserved words and commands in the language. We can include a header file in our program using C Preprocessor Directive “#include”, Header files almost always have a .h extension. Including a header file produces the same result as you copy the source code in your program.

In C Programming Language Headers files are used for the following purpose –

  • It enables you to include system or operating system-related macro definitions and functions so that you can invoke system calls and libraries.
  • You can create your own custom header files so that you can reuse and share them.
  • It makes the program more manageable.
  • It increases the portability of the program.

One of the most commonly used header files is for the standard input/output routines is called stdio. h.

We can include header files in the following two ways –

includes a header file from the current directory (the directory in which your C source code file appears), and

includes a file from a system directory.

Type Of Header Files

Standard Header Files

It is the set of header files used for performing various common and standard operations.

stdio. h – Defines core input and output functions

string.h – Defines string handling functions.

time.h – Defines date and time handling functions

math.h – Defines common mathematical functions.

User-Defined Header Files

In C Programming Language users can have their own custom header file that provides additional capabilities.

How to Create Your Own Header File in C Programming Language

Step #1

Type the below source code in a file

Put only function definition as you write in General C Program

Step #2

  • Save Above Code with [.h ] Extension.
  • Let the name of our header file be my head [ my head.h ]
  • Compile Code if required.

Step #3

Write Main Program

  • Include Our New Header File.
  • Instead of writing < my head.h> use this terminology “my head.h”
  • All the Functions are defined in the head.h header files are now ready for use.
  • Directly call function to add(); [ Provide proper parameter and take care of return type ]

While running your program both files (my head. h and sample. c) should be in the same directory.