C if

In C, if is a keyword used to implement decision control instruction.
The condition following the keyword if is always enclosed within a pair of parentheses.
The general syntax of if statement looks like below:

Syntax of if statement:

Above statement or block of statements will be executed when a condition is true. Otherwise, these statements get skipped.

Flowchart of if statement:

if statement flowchart

First of all, a condition is check and then, depending on whether the condition is true (‘non zero’) or false (‘zero’), it transfers the control to a particular statement.
If the condition is true then the statement inside the if block gets executed otherwise statements get skipped.

Example:

Output:

Explanation:

In above program, if condition is true therefore the output is ‘b is greater than a’ and also ‘a is greater than b’ because statements execute after if statements.
Whereas, if a condition was false then the output will be only ‘a is greater than b’.

Examples:

Condition will be any of the following to print output ‘hi’:

Forms of if statements

There are many forms of if statements, check out Forms of if: page for more details. These variations are used in different ways.

Help others by sharing the content!

C Format Specifier

Format specifiers define the type of data. The value of a variable is stored in memory. So we can not directly print values of a variable from memory. Therefore C provides format specifier for printing values of variables that are stored in memory. C provide different types of format specifier for data types. Every format specifier starts with % percent sign.

Following is the list of format specifiers that can be used with the printf( ) function.

List of format specifiers in C

Data type Format Specifier
Integer short signed %d or %I
short unsigned %u
long signed %ld
long unsigned %lu
unsigned hexadecimal %x
unsigned octal %o
Real float %f
double %lf
Character signed character %c
unsigned character %c
String %s

Let’s see an example to demonstrate the use of format specifier:
Example:

Output:

The %f for printing real values, %d for printing integer values, %c for printing character values.
The format specifier does not print on the screen, it displays the value stored in variables.
In this way, you can also print a string using %s format specifier.

You can use this format specifier between expressions.
Also, these can use with scanf(). You will understand the purpose of each format specifier in the program in our next post.

 

Help others by sharing the content!

C Variable Scope

Variable scope is an area of a program where variables can be accessed.

Two types of variables depending on a variable scope.

  • local scope variable aka. local variable
  • global scope variable aka. global variables

Local variables

  • The variable declared within parentheses of function or a block is called a local variable.
  • These local variables are stored in stack section in memory.
  • The scope and lifetime of a local variable are within the block/function.
  • The default/initial value of a local variable is garbage.
  • A local variable has higher priority than a global variable.

Output:

Global variables

The variables declare above the main() function are called as global variables

These global variables are stored in the data section of memory.

The scope and lifetime of a global variable are throughout the program.

The default/initial value of a global variable is zero.

The global variable should be initialized at the time of declaration.

Output:

Some more examples –

  • A local variable has higher priority than a global variable.

    Output
  • Constant local variable should be initialized at time of declaration.
  • The global variable should be initialized at the time of declaration.
Help others by sharing the content!

C sizeof

  • sizeof is a unary operator in C.

    Output:

    The terms in sizeof() are stored in stack. Firstly the 3 is inserted then 3.0999999. Thus as we know stack is a LIFO (last in first out) data structure. Therefore sizeof operator will give a size of last item i.e, 3.0999999. As 3.0999999 is of double data type, it returns size of double i.e, 8.
  • Here in the first printf, address array elements are always an integer. So that it return value of integer data type i.e, 4 bytes. In the second printf statement, it returns the number of elements in arr and ‘\0’
  • In first statement, null consider as a string. In the second statement, nothing means zero. So there are two elements zero and \0. Therefore it return number of elements.

Difference between sizeof and strlen

Help others by sharing the content!

C printf, scanf

C printf scanf sprintf sscanf:
These C functions are used in for taking input from user and display output to the user. Lets see how to use these keywords.

  • There is no keyword available in C for doing input/output.
  • All I/O in C is done using standard library functions.
  • C provide us some in build function like printf (), scanf () etc.
  • These functions are predefined in library “stdio.h”.
  • To include functions printf and scanf in program we have to include “stdio.h” file.
  • printf() and scanf() are different from Printf() and Scanf() as C is case sensitive language.
  • printf( ) outputs the values to the screen.
  • Whereas, scanf( ) receives them from the keyboard.
  • scanf() is used to read data from the keyboard.
  • All characters in printf() and scanf() functions must be in lower case.

The general form of printf( )

<format string> can contain, %f for printing real values, %d for printing integer values, %c for printing character values. This format string may also contain any other characters. When the printf ( ) is executed these characters are printed as they are.

printf() examines the format string from left to right. So it continuously prints characters that it encounters.  When any format string encounters it picks up the first variable in the list of variables and prints its value in the specified format.

The general form of scanf( )

In the scanf, the ampersand (&) before the variables is a must. & is an ‘Address of’ operator. It gives the location number used by the variable in memory. A blank, a tab or a new line must separate the values supplied to scanf( ). Do not include these escape sequences in the format string. All the format specifications that we have learned in printf( ) function are applicable to scanf( ) function as well.

Let’s see the example –

Output:

In above program, during compilation, when %d is met compiler picked up variable ‘c’ and print its value.  Similarly, when an escape sequence (newline, tab characters) is met it takes the appropriate action.  This process continues until the end of the format string is not reached.

sprintf and sprintf functions

sprintf( ) and printf() function works similar except one small difference.

printf() sends the output to the screen whereas sprintf() function writes the output to an array of characters.
Let’s see an example to understand difference-

In above program The printf() prints values of a, ch, and b on screen. Whereas sprintf() stores these values in the character array str.
Using sprintf( ) doesn’t get displayed on the screen. So by using printf() you can print string str on screen.

sscanf() allows us to read characters from a string and to convert and store them in C variables according to specified formats. The usage of sscanf( ) is same as scanf( ), except that the first argument is the string from which reading is to take place.

Help others by sharing the content!

Difference between strlen and sizeof

strlen()

  • strlen() is a predefined function in C.
  • strlen() is used to get the length of an array of chars/string.

sizeof()

  • sizeof is a unary operator in C.
  • sizeof() is used to get the actual size of any type of data in bytes.

Some example to determine difference between strlen() and sizeof().

  • sizeof() calculate the length of string including ‘\0’. Whereas strlen() calculate the length of string excluding ‘\0’.
  • .
  • strlen() stops calculating a length of string when the pointer points to ‘\0’, even though ‘\0’ is in the string.
  • .

    Here in first printf statement, the address of array elements is always an integer. So that it return value of integer data type i.e, 4 bytes in the second printf statement, it returns the number of elements in arr including ‘\0’.

    strlen(&arr[1]) – This calculate length from arr[1] upto end of string excluding ‘\0’. strlen(arr) – it return the number of elements in arr excluding ‘\0’

Help others by sharing the content!

C continue keyword

Sometimes there is a situation in the program where we want to take control to the beginning of the loop, bypassing the statements inside the loop, which have not yet been executed. The keyword continue allows us to do this. The continue statement skip the present iteration or true expression and jumps to next iteration. Generally continue keyword cannot use with control statement (if, if-else, switch). It is used in loops.

Let’s see an example to demonstrate the use of continue

Output:

Here in above example, the condition i == 3 is satisfied then also it gets skipped. Because of keyword continue.

continue keyword with while

Output:

 

Output:

Help others by sharing the content!

C break keyword

Sometimes there is a situation where we want to jump out of the loop, without checking the loop condition. The break keyword allows us to do this. When the compiler sees break inside any loop, control automatically passes to the first statement after the loop. Thus we can say break takes control outside the immediate block or loop(while, do while, for) or switch case.

You will understand better the use of break keyword from the following example:

Example:

Output:

Here you can see values from 0 to 6 is not printed after i == 3. Because if condition is satisfied. But in if break keyword is used. So the control is passed to an immediate statement.

Progran using break keyword

Output:

Help others by sharing the content!

C Structure

We have seen earlier how variables hold only one item. And how arrays can hold a number of items of the same datatype. But to hold a number of items each of different data type, C provides a datatype called structure.

For example, suppose you want to store data about a book. You might want to store its name (a string), its price (a float) and a number of pages in it (an int). Then you have to construct individual arrays, one for storing names, another for storing prices and still another for storing a number of pages.

The program becomes more difficult to handle as the number of items relating to the book go on increasing like date of publishing, a name of publisher etc. To solve this problem, C provides a special data type—the structure. Here is way to declare structure

Defination of Structure

  • A structure is a collection of different data types.
  • To declare structure in C, struct keyword is used.
  • Structures are used to represent a record.
  • Structure is a user defined datatype.
  • The elements of structure is called as member.
  • It is widely used to store book information, student information, employee information, product information etc.

Declaring a Structure

The general syntax to declare structure is given below:

A semicolon is must after closing brace. Only declaring structure does not reserve any space in memory.

Example:

In this statement a new structure of name book is define. A struct keyword is used to define a structure. The name, price, pages are a member of the structure. Each variable of this data type will consist of a character variable called name, a float variable called price and an integer variable called pages.

This statement sets aside space in memory. It makes available space to hold all the elements in the structure—in this case, 7 bytes—one for name, four for price and two for pages. These bytes are always in adjacent memory locations.

Declaring Structure Variable

To access the member of a structure, we can declare variables for the structure. Let’s see the example to declare structure variable. There are two ways to declare structure variable:

Let’s see the example to declare structure variable by struct keyword. It should be declared within the main() function.

is same as…

It is the another way to declare variable at the time of defining structure.

Structure variables can also be initialized where they are declared.

Note:

  • The closing brace in the structure type declaration must be followed by a semicolon.
  • Declaring the structure does not reserve any space in memory.
  • Usually structure type declaration appears at the top of the source code file, before any variables or functions are defined.
  • At the time of declaration of structure memory is not allocated. When structure variable is created then memory is allocated.
  • During declaration of structure, members of structure should not be initialized because memory is not allocated for members of structure.
  • The values of a structure variable can be assigned to another structure variable of the same type using the assignment operator.

Accessing Structure Members

In arrays we can access individual elements of an array using a subscript. There are two ways to access structure members.

  • By dot . operator
  • By pointer & operator.

Example:

Output:

Array of Structures

To store data of 100 employees we would be required to use 100 different structure variables from e1 to e100, which is definitely not very convenient. A better approach would be to use an array of structures. Following program shows how to use an array of structures.

Output:

Following diagram shows memory allocation of an array of structure.
structure-example

Uses of structure

A structure is mainly Database Management. To maintain data about employees, books in a library, items in a store, financial accounting transactions in a company etc.
They can be used for a variety of purposes like:

  • Changing the size of the cursor
  • Clearing the contents of the screen
  • Placing the cursor at an appropriate position on screen
  • Drawing any graphics shape on the screen
  • Receiving a key from the keyboard
  • Checking the memory size of the computer
  • Finding out the list of equipment attached to the computer
  • Formatting a floppy
  • Hiding a file from the directory
  • Displaying the directory of a disk
  • Sending the output to printer
  • Interacting with the mouse
Help others by sharing the content!

C Functions

  • A function is a self-contained block of statements.
  • Function is the block of code which does predefined task.
  • Writing functions avoids rewriting the same code over and over.
  • Any C program at least contains one function.
  • C program is a collection of one or more functions.
  • This function is main(), this function is important because execution always start from main().
  • Without main(), C program does not execute.
  • The compiler always begins the program execution with main( ).
  • Every function in a program must be called directly or indirectly by main( ).
  • Any C program can contain any number of functions.
  • These function called or execute as there sequence given in main().
  • One function can call another function.
  • In a program, a function can be called any number of times.
  • It is not necessary, the order in which functions are defined and order in which functions are called will be same.
  • A function can call itself. Such a process is called recursion.
  • A function can not be defined in another function.

Advantages of function:

  • Plugability
  • Readability
  • Memory requirement
  • Debugging
  • Reusability
  • Modularity

Types of Function

There are basically two types of functions:

  1. predefined or library or build-in functions.
  2. user defined functions.

The predefined functions like printf(), scanf(),getchar() etc. These predefined functions are already defined in standard library files, like stdio.h, conio.h etc. Predefined functions are commonly used functions stored in a library.

The user-defined function is defined by a user. If a user wants to write function then user have to write the declaration of a function. There can be any number of user-defined functions. But it is necessary to have one predefined function i.e, main().

Function Elements

Function have following three elements

  1. Function calling
  2. Function declaration
  3. Function definition

Example:

Function calling:

Function calling means calling a function from anywhere in the program. A function is called whenever it is needed. A function is called by using their name. As given in above program add(a,b) is called as function calling. A function is called by using their name followed by a list of arguments enclosed in parenthesis and separated by commas.

In above program ‘add’ is a function name and ‘a’ and ‘b’ are called as actual arguments or actual parameters.
When program executes, main() function call add() function then compiler find out add() function in program.
If a function is present then compiler execute this function and return value to function calling if required.
In this way, a function can be call.

Function declaration:

Usually, the function declaration is written on top of the program. Function declaration does not have any body.
The function declaration is also called a function prototype. In above program add() takes two integer parameters and return integer value. Function declaration is ended with a semicolon ;.

Syntax for function declaration:

return_type – it represents datatype of the value that is return by function.
The return_type of function declaration and return_type of function definition must be same.
function_name – it is a name of a user-defined function.
datatype1 – this is the type of argument 1. The datatypes of the respected arguments have to be same as given in function definition.
datatype2 – this is the type of argument 2.
datatype n – this is the type of argument number n.

Function definition:

It is a block of code in which the role of the function is defined. As in above example, the actual logic of function add() is written in a function definition. Here ‘p’ and ‘q’ are called as formal parameters or formal arguments.Because they represent the name of the data item that is transferred into the function from the calling portion of the program. So the values stored in actual parameters are copied into formal parameters. Name of formal parameters and name of actual parameters can be same or different.
Even though their names are same then also they are different and occupied different memory location.

Syntax for function defination

The following condition must be satisfied for the function call.

  • The number of arguments in the function call and function declaration must be same.
  • The datatype of each of the argument in the function call should be same as the corresponding parameter in the function declaration statement.

Return statement:

  • The return statement immediately transfers the control back to the calling program.
  • It returns the value to calling program.
  • There is no restriction on the number of return statements in a function.
  • The return statement need not always be present at the end of the called function.
  • All the following are valid return statements.
  • In some programming situations, we want that a called function should not return any value. This is made possible by using the keyword void.
    Example:
  • A function can return only one value at a time.
  • The following statements are invalid.

Functions Argument:

  • The list of variables used inside the parentheses of functions is called as arguments or parameters.
  • Any number of arguments can be passed to a function
  • If the value of a formal argument is changed in the called function, the corresponding change does not take place in the calling function.
  • The values stored in actual parameters are copied into formal parameters
  • NAme of formal parameters and name of actual parameters can be same or different.
  • Arguments can be passed to a function by two methods. They are,
    • call by value
    • call by reference
Help others by sharing the content!