if else statement in C Language

if else statement in C Language

In real programming situation we need to control the flow of our program. we have to execute statements according to situation like in one situation we have to execute a set of statements and in another situation we have to execute different set of statements. In this situation we can use Decision Control Instructions.

if statement is useful when we need to execute a set of statements if a particulat condition is true but when we want to execute one block of statements if condition is true and another block of statements if condition is false, only if statement is not enough. In this type of condition we need to use if else statement. In if else statement if given condition is true then if block executed , if condition is false then else block is executed.

Flow of if else statement in C Language


Syntex :
if(condition)
{
 statements;  /∗ statements will execute if the condition is true ∗/
}
else
{
 statements;  /∗ statements will execute if the condition is false ∗/
}
Example :
#include<stdio.h>
#include<conio.h>
int main()
{
int num;
printf("Enter a number = ");
scanf("%d",&num);
if(num>=50)
{
 printf("Number is Greater than or equal to 50"); 
}
else
{
 printf("Number is less than 50"); 
}
getch();
return 0;    
}
Output (first run)
Enter a number = 70
Number is Greater than or equal to 50
Output (second run)
Enter a number = 20
Number is less than 50
Description
When you run above program, it takes an input from user and store it to a variable named num. in first run user provide 70 as input and it stored to variable num. now condition in if statement is tested (num>=50 or 70>=50) and that is true so block of if statement get executed.
in second run user provide 20 as input and condition in if statement is false so block of else statement is get executed.
if statement in C Language

if statement in C Language

In real programming situation we need to control the flow of our program. we have to execute statements according to situation like in one situation we have to execute a set of statements and in another situation we have to execute different set of statements. In this situation we can use Decision Control Instructions.
if statement is one of the Decision Control Instruction. if we want to execute a block of statements in a particular condition then we can use if statement.

Flow of if statement in C Language

Flow of if statement

Syntex :
if(condition)
{
 statements;  /∗ statements will execute if the condition is true ∗/
}
Example :
#include<stdio.h>
#include<conio.h>
int main()
{
int a=10;
if(a==10)
{
 printf("First if block \n"); 
}
if(a>20)
{
 printf("Second if block \n"); 
}
if(a<20)
{
 printf("Third if block \n"); 
}
getch();
return 0;    
}
Output
First if block
Third if block 
In above program an integer variable is a is initilized to 10.then in first if block condition is a==10 that is true and it returns 1 and a non zero value in if considered true and statements in this block executed and it printf "First if block". in next if statement a>20 condition is tested that is false and returns 0 to if and second if block is not executed. in third if block a<20 condition is tested that is true and returns 1 so block executed. 
Operators in C Language

Operators in C Language

operators in c language
Operators are the symbol which operates on value or a variable. C language is rich in built-in operators and provides the following types of operators - 
  • Arithmetic Operators
  • Relational Operators
  • Logical Operators
  • Bitwise Operators
  • Assignment Operators
  • Other Operators

Arithmetic Operators

OperatorDescription
+Addition
-Subtraction
Multiplication
/Division
%Modulus/Remainder

Relational Operators

OperatorDescriptionExampleMeaning
>Greater thanx>yx is greater than y
<Less thanx<yx is less than y
>=Multiplicationx>=yx is greater than or equal to y
<=Divisionx<=yx is less than or equal to y
==Modulus/Remainderx==yx is equal to y
!=Modulus/Remainderx!=yx is not equal to y
  • Relational Operators are used to compare two numbers
  • if in a comparasion the condition is true then it returns 1.
  • if given condition is false then it returns 0.

Logical Operators

OperatorDescription
&&Logical AND
||Logical OR
!Logical NOT
Logical Operators works on Logic gates. The below table can help to understand how logic gate works in C Language.(False - 0, True - 1)
ABA&&BA||B!A
00001
01011
10010
11110

Bitwise Operators

Bitwise operator works on bits and performs bit-by-bit operation.
OperatorDescription
&Bitwise AND
|Bitwise OR
^Bitwise XOR
~One's complement
>>Right Shift
<<Left Shift

Assignment Operators

OperatorDescriptionExample
=Assigns values from right side operands to left side operandc = a + b, in this statement value of a+b assigned into c
+=Add right operand to the left operand and then assign it to left operanda+=b is same as a=a+b
-=Subtract right operand from the left operand and then assign it to left operanda-=b is same as a=a-b
∗=Multiplies right operand with left operand and then assign it to left operanda∗=b is same as a=a*b;
/=Divides left operand with the right operand and then assign it to left operanda/=b is same as a=a/b
%=Calculate modulus using two operands and then assign it to left operanda%=b is same as a=a%b

Other Operators

OperatorDescriptionExample
sizeof()Returns size of variable.sizeof(i), if i is integer then it will return 4.
&Returns address of variable in memory.&i; will return address of the variable.
*Pointer variable.*i; will declare a pointer variable.
? :Conditional Operator
..
Arithmetic Instruction in C Language

Arithmetic Instruction in C Language

Arithmetic Instructions can be classified in three categories
  • Integer Mode Arithmetic Instruction
  • Real Mode Arithmetic Instruction
  • Mixed Mode Arithmetic Instruction

Integer Mode Arithmetic Instruction

In Integer Mode Arithmetic Instruction all the operands are integer and result is also integer.
int  a,b,div;
a = 21;
b = 2;
div = a/b;
printf("Division = %d",div);

Output

Division = 10
In above program 21 divided by 2 and expected result will be 10.5 but both variable a and b are integers so their output is 10

Real Mode Arithmetic Instruction

In Real Mode Arithmetic Instruction all the operands are real numbers and result is also a real number.
float  a,b,div;
a = 21.0;
b = 2.0;
div = a/b;
printf("Division = %d",div);

Output

Division = 10.500000

Mixed Mode Arithmetic Instruction

In Mixed Mode Arithmetic Instruction some operands are integer and some are real numbers and result is a real number.
int  a;
float  b,div;
a = 21;
b = 2.0;
div = a/b;
printf("Division = %d",div);

Output

Division = 10.500000
How to Get Input using scanf in C Language ?

How to Get Input using scanf in C Language ?

Just like printf() to display output a ready-made function scanf() is also available in C Library to take input from user through keyboard. scanf() function is also defined in a Header file stdio.h so if you want to use scanf function in your program then first you have to include the header file stdio.h in your program.
Scanf in C Language
The general form of scanf() function is,
scanf("format string",list of variables);
  • %d used in format string for an integer.
  • %f used in format string for a real number.
  • %c used in format string for a character.
#include<stdio.h>
#include<conio.h>
int main()
{
int a;
float b;
printf("Enter an Integer = ");
scanf("%d",&a);
printf("Enter a Real number = ");
scanf("%f",&b);
printf("Integer number = %d \n",a);
printf("Real number = %f",b);
getch();
return 0;    
}

Output

Enter an Integer = 35
Enter a Real number = 45.56
Integer number = 35
Real number = 45.560000
In above c program the ampersand(&) is used before variables in scanf() function. & is known as "Address of " operator and it gives address of variable in memory.
  • More than one input can be taken in a single scanf() function.
scanf("%d%d%d",&a,&b,&c);

A Program to subtract two integer number in C

#include<stdio.h>
#include<conio.h>
int main()
{
int  a,b,sub;
printf("Enter First Number = ");
scanf("%d",&a);
printf("Enter Second Number = ");
scanf("%d",&b);
sub = a-b;
printf("Subtraction of %d and %d = %d",a,b,sub);
getch();
return 0;    
}

Output

Enter First Number = 20
Enter Second Number = 5
Subtraction of 20 and 5 = 15
Before going to next chapter you first need to write some programs in c like.
  • To Add two numbers using scanf().
  • To Multiply two numbers using scanf().
  • To Divide two numbers using scanf().
How to Display Output using printf in C Language ?

How to Display Output using printf in C Language ?

In C language to display output on screen ready-made library function printf() is used. printf() function defined in a Header file stdio.h so if you want to use printf function in your program then first you have to include the header file stdio.h in your program.

The general form of printf() function is,
printf("format string",list of variables);
  • %d used in format string to print an integer.
  • %f used in format string to print a real number.
  • %c used in format string to print a character.
#include<stdio.h>
#include<conio.h>
int main()
{
int a = 50;
float b = 120.54;
char c = 'R'; 
printf("Value of a = %d \n",a);
printf("Value of b = %f \n",b);
printf("Value of c = %c ",c);
getch();
return 0;    
}

Output

Value of a = 50
Value of b = 120.540000
Value of c = R
\n in above program is an Escape Sequence that is used to take cursor to the next line. if you remove this then output will display on a single line.
  • printf() can not only print a value of a variable, it can also print the result of an expression and a constant.
printf("%d%d%d",14,12-4+26,i+j);

 A Progaram in C Language to add two integer

#include<stdio.h>
#include<conio.h>
int main()
{
int  a,b,sum;
a = 20;
b = 50;
sum = a+b;
printf("Addition of %d and %d = %d",a,b,sum);
getch();
return 0;    
}

Output

Addition of 20 and 50 = 70
Before going to next chapter you first need to write some programs in c like.
  • To subtract two numbers.
  • To Multiply two numbers.
  • To Divide two numbers.
Variables in C language

Variables in C language

Variables are simply names used to refer to a location in memory – a location that holds a value with which we are working. A particular type of a variable can hold only the same type of constant. For Example, an integer variable can hold only an integer constant and float variable can hold only float(real) constant. Each variable needs a unique Identifier(unique name to use it).
Variables in C language

Rules for Constructing an Identifier

  • An identifier is combination of 1 to 31 alphabets, digits or underscores. Some compilers allow identifiers length up to 247 characters but we should use the identifiers length up to 31 characters.
  • An identifier must start with an alphabet or underscore.
  • Symbols other than underscore is not allowed in an identifier.
  • Keyword cannot be used as identifier.
Examples :
marks_1
amount
time_duration
rate

Variable Declaration in C

Before using a variable first we have to declare that variable.
Syntex :
                  type   variable_name;
  • int keyword is used to declare an Integer Variable.
  • float keyword is used to declare an float(real number) Variable.
  • char keyword is used to declare an Character Variable.
Examples:
int  a;
float  f;
char  c;
Multiple variables can be declared in a single statement.
int  i,j,k;
float  a,b;
char  c,d,e;

Storing values in variables

  • Assignment Operator(=) is used to assign value to a varible.
int  a;
float  b;
char  c;
a = 20;
b = 40.67;
c='R';
  • We can also assign value to a variable while declaration.
int  a = 20;
float  b = 40.67;
char  c = 'R';
Constants in C Language

Constants in C Language

Constants are very important part of any programming language. Constant is a value that can not be changed and remains fixed. constants are also known as Literals. in C Language constants can be classified in different categories like integer Constant, float Constant, character constant or a string.
Constants in C Language

Integer Constants in C Language 

An Integer literal can not have a decimal point. Comma or Blank space is not allowed. integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal. integer literal can also have a suffix that is a combination of U and L, for unsigned and long, respectively. The suffix can be uppercase or lowercase and can be in any order.  

Examples : 

146         /* decimal integer literal in c language */

0564       /* octal integer literal in c language */

0x2c       /* hexadecimal integer literal in c language */

89u        /* unsigned int integer literal in c language */
128l        /* long integer literal in c language */
33ul       /* unsigned long integer literal in c language */

Real Constants or Floating-point Literals in C Language

Real constants are also known as Floating Point constants and Can be written in two forms - Fractional form and Exponential form. If the value of a real constant is either too small or too large then real constant can be expressed in exponential form.0.0000794 can be written in 7.94e-5. Part before 'e' is called mantissa and part after 'e' is called exponent.
Examples:
37.89
4.98e-7
+6.74e+6
-158.29

Character Constants in C language

A Character constant is a single alphabet, a single digit or a single special symbol enclosed within single inverted commas. character literal can be a plain character (e.g., 'R'), an escape sequence (e.g., '\t'), or a universal character (e.g., '\u02C0').
Examples :
'R'
'6'
'+'
'$'
There are certain characters in C that represent special meaning when preceded by a backslash for example, newline (\n) or tab (\t)

Escape sequence

To Format Output we want to use newline, tab, quotation mark then escape sequences are used.
\\ Backslash
\' Single quotation mark
\" Double quotation mark
\? Question mark
\a Alert
\b Backspace
\f Form feed
\n Newline
\r Carriage return
\t Horizontal tab
\v Vertical tab
\0 Null character

String Literals

Strings are enclosed in double quotes. A string contains characters that are similar to character literals: plain characters, escape sequences, and universal characters. You can break a long line into multiple lines using string literals and separating them using white spaces.
Example:
"Technorials"
"C programming language"
Data Types in C Language

Data Types in C Language

data types in c is used to spicefy the type of data. in a c programming each data has its own type and different from other data like 5, 10, 25, 9, 30(Integer numbers) is different from 3.23, 14.32, 93.21(Real numbers) and 'T', '5', 'c', '@', '+' (Single Characters) is different from "Technorials", "A001"(String).
To Store Different types of data in memory we first need to define their data type. Data types are used to define a variable. In C language a variable should be declared before it can be used in program. Data types are the keywords, which are used for assigning a type to a variable. there are the data types in c language.

Integer data types in c

An Integer data type in c can not have a decimal point. Comma or Blank space is not allowed in integer data types. 
Data Type Storage Size Range
char 1 byte -128 to +127
unsigned char1 byte0 to 255
signed char1 byte-128 to 127
int2 or 4 bytes-32,768 to 32,767 or -2,147,483,648 to 2,147,483,647
unsigned int2 or 4 bytes0 to 65,535 or 0 to 4,294,967,295
short2 bytes-32,768 to 32,767
unsigned short2 bytes0 to 65,535
long4 bytes-2,147,483,648 to 2,147,483,647
unsigned long4 bytes0 to 4,294,967,295

The Size and range depends on platform, to get size of a variable on a particular platform, you can use sizeof operator.

Floating Point data types in c

An floating point type in c have a decimal point and can be written in two forms - Fractional form and Exponential form. If the value of a real constant is either too small or too large then real constant can be expressed in exponential form.0.0000794 can be written in 7.94e-5. Part before 'e' is called mantissa and part after 'e' is called exponent.
Data Type Storage Size Range Precision
float4 byte1.2E-38 to 3.4E+38 6decimal places
double8 byte2.3E-308 to 1.7E+30815 decimal places
long double10 byte3.4E-4932 to 1.1E+493219 decimal places

void type in c

void type specifies that no value is available and used as function return type, as function argument and pointers to void.

enum type in c

enum types in c are arithmetic types and used to define variables that can only assign certain discrete integer values throughout the program.
  

Basic Elements of C Programming

Basic Elements of C Programming

Before Learning C programming first you should know what is c language and structure of a c program then you should focus basic elements of c programming. these are some basic building blocks of c programming that you must study to learn c programming.

Basic Elements of C programming

C Character Set

C Character set are the set of alphabets, digits and special symbols that can be used in c programming. C Character set contains Alphabets both small and uppercase, digits and Special symbols.

Keywords

C Keywords are those words whose meaning already been defined to C Compiler.there are 32 Keywords in C Language. to read more visit our Keywords in C Language tutorial.

Identifiers

Identifiers are names used to C entities, such as variables, functions, structures and any other user-defined element. Identifier are created to give unique name to C entities to identify it during the execution of program.

Comments in C Language

Comments are used in a program to clear the purpose of the program or a statement in the program. Comments are Optional and ignored by the Compiler but when a team working on a project then comments can be used to help other team members in understanding a particular statement or a program. Comments in a C program should be enclosed within /*     */
/∗ formula to add two number ∗/
sum=a+b;

Comment can be split over more than one line.
/∗ This is a
Multiline
Comment ∗/

ANSI C allows comments in the following way.
//this is a c comment

Whitespace

whitespace in c language is completaly igonered by C compiler but you should use it make your program more readable. whitespace is the term used in C to describe blank spaces, tabs, newline characters, comments and escape sequences.


Constants

Constant is a value that doesn't change during the execution of program also known as Literals. a constant or a literal can be any type of data types in c like integer literals, floating-point literals, character literals, string literals.


Variables

Variables are simply names used to refer to a location in memory – a location that holds a value with which we are working.A particular type of a variable can hold only the same type of constant.


Keywords in C Language

Keywords in C Language

Keywords are also konwn as reserved words. C Keywords are those words whose meaning already been defined to C Compiler.there are 32 Keywords in C Language. A Keyword Cannot be used as an Identifier. each keyword has its own unique meaning and purpose in C language.

keywords in C language

auto keyword in c

auto keyword in c is used to define storage class of a variable. the default storage class for local variables is auto , so you don't normally need to manually specify it.

break keyword in c

break keyword in c is used to jump out of the innermost enclosing loop (while, do, for or switch statements) explicitly and pass the control to next statement immediately following the loop.

case keyword in c

case keyword in c language is used with switch statement to define a case.

char keyword in c

char keyword in c language represent the character data type and used to define a variable of type char.

const keyword in c

const keyword in c language is used to to make program elements constant and can be used with variables, pointers, function arguments and return types.

continue keyword in c

continue keyword in c language is used to skip certain statements inside the loop.


default keyword in c

default keyword in c language is used with switch statement to define default case.

do keyword in c

do keyword in c language is used for do while loop.

double keyword in c

double keyword in c language is used to define a floating point variable.

else keyword in c

else keyword in c language is used to define else part of if else statement.

enum keyword in c

enum keyword in c language is used to define enumerated type data type.

extern keyword in c

extern keyword in c language is used to define storage class of a variable.


float keyword in c

double keyword in c language is used to define a floating point variable.

for keyword in c

for keyword in c language is used to define for loop.

goto keyword in c

goto keyword in c language is used for unconditional jump to a labeled statement.

if keyword in c

if keyword in c language is used as a decision making statement.

int keyword in c

int keyword in c language is used to define a  variable of Integer type.

long keyword in c

long keyword in c language is also used to define a  variable of Integer type.

register keyword in c

register keyword in c language is used to define storage class of a variable.


return keyword in c

return keyword in c language is used for returning a value back to its calling function.

short keyword in c

short keyword in c language is also used to define a variable of Integer type.

signed keyword in c

signed keyword in c language is also used in defining a variable of Integer type.

sizeof keyword in c

sizeof keyword in c language is used to find the number of bytes of a variable.

static keyword in c

static keyword in c language is used to define storage class of a variable.


struct keyword in c

struct keyword in c language is used to define a structure that can hold different types of variable under one name.

switch keyword in c

switch keyword in c is used to define a switch statement to create a menu based program.

typedef keyword in c

typedef keyword in c language is used to explicitly associate a type with an identifier.

union keyword in c

union keyword in c language is used to define a union.

unsigned keyword in c

unsigned keyword in c language is also used in defining a variable of Integer type.

void keyword in c

void keyword in c language is also used in defining void data type.

volatile keyword in c

volatile keyword in c language tells the compiler not to optimize anything that has to do with the volatile variable.

while keyword in c

while keyword in c language is used to define while loop
Basic Structure of a C Program

Basic Structure of a C Program

Basic Structure of a C Program
If you are new to C programming and want to learn basics of c programming then this tutorial is for you. Before you speed up your learning in C programming, first you should take a look at basic building blocks of a c program.  Just look at the c program below and then understand basic structure step by step.

#include<stdio.h> 
#include<conio.h>
int main()
{
 printf("Technorials");
 getch();
 return 0;


Header Files


First Two lines in above program is known as header files. In C Library functions are grouped into header files. for example Standard Input and Output functions are grouped into stdio.h, Console Input/Output functions are grouped into conio.h, functions for mathematical calculation are grouped into math.h, so if we want to use a function from C Library then we first include particular header file. In Above Program we are using functions from stdio.h and conio.h. if you want to read more about it then you may visit tutorial on Header Files in C Language.

main function in C Language       


The Next Line in program int main(). All C Programming code runs inside the functions and main is the most important function in a c program. main function is the Entry Point in a C program.

int is return type of main function, when a function completes it can return a value back to calling function and the type of value it return is defined in function defination, thats why we have used return 0 at the end of main function.

printf("Technorials")


This C Statement will Display Technorials.com on Output Screen. printf() is function used to display or print output. printf function is defined in stdio.h header file, so to use this function in our program we have to include stdio.h in our program.

getch()


In some IDE like Turbo C++ if getch function is not used in your program then the output screen will be closed before you could see the output. getch function is used to get a character form keybord, we will use this function to hold the output screen till we press a character. this function is defined in conio.h

return 0


this statement belongs to the second line of program(int main()). return type of main function is defined as int, so at the end of main function we have to return an Integer value. 

; semicoln

 

; is known as statement tarminator. Every C statement must end with a ;