C Language Material Ameerpet Technologies
C Language Material Ameerpet Technologies
Programming
&
Logical Thinking
SRINIVAS GARAPATI
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Introduction to C
History:
C is a Programming language developed by Dennis Ritchie in 1972.
It is mainly used in development of Operating Systems, Embedded software, Device
drivers, application software etc.
Programming language:
Programming languages are used to develop applications.
Computer applications Store data and perform operations on data.
For example: Banking application store Accounts data and perform transactions like
withdraw, deposit etc.
Platform Dependency:
Platform means “Operating System”
C and C++ Compilers convert the source program into specific Operating system
understandable code. Hence the compiled code is compatible to same Operating system
on which it has compiled.
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
2. Web application:
Application runs from multiple machines connected in a network.
Web application installed in server.
Data connection is required to run the application.
Examples: gmail.com, icici.com, irctc.in etc.
Note: We use technologies to develop Web applications which are platform independent
C-software:
C is a standalone software.
We have different types of C-software to develop and run C Programs. For example,
Turbo-C, C-Free, Code Blocks etc.
Download and install any C IDE to write and run programs easily.
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Programming Elements
1. Identity:
o Identity of a program is unique.
o Programs, Classes, Variables and Methods having identities
o Identities are used to access these members.
2. Variable:
o Variable is an identity given to memory location.
or
o Named Memory Location
o Variables are used to store information of program(class/object)
Syntax Examples
3. Function:
Function is a block of instructions with an identity
Function performs operations on data(variables)
Function takes input data, perform operations on data and returns results.
Syntax Example
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
C Application Structure
Program:
C program consists variables and functions.
Program execution starts with main() function automatically.
Main.c
#include<stdio.h>
void main()
{
printf("Hello");
}
Application:
C application contains more than one program.
We connect these programs by calling one program functions from another program.
We connect these programs using #include.
Only one program contain main() function from which application execution starts.
Main.c Arithmetic.c
#include<stdio.h>
#include<arithmetic.c> void add()
void main() {
{ printf("Add");
// invoking functions }
add(); void subtract()
subtract(); {
} printf("Subtract");
}
#include:
A pre-processor directive is used to connect the programs in C application.
Library:
Library is a collection of pre-define programs called Header-files.
Header-file contains Variables and Methods.
Library is used to develop C application quickly.
Some of the header file names as follows:
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Variables in C
Variables:
Variable is an Identity given to memory location.
Variable is used to store information.
We need to specify the datatype of every variable.
Syntax:
datatype identifier = value;
Examples:
char name[] = “amar”
int age = 23
char* mail = “[email protected]”
char gender = ‘M’;
double salary = 35000;
Assignment:
Assigning a value to the variable which is already declared.
For example,
o int a ; // declaration
o a=10 ; // assignment
Modify:
Increase or decrease the value of a variable
For example,
o int a ; // declaration
o a=10 ; // assignment
o a=a+20; //modify
Initialization:
Defining a variable along with value
For example,
o int a = 10 ; // initialization
o a = a+20 ; // modify
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Rules to create variable:
Variable contains alphabets(A-Z , a-z) or Digits (0-9) and only one symbol( _ ).
Variable should not starts with digit
o int 5a = 10; (error)
o int a5 = 10;
o int 1stRank; (error)
Note: We will discuss briefly about Local and Global variables after Functions concept
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Functions and Calling
Main() function:
Main() function must be defined in every C program
C program execution starts from main() function.
Main() function automatically invoke by Operating system.
User function:
Defining other functions along with main() function.
We must declare(prototype) of user function.
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
The following program clearly explains how the control back to calling function after execution
of called function.
Calling Function: the function from which other function called.
Called Function: the function which is called from other function.
We can invoke the function any number of times once it has defined.
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Execution flow of HelloWorld program briefly:
Every C Program execution starts with main() function.
OS invokes main() function automatically.
#include is a pre-processor directive which is used to connect programs in C application.
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Local and Global variables
Local variables:
A variable inside the function or block.
Local variable cannot access outside of that block.
int main()
{
int a ; -> local variable
}
Local variables automatically initialize with garbage values. We cannot guess garbage
value.
#include<stdio.h>
int main()
{
int a;
printf("%d \n", a); -> Prints unknown value.
return 0;
}
Format specifiers:
Formatting the result is very important before display to user.
We use following format specifiers to read and print different types of data values.
Data type Format specifier
int %d
char %c
float %f
string %s
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
#include<stdio.h>
void test();
int main (){
int a=10;
printf("a value in main : %d \n", a);
test();
return 0;
}
void test(){
printf("a value in test :%d \n", a); // Error :
}
Global Variables:
Defining a variable outside to all functions.
Global variables can be accessed from all the functions.
#include<stdio.h>
void test();
int a=10;
int main (){
printf("a value in main : %d \n", a);
test();
return 0;
}
void test(){
printf("a value in test :%d \n", a);
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
\b Backspace
\n New line
\r Carriage return
\t Horizantal tab
\v Vertical tab
\\ Backslash
\' Single quote
\" Double quote
\0 Null
Data Types in C
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Data type:
We need to specify the data type in variable declaration.
Data type specifies, the type of data is allowed to store.
Primitive types: In the above diagram primitive types are generalized. Primitive types sub
classified as follows
Following table describes the data type with size, format specifier and limits:
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Character data type: Char type is used to store alphabets, symbols and digits. We represents
character with single quotes.
#include <stdio.h>
int main(){
char v1 = 'a';
char v2 = '5';
char v3 = '$';
printf("v1 value is : %c \n", v1);
printf("v2 value is : %c \n", v2);
printf("v3 value is : %c \n", v3);
return 0;
}
#include <stdio.h>
int main(){
char v1 = 'a';
char v2 = '5';
char v3 = '$';
printf("%c ascii value is : %d \n", v1, v1);
printf("%c ascii value is : %d \n", v2, v2);
printf("%c ascii value is : %d \n", v3, v3);
return 0;
}
Output:
a ascii value is : 97
5 ascii value is : 53
$ ascii value is : 36
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
limits.h: It is a header file providing constant variables assigned with limits of each data type..
What happens when we try to store the value beyond the limits of datatype?
Every variable can store the value within the limits only.
When limit exceeded, it counts the value in the specified limit and store some other
value.
#include<stdio.h>
int main(){
char ch = 130;
printf("ch val : %d \n", ch); // prints -126
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
#include<stdio.h>
int main(){
char c1=256, c2=1024;
printf("c1 : %d \n", c1);
printf("c2 : %d \n", c2);
return 0;
}
Output:
c1 : 0
c2 : 0
#include<stdio.h>
int main()
{
short s = 32769;
printf("s val : %d \n", s);
return 0;
}
#include<stdio.h>
int main()
{
short s = -32744;
printf("s val : %d \n", s);
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
sizeof(): a pre-defined function used to find the size of Variable, value, Datatype etc.
Finding the size of expression: In expression, which type occupies highest memory will be the
output.
short + long long
float + double double
#include <stdio.h>
int main(){
char c;
short s;
printf("char + short : %d \n", sizeof(c+s));
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
C library is a Collection of Header files.
Header file contains Variables and Functions.
printf() and scanf() functions belongs to stdio.h header file.
Printf() function is used to display the information on Monitor(standard output).
Scanf() function is used to read information from keyboard(standard input)
Address operator:
We need to specify the location (memory address) using variable to read the data.
‘&’ is called Address operator in C.
#include <stdio.h>
int main()
{
int a;
printf("Enter a value : ");
scanf("%d", &a);
printf("a value is : %d \n", a);
return 0;
}
Operators in C
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Operator: It is a symbol that performs operation on data.
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
#include<stdio.h>
int main(){
float a=5, b=2;
printf("%.2f \n", a/b); // prints 2.50
return 0;
}
Operators Priority: We need to consider the priority of operators if the expression has more
than one operator. Arithmetic operators follow BODMAS rule.
Priority Operator
() First. If nested then inner most is first
*, / and % Next to (). If several, from left to right
+, - Next to *, / , %. If several, from left to right
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
int main() {
int n, sum;
printf("Enter n value : ");
scanf("%d", &n);
sum = n*(n+1)/2;
printf("Sum of first %d numbers is : %d \n", n, sum);
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
#include <stdio.h>
int main(){
int a, b;
printf("Enter 2 numbers : \n");
scanf("%d%d", &a, &b);
printf("Before swap : %d \t %d \n", a, b);
a = a+b;
b = a-b;
a = a-b;
printf("After swap : %d \t %d \n", a, b);
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Conditional operator: This operator validates the condition and execution corresponding
statement. It is also called Ternary operator.
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Relational operators: These operator returns true(1) or false(0) by validating the relation
among the data. Operators are >, <, >=, <=, ==, !=
#include<stdio.h>
int main()
{
printf("5>3 : %d \n", 5>3);
printf("5<3 : %d \n", 5<3);
printf("5==3 : %d \n", 5==3);
printf("5!=3 : %d \n", 5!=3);
return 0;
}
Note: All relational operators having same priority. Hence these operators execute from left to
right
#include<stdio.h> Explanation:
int main()
{
int a=25, b=15, c=5, d, e;
d = a>b>c;
e = b<a>c;
printf("%d, %d \n", d, e);
return 0;
}
#include<stdio.h> Explain here:
int main()
{
int a=0, b=0, c=0, d;
d = a>b==c;
printf("Output : %d\n", d);
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Modify operators:
Modify operators increase or decrease the value of variable by 1
Operators are ++, --
Modify operators also called unary operators (operate on single operand)
Modify Operators
Increment Operators Decrements Operators
Pre-Increment Post-Decrement Pre-Decrement Pos-Decrement
Example: Example: Example: Example:
int a = 5; int a = 5; int a = 5; int a = 5;
print(++a); // 6 print(a++); // 5 print(--a); // 4 print(a--); // 5
print(a); //6 print(a); //6 print(a); //4 print(a); //4
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
#include<stdio.h> #include<stdio.h> #include<stdio.h>
int main() int main() int main()
{ { {
int a=5, b; int a=5, b; int a=5, b;
b = ++a + a++; b = a++ + a++; b = --a + --a;
printf("a=%d\n", a); printf("a=%d\n", a); printf("a=%d\n", a);
printf("b=%d\n", b); printf("b=%d\n", b); printf("b=%d\n", b);
return 0; return 0; return 0;
} } }
#include<stdio.h> #include<stdio.h> #include<stdio.h>
int main() int main() int main()
{ { {
int a=5, b; int a=5, b; int a=5, b;
b = --a + a--; b = a-- + a--; b = a++ + ++a + a--;
printf("a=%d\n", a); printf("a=%d\n", a); printf("a=%d\n", a);
printf("b=%d\n", b); printf("b=%d\n", b); printf("b=%d\n", b);
return 0; return 0; return 0;
} } }
Logical Operators:
These operators return true (1) or false (0) by evaluating more than one expression.
Operators are,
o Logical-AND (&&)
o Logical-OR (||)
o Logical-NOT (!)
Following truth table represents the results of Logical operators’ evaluation
A B A&&B A||B !A !B
T T T T F F
T F F T F T
F T F T T F
F F F F T T
#include <stdio.h>
int main(){
printf("5>3 && 5!=3 = %d \n", 5>3 && 5!=3);
printf("5>3 && 5==3 = %d \n", 5>3 && 5==3);
printf("5>3 || 5==3 = %d \n", 5>3 || 5==3);
printf("5<3 || 5==3 = %d \n", 5<3 || 5==3);
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Compound assignment Operators:
Compound assignment operators reduce the size of modify expression.
Operators are +=, -=, *=, &&=, >>=
Bitwise operators:
These operators convert the input into binary data and perform operations.
Operators are,
a. Bitwise AND (&)
b. Bitwise OR (|)
c. Bitwise XOR (^)
The following table explains the how Bitwise operations returns the results.
Truth table:
A B A&B A|B A^B
1 1 1 1 0
1 0 0 1 1
0 1 0 1 1
0 0 0 0 0
Note: After performing bitwise operations, results will be displayed in Decimal format only.
Bitwise – AND operator:
#include <stdio.h> 12 = 00001100 (In Binary)
int main() 25 = 00011001 (In Binary)
{
int a = 12, b = 25; 00001100
printf("Output = %d", a & b); & 00011001
return 0; ----------
} 00001000 = 8 (In decimal)
Bitwise – OR operator:
#include <stdio.h> 12 = 00001100 (In Binary)
int main() 25 = 00011001 (In Binary)
{
int a = 12, b = 25; 00001100
printf("Output = %d", a | b); | 00011001
return 0; ----------
} 00011101 = 29 (In decimal)
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Bitwise – XOR operator:
#include <stdio.h> 12 = 00001100 (In Binary)
int main() 25 = 00011001 (In Binary)
{
int a = 12, b = 25; 00001100
printf("Output = %d", a ^ b); ^ 00011001
return 0; -----------
} 00010101 = 21 (In decimal)
2's Complement:
The 2's complement of a number is equal to the complement of that number plus 1.
Bitwise Complement of Any Number N is -(N+1).
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Shift Operators:
These operators are used to shift binary bits either to Left or Right
The operators are,
o Left Shift (<<)
o Right Shift(>>)
Theoretical formulas:
For Right Shift: n/2s
For Left Shift: n*2s
o Where ‘n’ is the data and ‘s’ is the number of bits to shift
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Control Statements in C
Sequential statements:
Statement is a line of code.
Sequential Statements execute one by one from top-down approach.
#include<stdio.h>
int main(){
int a, b, c;
a = 10;
b = a;
c = a*b;
printf("c value : %d \n", c);
return 0;
}
if(condition)
{
statements;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Program to give 15% discount to Customer if the bill amount is >= 5000
#include<stdio.h>
int main(){
float bill=0, discount=0;
printf("Enter Bill amount : ");
scanf("%f", &bill);
if(bill>=5000)
{
discount = 0.15*bill;
bill = bill-discount;
}
printf("Final bill to pay : %f \n", bill);
printf("Your discount is : %f \n", discount);
return 0;
}
Output: Enter Bill amount : 6000.0
Final bill to pay : 5100.0
Your discount is : 900.0
Program to give 20% bonus to Employees having more than 5 years’ experience
#include<stdio.h>
int main(){
int exp=0;
float salary=0, bonus=0;
printf("Enter Employee salary : ");
scanf("%f", &salary);
printf("Enter Expierience : ");
scanf("%d", &exp);
if(exp>5)
{
bonus = 0.20 * salary;
salary = salary + bonus;
}
printf("Your salary : %f \n", salary);
printf("Bonus : %f \n", bonus);
return 0;
}
Output: Enter Employee salary : 25000
Enter Expierience : 6
Your salary : 30000.000000
Bonus : 5000.000000
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
if - else block: Else block can be used to execute an optional logic if the given condition has
failed.
Syntax Flow Chart
if (condition){
If – Stats;
}
else{
Else – Stats;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Program to find the biggest of 2 numbers:
#include<stdio.h>
int main(){
int a, b;
printf("Enter a value : ");
scanf("%d", &a);
printf("Enter b value : ");
scanf("%d", &b);
if(a>b)
printf("a is big \n");
else
printf("b is big \n");
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Program to check the character is Vowel or not:
Vowels are a, e, i, o, u.
#include<stdio.h>
int main()
{
char ch;
printf("Enter character : ");
scanf("%c", &ch);
if(ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u')
printf("Given character is Vowel \n");
else
printf("Given character is not Vowel \n");
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Program to check the login details are correct or not:
#include<stdio.h>
int main(){
char user[20];
int pwd;
printf("Enter user name : ");
scanf("%s", user);
printf("Enter password : ");
scanf("%d", &pwd);
if(strcmp(user, "amar")==0 && pwd==1234)
printf("Login success\n");
else
printf("Login failed\n");
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
If-else-if ladder:
It is allowed to defined multiple if blocks sequentially.
It executes only one block among the multiple blocks defined.
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
else if(ch>='a' && ch<='z')
printf("Lower case alphabet\n");
else if(ch>='0' && ch<='9')
printf("Digit\n");
else
printf("Symbol \n");
return 0;
}
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Program to check profit or loss:
#include<stdio.h>
int main()
{
int originalCost, sellingPrice;
printf("Enter Original Cost : ");
scanf("%d", &originalCost);
printf("Enter Selling Price : ");
scanf("%d", &sellingPrice);
if(originalCost < sellingPrice)
printf("Profit\n");
else if(originalCost > sellingPrice)
printf("Loss\n");
else
printf("No Loss No Profit \n");
return 0;
}
#include<stdio.h>
int main()
{
int units;
float bill;
printf("Enter units consumed : ");
scanf("%d", &units);
if(units>0 && units<=100)
bill = units*0.8;
else if(units>100 && units<=200)
bill = (100*0.8) + (units-100)*1.0;
else if(units>200 && units<=300)
bill = (100*0.8) + (100*1.0) + (units-200)*1.2;
else
bill = (100*0.8) + (100*1.0) + (100*1.2) + (units-300)*1.5;
printf("Bill to pay : %f \n" , bill);
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Nested if block: Defining a block inside another block. Inner if block condition evaluates only if
the outer condition is valid. It is not recommended to write many levels to avoid complexity.
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
printf("Enter 2 numbers : ");
scanf("%d%d", &a, &b);
if(a!=b)
{
if(a>b)
printf("a is big\n");
else
printf("b is big\n");
}
else
printf("Both are equal numbers\n");
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Minimum pass marks must be >=35
Display the Grade only if the student passed in all subjects.
If the average >= 60 then print “A-Grade”
If the average >= 50 then print “B-Grade”
If the average >= 40 then print “C-Grade”
#include<stdio.h>
int main(){
int m1, m2, m3;
printf("Enter 3 marks : ");
scanf("%d%d%d", &m1, &m2, &m3);
if(m1>=35 && m2>=35 && m3>=35)
{
int avg = (m1+m2+m3)/3;
if(avg>=60)
printf("Grade-A\n");
else if(avg>=50)
printf("Grade-B\n");
else
printf("Grade-C\n");
}
else
printf("Student failed\n");
return 0;
}
#include<stdio.h>
int main()
{
int a, b, c;
printf("Enter angles of triangle : ");
scanf("%d%d%d", &a, &b, &c);
if(a+b+c==180)
{
if(a==b && b==c)
printf("Equilateral triangle \n");
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
else if(a==b || b==c || a==c)
printf("Isosceles triangle \n");
else
printf("Scalene triangle \n");
}
else
printf("Invalid angles given \n");
return 0;
}
#include<stdio.h>
int main()
{
int month;
printf("Enter month : ");
scanf("%d", &month);
if(month>=1 && month<=12)
{
if(month==2)
printf("28 days \n");
else if(month==4 || month==6 || month==9 || month==11)
printf("30 days \n");
else
printf("31 days \n");
}
else
printf("Invalid month given \n");
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Introduction to Loops
Note: Block executes only once whereas Loop executes until condition become False
For Loop: We use for loop only when we know the number of repetitions. For example,
Print 1 to 10 numbers
Print Array elements
Print Multiplication table
Print String character by character in reverse order
While loop: We use while loop when we don’t know the number of repetitions.
Display contents of File
Display records of Database table
Do while Loop: Execute a block at least once and repeat based on the condition.
ATM transaction: When we swipe the ATM card, it starts the first transaction. Once the
first transaction has been completed, it asks the customer to continue with another
transaction and quit.
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
For Loop
for loop: Execute a block of instructions repeatedly as long as the condition is valid. We
use for loop only when we know the number of iterations to do.
Syntax Flow Chart
for(init ; condition ; modify)
{
statements;
}
C Program to Print 1 to N:
int main(){
int n, i;
printf("Enter n value : ");
scanf("%d", &n);
for(i=1 ; i<=n ; i++){
printf("%d \n", i);
}
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
C Program to display A to Z
#include<stdio.h>
int main(){
char ch;
for(ch='A' ; ch<='Z' ; ch++){
printf("%c", ch);
}
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
C Program to display Sum of First N numbers
int main(){
int n, i, sum=0;
printf("Enter n value : ");
scanf("%d", &n);
for(i=1 ; i<=n ; i++){
sum = sum+i;
}
printf("Sum of first %d numbers is : %d \n", n, sum);
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
C program to display factors of given number
int main(){
int i, n;
printf("Enter n value : ");
scanf("%d", &n);
for(i=1 ; i<=n ; i++){
if(n%i==0)
printf("%d is a factor for %d \n", i, n);
}
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
C program to find the sum of factors for input number
int main(){
int i, n, sum=0;
printf("Enter n value : ");
scanf("%d", &n);
for(i=1 ; i<=n ; i++){
if(n%i==0)
sum=sum+i;
}
printf("Sum of factors of %d is %d \n", n, sum);
return 0;
}
Perfect Number Program: Sum of factors except itself is equals to the same number.
int main(){
int i, n, sum=0;
printf("Enter n value : ");
scanf("%d", &n);
for(i=1 ; i<n ; i++){
if(n%i==0)
sum=sum+i;
}
if(n==sum)
printf("%d is Perfect number \n", n);
else
printf("%d is not a perfect number \n", n);
return 0;
}
Fibonacci series: The series in which sum of 2 consecutive numbers will be the next number
Series: 0, 1, 1, 2, 3, 5, 8, 13, 21,…
int main(){
int i, n, a=0, b=1, c;
printf("Enter limit : ");
scanf("%d", &n);
for(i=1 ; i<=n ; i++){
printf("%d ", a);
c = a+b ;
a=b;
b=c;
}
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
While Loop
While loop: Execute a block of instructions repeatedly until the condition is false. We
use while loop only when don’t know the number of iterations to do.
while(condition)
{
statements;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Program to display sum of the digits in the given number:
int main(){
int n, sum=0;
printf("Enter num : ");
scanf("%d", &n);
while(n!=0){
sum = sum + n%10;
n = n/10;
}
printf("Digits sum : %d \n", sum);
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
C Program to display the first digit of given number:
int main(){
int n;
printf("Enter num : ");
scanf("%d", &n);
while(n>=10){
n = n/10;
}
printf("First Digit : %d \n", n);
return 0;
}
C Program to Find the Sum of First and Last digits of given number:
int main(){
int n, first, last;
printf("Enter num : ");
scanf("%d", &n);
first = n%10;
n=n/10;
while(n>=10){
n = n/10;
}
last = n%10;
printf("Sum of First and Last digits : %d \n", first+last);
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Palindrome Number Program in C:
The number become same when we reverse is called Palindrome number(121, 1001, 123321)
int main(){
int n, rev=0, r, temp;
printf("Enter num : ");
scanf("%d", &n);
temp=n;
while(n>0){
r = n%10;
rev = rev*10 + r;
n = n/10;
}
if(temp==rev)
printf("Palindrome Number \n");
else
printf("Not a palindrome number \n");
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
int main(){
int n, r, large=0;
printf("Enter num : ");
scanf("%d", &n);
while(n>0){
r = n%10;
if(r>large){
large = r;
}
n = n/10;
}
printf("Largest digit is : %d \n", large);
return 0;
}
int main(){
int n, r, sum=0, temp;
printf("Enter num : ");
scanf("%d", &n);
temp=n;
while(n>0){
r = n%10;
sum = sum + r*r*r;
n = n/10;
}
if(temp==sum)
printf("Armstrong number \n");
else
printf("Not an Armstrong number \n");
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
printf("Enter num : ");
scanf("%d", &n);
temp=n;
while(n>0){
n=n/10;
c++;
}
n=temp;
while(n>0){
r = n%10;
s=1;
for(i=1 ; i<=c ; i++)
s = s*r;
sum = sum + s;
n = n/10;
}
if(temp==sum)
printf("Armstrong number \n");
else
printf("Not an Armstrong number \n");
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Number(12) -> Square(144) -> Reverse(441) -> Square root(21) -> Reverse(12)
#include<stdio.h>
#include<math.h>
int main (){
int num, temp, r1, r2, sq, rev1 = 0, rev2 = 0;
sq = sqrt(rev1);
printf("Sqrt num : %d \n", sq);
return 0;
}
break: A branching statement that terminates the execution flow of a Loop or Switch case.
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
#include<stdio.h>
int main(){
int i;
for(i=1 ; i<=10 ; i++)
{
if(i==5)
break;
printf("i val : %d \n", i);
}
return 0;
}
Continue: A branching statement that terminates the current iteration of loop execution.
#include<stdio.h>
int main()
{
int i;
for(i=1 ; i<=10 ; i++)
{
if(i==5)
continue;
printf("i val : %d \n", i);
}
return 0;
}
Switch case
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Switch: It is a conditional statement that executes specific set of statements(case) based on
given choice. Default case executes if the user entered invalid choice. Case should terminate
with break statement.
Syntax FlowChart
switch(choice)
{
case 1 : Statements ;
break
case 2 : Statements ;
break
......
case n : Statements ;
break
default: Statements ;
}
#include<stdio.h>
int main(){
char ch;
printf("Enter character(r, g, b) : ");
scanf("%c", &ch);
switch(ch)
{
case 'r' : printf("Red \n");
break;
case 'g' : printf("Green \n");
break;
case 'b' : printf("Blue \n");
break;
default : printf("Unknown \n");
}
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
int main(){
int a, b, c, ch;
printf("Arithmetic Opeations");
printf("1.Add \n");
printf("2.Subtract \n");
printf("3.Multiply \n");
printf("4.Divide \n");
switch(ch)
{
case 1: c=a+b;
printf("Add result : %d\n", c);
break;
case 2: c=a-b;
printf("Subtract result : %d\n", c);
break;
case 3: c=a*b;
printf("Multiply result : %d\n", c);
break;
case 4: c=a/b;
printf("Division result : %d\n", c);
break;
Do-While Loop
do-while: Executes a block at least once and continue iteration until condition is false.
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Syntax Flow Chart
do
{
statements;
} while(condition);
if(n%2==0)
printf("%d is even \n", n);
else
printf("%d is odd \n", n);
}while(ch!='n');
return 0;
}
getch():
getch() is a pre-defined method belongs to conio.h header file.
It is used to read character from the console while program is running.
goto: A branching statement used to send the control from one place to another place in the
program by defining labels.
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Program to display 1 to 10 numbers without loop:
#include<stdio.h>
int main(){
int a=1;
top:
printf("a value : %d \n", a);
++a;
if(a<=10)
goto top;
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Program to perform Arithmetic operations using (while and if) :
int main(){
int a, b, ch;
while(1){
printf("Arithmetic Opeations\n");
printf("1.Add \n");
printf("2.Subtract \n");
printf("3.Multiply \n");
printf("4.Divide \n");
printf("5.Quit\n");
if(ch==1){
printf("Enter 2 numbers : \n");
scanf("%d%d", &a, &b);
printf("Add result : %d\n", a+b);
}
else if(ch==2){
printf("Enter 2 numbers : \n");
scanf("%d%d", &a, &b);
printf("Subtract result : %d\n", a-b);
}
else if(ch==3){
printf("Enter 2 numbers : \n");
scanf("%d%d", &a, &b);
printf("Multiply result : %d\n", a*b);
}
else if(ch==4){
printf("Enter 2 numbers : \n");
scanf("%d%d", &a, &b);
printf("Division result : %d\n", a/b);
}
else if(ch==5){
printf("End \n");
exit(1);
}
else
printf("Invalid choice \n");
}
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Program to perform Arithmetic operations using (while and switch):
int main()
{
int a, b, c, ch;
while(1){
printf("Arithmetic Opeations\n");
printf("1.Add \n");
printf("2.Subtract \n");
printf("3.Multiply \n");
printf("4.Divide \n");
printf("5.Quit\n");
printf("Enter your choice : ");
scanf("%d",&ch);
if(ch>=1 && ch<=4){
printf("Enter 2 numbers : \n");
scanf("%d%d", &a, &b);
}
switch(ch){
case 1: c=a+b;
printf("Add result : %d\n", c);
break;
case 2: c=a-b;
printf("Subtract result : %d\n", c);
break;
case 3: c=a*b;
printf("Multiply result : %d\n", c);
break;
case 4: c=a/b;
printf("Division result : %d\n", c);
break;
case 5: printf("End\n");
exit(1);
default: printf("Invalid choice\n");
}
}
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
{
printf("Arithmetic Opeations\n");
printf("1.Add \n");
printf("2.Subtract \n");
printf("3.Multiply \n");
printf("4.Divide \n");
printf("5.Quit\n");
Nested While loop: Defining a while loop inside another while loop. Loop execution terminates
only when outer loop condition fails.
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
#include<stdio.h>
int main(){
int x=1;
while(x<=5)
{
printf("x : %d -> ", x);
int y=1;
while(y <= 5)
{
printf("y : %d \t ", y);
++y;
}
printf("\n");
++x;
}
return 0;
}
Output:
x : 1 -> y : 1 y : 2 y : 3 y : 4 y : 5
x : 2 -> y : 1 y : 2 y : 3 y : 4 y : 5
x : 3 -> y : 1 y : 2 y : 3 y : 4 y : 5
x : 4 -> y : 1 y : 2 y : 3 y : 4 y : 5
x : 5 -> y : 1 y : 2 y : 3 y : 4 y : 5
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Outer loop represents number of rows
Inner loop represents number of columns.
Following program prints the combinations of outer loop and inner loop variable values:
#include<stdio.h>
int main()
{
int i, j;
for(i=1 ; i<=5 ; i++)
{
for(j=1 ; j<=5 ; j++)
{
printf("(%d,%d)\t", i, j);
}
printf("\n");
}
return 0;
}
Output:
(1,1) (1,2) (1,3) (1,4) (1,5)
(2,1) (2,2) (2,3) (2,4) (2,5)
(3,1) (3,2) (3,3) (3,4) (3,5)
(4,1) (4,2) (4,3) (4,4) (4,5)
(5,1) (5,2) (5,3) (5,4) (5,5)
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
int limit, n;
printf("*****Even Numbers in the Given Range*****\n");
printf("Enter Limit : ");
scanf("%d", &limit);
for(n=1 ; n<=limit ; n++){
if(n%2==0)
printf("%d \t", n);
}
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
printf("Enter Limit : ");
scanf("%d", &limit);
for(n=1 ; n<=limit ; n++){
int fact=1;
for(i=1 ; i<=n ; i++){
fact = fact*i;
}
printf("Factorial of %d is : %d \n", n, fact);
}
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
return 0;
}
C Program to print Perfect numbers in the given range:
int main (){
int limit, n, i;
printf("*****Perfect Numbers in the Given range*****\n");
printf("Enter Limit : ");
scanf("%d", &limit);
for(n=1 ; n<=limit ; n++){
int sum=0;
for(i=1 ; i<n ; i++){
if(n%i==0)
sum=sum+i;
}
if(n==sum)
printf("%d is perfect \n", n);
}
return 0;
}
C Program to print Perfect numbers in the given range:
int main (){
int limit, n, i;
printf("*****Perfect Numbers in the Given range*****\n");
printf("Enter Limit : ");
scanf("%d", &limit);
for(n=1 ; n<=limit ; n++){
int sum=0;
for(i=1 ; i<n ; i++){
if(n%i==0)
sum=sum+i;
}
if(n==sum)
printf("%d is perfect \n", n);
}
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
scanf("%d", &limit);
for(n=1 ; n<=limit ; n++){
int rev=0;
x=n;
while(x>0){
d = x%10;
rev = rev*10 + d;
x = x/10;
}
printf("%d -> %d \n", n, rev);
}
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
printf("*****Strong numbers in the Given range*****\n");
Pattern Programs in C
Basic Patterns:
int main (){
int i, j;
11111
for (i=1 ; i<=5 ; i++){
22222
for (j=1 ; j<=5 ; j++){ 33333
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
printf("%d", i); 44444
} 55555
printf("\n");
}
return 0;
}
int main (){
int i, j;
12345
for (i=1 ; i<=5 ; i++){
12345
for (j=1 ; j<=5 ; j++){ 12345
printf("%d", j); 12345
} 12345
printf("\n");
}
return 0;
}
int main (){
int i, j;
11111
for (i=1 ; i<=5 ; i++){
00000
for (j=1 ; j<=5 ; j++){ 11111
printf("%d", i%2); 00000
} 11111
printf("\n");
}
return 0;
}
int main (){
int i, j;
10101
for (i=1 ; i<=5 ; i++){
10101
for (j=1 ; j<=5 ; j++){ 10101
printf("%d", j%2); 10101
} 10101
printf("\n");
}
return 0;
}
int main (){
int i, j;
55555
for (i=5 ; i>=1 ; i--){
44444
for (j=5 ; j>=1 ; j--){ 33333
printf("%d", i); 22222
} 11111
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
printf("\n");
}
return 0;
}
int main (){
int i, j;
54321
for (i=5 ; i>=1 ; i--){
54321
for (j=5 ; j>=1 ; j--){ 54321
printf("%d", j); 54321
} 54321
printf("\n");
}
return 0;
}
int main (){
char x, y;
AAAAA
for (x='A' ; x<='E' ; x++){
BBBBB
for (y='A' ; y<='E' ; y++){ CCCCC
printf("%c", x); DDDDD
} EEEEE
printf("\n");
}
return 0;
}
#include<stdio.h>
int main (){
ABCDE
char x, y;
ABCDE
for (x='A' ; x<='E' ; x++){ ABCDE
for (y='A' ; y<='E' ; y++){ ABCDE
printf("%c", y); ABCDE
}
printf("\n");
}
return 0;
}
#include<stdio.h>
int main (){
*****
int i, j;
*****
for (i=1 ; i<=5 ; i++){ *****
for (j=1 ; j<=5 ; j++){ *****
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
printf("*"); *****
}
printf("\n");
}
return 0;
}
#include<stdio.h>
int main (){
int i, j;
for (i=1 ; i<=5 ; i++){
for (j=1 ; j<=5 ; j++){ *****
#####
if(i%2==0)
*****
printf("*"); #####
else *****
printf("#");
}
printf("\n");
}
return 0;
}
#include<stdio.h>
int main (){
int i, j;
for (i=1 ; i<=5 ; i++){ #*#*#
for (j=1 ; j<=5 ; j++){ #*#*#
#*#*#
if(j%2==0)
#*#*#
printf("*"); #*#*#
else
printf("#");
}
printf("\n");
}
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
} 55555
printf("\n");
}
return 0;
}
int main (){
int i, j;
55555
for (i=5 ; i>=1 ; i--){
4444
for (j=i ; j>=1 ; j--){ 333
printf("%d", i); 22
} 1
printf("\n");
}
return 0;
}
int main (){
int i, j;
1
for (i=1 ; i<=5 ; i++){
12
for (j=1 ; j<=i ; j++){ 123
printf("%d", j); 1234
} 12345
printf("\n");
}
return 0;
}
int main (){
int i, j;
1
for (i=1 ; i<=5 ; i++){
21
for (j=i ; j>=1 ; j--){ 321
printf("%d", j); 4321
} 54321
printf("\n");
}
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
printf("\n");
}
return 0;
}
int main (){
int i, j;
12345
for (i=1 ; i<=5 ; i++){
2345
for (j=i; j<=5 ; j++){ 345
printf("%d", j); 45
} 5
printf("\n");
}
return 0;
}
int main (){
int i, j;
5
for (i=5 ; i>=1 ; i--){
54
for (j=5; j>=i ; j--){ 543
printf("%d", j); 5432
} 54321
printf("\n");
}
return 0;
}
int main (){
int i, j;
5
for (i=5 ; i>=1 ; i--){
45
for (j=i; j<=5 ; j++){ 345
printf("%d", j); 2345
} 12345
printf("\n");
}
return 0;
}
#include<stdio.h>
int main ()
1
{
23
int i, j, k=1; 456
for (i=1 ; i<=5 ; i++){ 7891
for (j=1; j<=i ; j++){ 23456
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
printf("%d", k++);
if(k>9)
k=1;
}
printf("\n");
}
return 0;
}
#include<stdio.h>
int main ()
12345
{
6789
int i, j, k=1; 123
for (int i=5 ; i>=1 ; i--){ 45
for (j=1; j<=i ; j++){ 6
printf("%d", k++);
if(k>9)
k=1;
}
printf("\n");
}
return 0;
}
int main ()
{
A
char i, j;
AB
for (i='A' ; i<='E' ; i++) ABC
{ ABCD
for (j='A' ; j<=i ; j++) ABCDE
{
printf("%d", j);
}
printf("\n");
}
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
printf("\n");
}
return 0;
}
int main (){
int i, j, k=1;
1
for (int i=1 ; i<=5 ; i++){
01
for (j=1; j<=i ; j++){ 010
printf("%d", k++%2); 1010
} 10101
printf("\n");
}
return 0;
}
int main (){
int i, j, k=1;
10101
for (int i=5 ; i>=1 ; i--){
0101
for (j=1; j<=i ; j++){ 010
printf("%d", k++%2); 10
} 1
printf("\n");
}
return 0;
}
int main (){
int i, j;
for (i=1 ; i<=5 ; i++){
1
for (j=1; j<=i ; j++){ 00
printf("%d", i%2); 111
} 0000
printf("\n"); 11111
}
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
for (k=1 ; k<=i ; k++){ ****
printf("*"); *****
}
printf("\n");
}
return 0;
}
int main (){
int i, j, k;
for (i=1 ; i<=5 ; i++){
*****
for (j=1 ; j<i ; j++){ ****
printf(" "); ***
} **
for (k=i ; k<=5 ; k++){ *
printf("*");
}
printf("\n");
}
return 0;
}
int main (){
int i, j, k;
for (i=1 ; i<=5 ; i++){
for (j=i ; j<5 ; j++){ 1
printf(" "); 12
123
}
1234
for (k=1 ; k<=i ; k++){ 12345
printf("%d", k);
}
printf("\n");
}
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
for (k=i ; k>=1 ; k--){ 54321
printf("%d", k);
}
printf("\n");
}
return 0;
}
int main (){
int i, j, k;
for (i=5 ; i>=1 ; i--){
12345
for (j=i ; j<5 ; j++){ 1234
printf(" "); 123
} 12
for (k=1 ; k<=i ; k++){ 1
printf("%d", k);
}
printf("\n");
}
return 0;
}
int main (){
int i, j, k;
for (i=1 ; i<=5 ; i++){
12345
for (j=1 ; j<i ; j++){ 2345
printf(" "); 345
} 45
for (k=i ; k<=5 ; k++){ 5
printf("%d", k);
}
printf("\n");
}
return 0;
}
Functions in C
Variable: Stores data.
Function: Performs operation on data.
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
int identity(arguments) int add(int a, int b)
{ {
-> statements; int res = a+b ;
} return res ;
}
Built in Functions:
C library is a set of header files
Header file is a collection of pre-defined functions.
stdio.h conio.h string.h graphics.h
printf() getch() strlen() line()
scanf() clrscr() strrev() circle()
feof() cetche() strcat() bar()
… …. ….. …
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
No arguments and No return values function:
#include<stdio.h>
void sayHi(void);
int main(void)
{
sayHi();
return 0 ;
}
void sayHi(void){
printf("Hi to all \n");
}
With arguments and No return values (Print ASCII value of given character):
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
#include<stdio.h>
void ascii_value(char);
int main(void){
char sym ;
printf("Enter symbol : ");
scanf("%c", &sym);
asciiValue(sym);
return 0;
}
void asciiValue(char sym)
{
printf("ASCII value is : %d \n", sym);
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
#include <stdio.h>
float add(float,float);
float subtract(float,float);
float multiply(float,float);
float divide(float,float);
int main(){
int choice;
float a,b,c;
while(1){
printf("1.Add\n");
printf("2.Subtract\n");
printf("3.Multiply\n");
printf("4.divide\n");
printf("5.Exit\n");
printf("Enter your choice : ");
scanf("%d" , &choice);
switch(choice){
case 1 : c = add(a,b);
printf("Result : %f\n\n",c);
break ;
case 2 : c = subtract(a,b);
printf("Result : %f\n\n",c);
break ;
case 3 : c = multiply(a,b);
printf("Result : %f\n\n",c);
break ;
case 4 : c = divide(a,b);
printf("Result : %f\n\n",c);
break ;
case 5 : exit(1);
default : printf("Invalid choice \n\n");
}
}
return 0;
}
float add(float x, float y){
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
return x+y ;
}
float subtract(float x, float y){
return x-y ;
}
float multiply(float x, float y){
return x*y ;
}
float divide(float x, float y){
return x/y ;
}
Recursion:
Function calling itself
or
Calling a function from the definition of same function.
#include<stdio.h>
void recur(void);
void main(){
recur();
}
void recur(){
printf("Starts \n");
recur();
printf("Ends \n");
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
int fact(int); int fact(int n)
void main(void) {
{ if(n==0)
int n, factorial; return 1;
printf("Enter one number : "); else
scanf("%d",&n); return n*fact(n-1);
factorial = fact(n); }
printf("result : %d\n",factorial);
}
Arrays in C
Primitive type:
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Variables are used to store data.
Primitive variable can store only one value at a time.
For example,
int main(){
int a=5;
a=10;
a=20;
printf("a val : %d \n", a); // prints - 20
return 0;
}
Array:
Array is used to store more than one value but of same type.
For example, storing 100 students’ average marks.
Array creation:
In array variable declaration, we need to specify the size
Array variable stores base address of memory block.
Array elements store in consecutive memory location.
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
If the array variable is local, all locations initialize with garbage values.
int main()
{
int arr[5], i;
printf("Array elements are : \n");
for(i=0 ; i<5 ; i++){
printf("%d \n", arr[i]);
}
return 0;
}
Length of array:
sizeof() function returns the total size of array.
We can find the length of array by dividing total size with single element size.
int main()
{
float arr[5];
printf("Total size of array : %d \n", sizeof(arr));
printf("Array element size : %d \n", sizeof(arr[0]));
printf("Length of Array : %d \n", sizeof(arr)/sizeof(arr[0]));
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
If we assign the elements less than the length of array, other locations get default values.
int main(){
int arr[5] = {10, 20, 30};
int i;
printf("Array default values are : \n");
for(i=0 ; i<5 ; i++){
printf("%d \n", arr[i]);
}
return 0;
}
C Program to Check First and Last elements Sum equals to 10 or not in Array:
int main (){
int arr[] = {4, 3, 9, 2, 6};
int first = arr[0];
int last = arr[4];
if(first+last==10)
printf("Equals to 10 \n");
else
printf("Not equals to 10 \n");
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
{
int arr[] = {4, 3, 9, 2, 6};
if(arr[0]%2==0)
printf("First element is Even \n");
else
printf("First element is not Even \n");
return 0;
}
C Program to replace the First and Last elements of array with 10:
int main ()
{
int arr[] = {4, 3, 9, 2, 6}, i;
arr[0] = 10;
arr[4] = 10;
printf("Array elements are : \n");
for(i=0 ; i<5 ; i++){
printf("%d \n", arr[i]);
}
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
arr[4] = temp;
printf("Array elements are : \n");
for(i=0 ; i<5 ; i++){
printf("%d \n", arr[i]);
}
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
int arr[5] = {10, 20, 30, 40, 50}, i;
printf("Reverse Array : \n");
for(i=4 ; i>=0 ; i--){
printf("%d \n", arr[i]);
}
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
int arr[8] = {7,2,9,14,3,27,5,4};
int large=arr[0], i;
for(i=1 ; i<8 ; i++){
if(arr[i]>large)
large = arr[i];
}
printf("Largest element is : %d \n", large);
return 0;
}
void display(int[]);
int main(){
int a[5] = {10, 20, 30, 40, 50};
display(a);
return 0;
}
void display(int x[]){
int i;
printf("Array is :\n");
for(i=0 ; i<5 ; i++){
printf("%d\n", x[i]);
}
}
#include<stdio.h>
int main(){
int arr[20], n, i, ele, loc ;
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
printf("Enter size : ");
scanf("%d", &n);
printf("Enter elements : \n");
for(i=0 ; i<n ; i++){
scanf("%d", &arr[i]);
}
printf("Enter element to insert : ");
scanf("%d", &ele);
printf("Enter location to insert : ");
scanf("%d", &loc);
for(i=n-1 ; i>=loc ; i--){
arr[i+1] = arr[i];
}
arr[loc] = ele;
printf("Array elements now : \n");
for(i=0 ; i<=n ; i++){
printf("%d \n", arr[i]);
}
return 0;
}
#include<stdio.h>
void reverse(int[], int);
int main(){
int a[5] = {10,20,30,40,50}, i;
printf("Before reverse : \n");
for(i=0 ; i<5 ; i++){
printf("%d \n", a[i]);
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
reverse(a,5);
return 0;
}
void reverse(int a[], int n){
int i,j,temp;
i=0;
j=n-1;
while(i<j){
temp=a[i];
a[i]=a[j];
a[j]=temp;
i++;
j--;
}
printf("After reverse : \n");
for(i=0 ; i<5 ; i++){
printf("%d \n", a[i]);
}
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
scanf("%d", &m);
printf("Enter %d elements into A : \n", m);
for(i=0 ; i<m ; i++)
scanf("%d", &a[i]);
Linear Search:
Linear Search is used to search for an element in the array.
Linear Search can be applied on Sorted array / Unsorted array.
In linear search, index element starts with key element. If element found return index else
display Error message.
int main(){
int a[30], m, key, i, n, found=0;
printf("Enter size of array : ");
scanf("%d",&m);
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
printf("Enter Elements in array : \n");
for(i=0; i<m; i++){
scanf("%d",&a[i]);
}
int main(){
int a[30], b[10], m, n, i;
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
for(i=0 ; i<n ; i++)
a[m+i] = b[i];
Binary Search:
Binary search can be applied to only sorted array.
In binary search, we find the mid location and compare with searching element.
If the searching element less than mid location element, search goes to left side.
If the searching element greater than mid location, search goes to right side.
int main(){
int a[10],m,i,n,k,low,high;
printf("Enter the size of array : ");
scanf("%d",&n);
printf("Enter %d elements \n",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
low=0;
high=n-1;
printf("Enter the key value : ");
scanf("%d",&k);
while(low<=high){
m=(low+high)/2;
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
if(k<a[m])
high=m-1;
else if(k>a[m]){
low=m+1;
else if(k==a[m]){
printf("Element found @ loc : %d\n",m);
break;
}
}
return 0;
}
Bubble Sort:
Simple sorting technique to arrange elements either in Ascending order or Descending
order.
In Bubble sort, the index element compares with the next element and swapping them if
required.
For each pass(inner loop completion) highest element bubbled to last location.
This process continuous until the complete array get sorted.
#include<stdio.h>
int main(){
int arr[7] = {7, 3, 9, 4, 2, 5, 1}, i, j, n=7, t;
for(i=0 ; i<n-1 ; i++){
for(j=0 ; j<n-1-i ; j++){
if(arr[j]>arr[j+1]){
t = arr[j];
arr[j] = arr[j+1];
arr[j+1] = t;
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
}
}
}
printf("Sorted array : ");
for(i=0 ; i<n ; i++){
printf("%d ", arr[i]);
}
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
for(j=0 ; j<3 ; j++){
printf("%d \t", arr[i][j]);
}
printf("\n");
}
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
printf("Enter array elements : \n");
for(i=0 ; i<2 ; i++){
for(j=0 ; j<2 ; j++){
scanf("%d", &arr[i][j]);
}
printf("\n");
}
#include<stdio.h>
int main(){
int a[2][2], b[2][2], c[2][2], i, j;
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
for(j=0 ; j<2 ; j++)
c[i][j] = a[i][j] + b[i][j];
#include<stdio.h>
int main(){
int arr[3][3]={{10,20,30},{40,50,60},{70,80,90}} ,I ,j ,temp;
printf("Matrix is: \n");
for(i=0 ; i<3 ; i++){
for(j=0 ; j<3 ; j++){
printf("%d\t", arr[i][j]);
}
printf("\n");
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
}
#include<stdio.h>
int main()
{
int a[2][2],b[2][2],c[2][2],i,j,k;
printf("Enter array A \n");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
scanf("%d",&a[i][j]);
}
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
c[i][j]=0;
for(k=0;k<2;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}
}
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
String Handling in C
String:
String is a one-dimensional character array.
String is a collection symbols (alphabets, digits and special symbols).
Strings must be represented with double quotes.
Syntax: Example:
char identity[size]; char name[20];
Memory representation:
We can store only 'n-1' characters into an array of size 'n'.
Last character of every string is '\0'
ASCII value of '\0' character is 0.
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
In C, duplicate strings get different memory locations:
== operator only compares the addresses of strings, hence following program outputs
“Strings are not equal”
int main(){
char s1[10] = "abc";
char s2[10] = "abc";
if(s1==s2)
printf("Strings are equal \n");
else
printf("Strings are not equal \n");
return 0;
}
Note: Strings can be processed with \0 character only. ASCII value as follows.
#include<stdio.h>
int main(){
printf("\0 ascii value is : %d \n", '\0');
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Note: In the above program, printf() function stops printing string when \0 reached.
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
How %s read input into String variable:
“%s” takes the base address of memory block.
It reads character by character and stores from the base address.
Once input is over, it will add null character at the end of the string.
int main(){
char name[20];
printf("Enter multi word name : ");
gets(name);
printf("Hello %s \n", name);
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
void display(char name[], int age){
printf("Name is : %s \n", name);
printf("Age is : %d \n", age);
}
string.h functions
strlen() :
strlen() returns length of string excluding null character.
Return type is size_t (positive integer)
Prototype is size_t strlen(char s[]);
#include<string.h>
int main(){
char str[20];
size_t len;
printf("Enter string : ");
gets(str);
len = strlen(str);
printf("Length is : %u \n", len);
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
gets(str);
while(str[i] != '\0'){
len++;
i++;
}
printf("Length is : %u \n", len);
return 0;
}
Program to convert Upper case characters into Lower case without Library function:
#include<stdio.h>
#include<string.h>
int main(){
char src[20];
int i=0;
printf("Enter Upper string : ");
gets(src);
while(src[i] != '\0')
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
{
if(src[i]>='A' && src[i]<='Z')
{
src[i] = src[i]+32;
}
i++;
}
printf("Lower string : %s \n", src);
}
i=0;
j=strlen(src)-1;
while(i<j)
{
temp = src[i];
src[i] = src[j];
src[j] = temp;
i++;
j--;
}
printf("Reverse string : %s \n", src);
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
strcmp(): Compare strings are return 0 if equal else return the ASCII difference between
mismatching characters.
#include<string.h>
int main()
{
char s1[20] = "hello";
char s2[20] = "Hello";
if(strcmp(s1,s2)==0)
printf("Strings are equal \n");
else
printf("String are not equal \n");
}
if(stricmp(s1,s2)==0)
printf("Strings are equal \n");
else
printf("String are not equal \n");
}
#include<stdio.h>
int stringCompare(char[],char[]);
int main()
{
char str1[100], str2[100];
int compare;
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
printf("Enter second string: ");
gets(str2);
compare = stringCompare(str1,str2);
if(compare == 1)
printf("Both strings are equal.\n");
else
printf("Both strings are not equal\n");
return 0;
}
int stringCompare(char str1[],char str2[])
{
int i=0,flag=0;
while(str1[i]!='\0' && str2[i]!='\0')
{
if(str1[i]!=str2[i]){
flag=1;
break;
}
i++;
}
if (flag==0 && str1[i]=='\0' && str2[i]=='\0')
return 1;
else
return str1[i]-str2[i];
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
char *strncat(char *dest, const char *src, size_t n)
Appends the string pointed to, by src to the end of the string pointed to, by dest up to n
characters long.
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Structures in C
Introduction:
Applications are used to store and process the information
We store information using variables and process using functions.
We use different types of variables to store the information as follows.
int a = 10;
Array variable: stores more than one value but of same type.
Structure variable: stores more than one value of different data types. We define structures
using struct keyword.
struct Employee
{
int id;
char name[20];
float salary;
};
struct Employee e = {101, "Amar", 35000};
Memory representation:
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Note: Structure is a data type and memory allocate to structure only when we create variable
Structure (Data type) Memory allocation (create variable)
struct Employee
{
int id; struct Employee e;
char name[20];
float salary;
};
Program to find the size (memory allocated to structure): sizeof() functions returns the total
number bytes allocated to structure.
#include<stdio.h>
struct Emp{
int id;
char name[20];
float salary;
};
int main(){
struct Emp x;
printf("size of Emp : %d \n", sizeof(x));
printf("size of Emp : %d \n", sizeof(struct Emp));
return 0;
}
Structure initialization: Like Primitive types and Arrays, we can assign values directly to
structure variables at the time of declaration.
struct identity var = {val1, val2, val3 …};
Accessor (dot operator): We must access the locations of structure through dot(.) operator
#include<stdio.h>
struct Employee {
int id;
char name[20];
float salary;
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
};
int main(){
struct Employee e = {101, "amar", 35000};
printf("Employee id : %d \n", e.id);
printf("Employee name : %s \n", e.name);
printf("Employee salary : %f \n", e.salary);
return 0;
}
#include<stdio.h>
struct Employee {
int id;
char name[20];
float salary;
};
void display(struct Employee);
int main(){
struct Employee x = {101, "Amar", 35000};
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
display(x);
return 0;
}
void display(struct Employee y){
printf("Emp id : %d \n", y.id);
printf("Emp name : %s \n", y.name);
printf("Emp salary : %f \n", y.salary);
}
Array of Structures: by creating array type variable to structure data type, we can store multiple
records like Employee details, Customer details, Student details, Account details etc.
struct Emp{ struct Emp e; -> store 1 record
.... struct Emp e1, e2, e3; -> store 3 records
}; struct Emp arr[100]; -> store 100 records
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
int main(){
struct Emp arr[3];
int i;
Arrays in structure: If the structure contains Array type variable, we need to process the data
using loops.
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
#include<stdio.h>
struct Student
{
int id;
char name[20];
int marks[5];
};
int main()
{
struct Student s;
int i;
printf("Enter Student id and name : \n");
scanf("%d%s", &s.id, s.name);
printf("Enter student marks of 5 subjects : \n");
for(i=0 ; i<5 ; i++)
{
scanf("%d", &s.marks[i]);
}
printf("Student details are : \n");
printf("%d, %s, ", s.id, s.name);
for(i=0 ; i<5 ; i++)
{
printf("%d ,", s.marks[i]);
}
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
#include<stdio.h>
struct student
{
int id;
char name[20];
int marks[5];
};
int main()
{
struct student a[3];
int i,j;
printf("Enter student details\n");
for(i=0;i<3;i++) {
printf("Enter student id and name\n");
scanf("%d%s",&a[i].id,a[i].name);
printf("Enter marks of student\n");
for(j=0;j<5;j++)
scanf("%d",&a[i].marks[j]);
}
printf("Student details are \n");
for(i=0 ; i<3 ; i++) {
printf("%d \t %s \t ",a[i].id,a[i].name);
for(j=0;j<5;j++)
printf("%d\t",a[i].marks[j]);
printf("\n");
}
return 0;
}
Nested structures: Defining a structure inside another structure. We access the elements of
nested structure using outer structure reference variable.
#include<stdio.h>
struct Emp
{
int num;
float salary;
};
struct Employee
{
struct Emp e;
char name[20];
};
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
int main()
{
struct Employee x;
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Unions in C
Introduction:
Union is a user defined data type.
Unions were used when memory at premium.
A union basically allows a variable to have more than one type; but only one of these
types can be used.
Syntax: Example:
union identity union Test
{ {
Members; char c;
}; short s;
};
STRUCTURE UNION
Define with struct keyword. Define with union keyword
The size of the structure is equal to the sum of The size of the union is equal to the size of the
the sizes of its members. largest member.
Each member within a structure is assigned a Memory allocated is shared by individual
unique storage area. members of the union.
Individual members can be accessed at a time. Only one member can be accessed at a time.
Altering the value of a member will not affect Altering the value of any of the member will
other members of the structure. alter other member values.
Program to display size of union: The sum of all sizes of variables defined in structures is the
size of total structure.
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
#include<stdio.h>
struct st{
char a;
short b;
float c;
};
union un{
char a;
short b;
float c;
};
int main(){
struct st s ;
union un u ;
printf("Size of structure : %d \n", sizeof(s));
printf("Size of union : %d \n", sizeof(u));
return 0;
}
Accessing members of union: We use dot(.) operator to access the members of union.
Note: We can define any number of variables inside the union, but we cannot use multiple
variables at a time. We will get odd results like follows.
#include<stdio.h>
union un{
int a, b;
};
int main(){
union un u ;
u.a = 10;
printf("b value is : %d \n", u.b);
u.b = 20;
printf("a value is : %d \n", u.a);
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
#include<stdio.h>
union un
{
char a[2];
int b;
};
int main()
{
union un u ;
u.a[0] = 2 ;
u.a[1] = 3 ;
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Pointers in C
Introduction:
Pointers is a derived data type in C.
Pointer type variables store addresses of memory locations.
2. Un-typed: Can points to any type of data. It is also called Generic pointer.
void* -> can points to any data.
Operators using with Pointers: Every operation in data processing using pointers is possible
through 2 operators.
1. Address Operator (&): It returns the memory address of specified variable.
2. Pointer operator (*): It returns the value in the specified address.
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Call by Value & Call by Reference
Call by value: A copy of the variable is passed to the function.
Call by reference: An address of the variable is passed to the function.
Note: Call by reference is preferred when we have to return more than one variable, like in C
programming where we can only return one variable at a time. Call by reference can be achieved
via pointers.
Call By Reference: In this example, the output shows the correct result. This happens because
we have sent the exact address of the variable.
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Size of Pointer:
Pointer variable stores address(integer) hence the size of pointer equals to integer size.
sizeof() function can be used to display the size of each pointer type.
#include<stdio.h>
int main(){
char* a;
short* b;
float* c;
double* d;
printf("char* size : %d \n", sizeof(a));
printf("short* size : %d \n", sizeof(b));
printf("float* size : %d \n", sizeof(c));
printf("double* size : %d \n", sizeof(d));
return 0;
}
Pointer increment / decrement: When we modify the pointer, the value increase or decrease
by size bytes.
#include<stdio.h>
int main(){
char x = 'a';
float y = 2.3;
double z = 4.5;
char* p1 = &x;
float* p2 = &y;
double* p3 = &z;
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
printf("p1 value is : %u \n", p1);
printf("++p1 value is : %u \n", ++p1);
printf("p2 value is : %u \n", p2);
printf("++p2 value is : %u \n", ++p2);
printf("p3 value is : %u \n", p3);
printf("++p3 value is : %u \n", ++p3);
return 0;
}
Pointer to function: Function has address that we can assign to pointer variable by which we
can invoke the function.
Where: “fptr” is a pointer that points to a function which is taking 2 integers and return integer.
int add(int,int);
int sub(int,int);
int main(){
int r1, r2, r3, r4;
int (*fptr)(int,int);
r1=add(10,20);
r2=sub(10,20);
printf("r1 : %d\nr2 : %d\n",r1,r2);
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Pointer type-casting:
Converting one type of pointer variable into another type to access the data.
(type*) syntax is used to perform type casting.
#include<stdio.h>
void main(){
int i = 100;
int* ip;
char* cp;
ip = &i;
cp = (char*)ip;
printf("i value : %d\n", *ip);
printf("i value : %d\n", *cp);
}
Pointer to Pointer:
It is also called “double pointer”
A “Pointer to Pointer” variable holds the address of another “Pointer variable”
#include<stdio.h>
int main()
{
int x = 10;
int* px = &x;
int** ppx = &px;
#include<stdio.h>
int main()
{
int arr[5] = {10, 20, 30, 40, 50}, i;
printf("Array elements are : \n");
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
for(i=0 ; i<5 ; i++)
printf("%d\n", arr[i]);
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Pointers to Arrays:
Array variable stores address of memory block hence it is pointer type.
We can assign array variable directly to pointer variable and access the element using
that pointer variable.
#include<stdio.h>
void main(){
int a[5] = {10,20,30,40,50}, i;
int *p = a;
p=a;
for(i=0; i<5; i++){
printf("%d\t",a[i]);
printf("%d\t",p[i]);
printf("%d\t",*(p+i));
printf("%d\t",*(i+p));
printf("%d\n",i[p]);
}
}
#include<stdio.h>
int main(){
int arr[5] = {10,20,30,40,50};
int *p = arr;
printf("%d \n", *++p);
printf("%d \n", *(p+2));
printf("%d \n", *++p+3);
return 0;
}
#include<stdio.h>
int main(){
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
int arr[5] = {10,20,30,40,50};
int *ptr = arr;
printf("%d \n", *(++ptr+1));
return 0;
}
#include<stdio.h>
int main(){
int arr[5] = {10,20,30,40,50},i;
int* ptr;
ptr = arr;
printf("%u\n", *++ptr + 3);
printf("%u\n", *(ptr-- + 2) + 5);
printf("%u\n", *(ptr+3)-10);
return 0;
}
#include<stdio.h>
int main(){
int arr[5] = {8, 3, 4, 9, 2},i;
int* ptr;
ptr = arr;
printf("%u\n", *(--ptr+2) + 3);
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
printf("%u\n", *(++ptr + 2) - 4);
printf("%u\n", *(ptr-- +1 ) + 2);
return 0;
}
#include<stdio.h>
int main(){
int arr[5] = {5, 2, 7, 3, 6},i;
int* ptr;
ptr = arr;
printf("%d\n", *(ptr++ + 1) - 2);
printf("%d\n", *(ptr-- + 3) - 10);
printf("%d\n", *(--ptr + 2 ) + 5);
return 0;
}
Pointer to String:
A char* can points to a single character or a String.
Char* holds the base address.
We can process the strings using %s
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
To process character by character, we use %c
#include<stdio.h>
void main(){
char* s = "Harsha" ;
printf("%s \n", s);
printf("%c \n", s);
printf("%c \n", *s);
printf("%c \n", *(s+3));
printf("%c \n", *s+3);
}
void main(){
char* s = "Sathya" ;
printf("%c \n", *++s+2);
printf("%c \n", *++s);
printf("%c \n", *(s+2));
printf("%c \n", *s--);
printf("%c \n", *--s);
}
#include<stdio.h>
void main(){
char* str = "learnown";
printf("%c\n", *str++ + 3);
printf("%s\n", ++str+2);
}
#include<stdio.h>
void main(){
char* str = "learnown";
printf("%c\n" , *(str++ + 2)+3);
printf("%c\n" , *++str+2);
printf("%s\n" , --str-1);
}
#include<stdio.h>
void main(){
char* str = "learnown";
printf("%c\n",*((str-- +2)+1)-3);
printf("%c\n", *(--str + 3)-32);
printf("%c\n",*(++str+2)+4);
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
#include<stdio.h>
void main(){
char sport[ ]= "cricket";
int x=1 , y;
y=x++ + ++x;
printf(“%c”,sport[++y]);
}
Array of Pointers: If the array is Pointer type, it can store multiple references called Array of
Pointers.
#include<stdio.h>
int main()
{
int arr[5] = {10, 20, 30, 40, 50}, i;
int* ptr[5];
for(i=0 ; i<5 ; i++){
ptr[i] = &arr[i];
}
printf("Array elements are : \n");
for(i=0 ; i<5 ; i++){
printf("%d \n", *ptr[i]);
}
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
A function can return the string using char* return type.
#include<stdio.h>
char* read(void);
int main(){
char* name;
name = read();
printf("Name returned by read function is : %s \n", name);
return 0;
}
char* read(void){
char* name;
printf("Enter your name : ");
gets(name);
return name;
}
Array of Strings:
We can declare an array variable that stores list of pointers(strings base address).
We can process all the strings using array variable.
#include<stdio.h>
int main()
{
char* list[5] = {"C", "Java", "Python", "Android", "IOS"};
int i;
printf("List is : \n");
for(i=0 ; i<5 ; i++)
{
printf("%s \n", list[i]);
}
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
#include<stdio.h>
int main()
{
char* list[5] = {"C", "Java", "Python", "Android", "IOS"};
int i;
printf("List is : \n");
for(i=0 ; i<5 ; i++)
{
/* printf("%c \n", list[i]); */
printf("%c \n", *list[i]);
}
return 0;
}
#include<stdio.h>
void main()
{
char *s[ ] = {"black", "white", "pink", "violet"};
char **ptr[ ] = {s+3, s+2, s+1, s};
char ***p;
p = ptr;
++p;
printf("%s\n", (*(*p+1)+1)+2);
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
A function returning address:
A function can return address of aggregate data type variable or user defined data type
variable to access the data.
#include<stdio.h>
int* add(int,int);
void main(){
int a, b, *c;
printf("enter two numbers : ");
scanf("%d%d",&a,&b);
c = add(a,b);
printf("sum : %d\n",*c);
}
int* add(int x, int y) {
int z;
z=x+y;
return &z;
}
Dangling pointer:
In the above code, add function returns the address of local variable.
Local variables will be deleted once the function execution completes.
As we return the address of location, the value of that location may change by another
function before processing the data.
Hence Dangling pointers will not provide accurate results(values).
#include<stdio.h>
int *fun()
{
int x = 5;
return &x;
}
int main()
{
int *p = fun();
fflush(stdin);
printf("%d", *p);
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Operator Precedence Associative
(),[] 1 Left to right
*, identifier 2 Right to left
Data type 3
Where:
() : This operator behaves as function operator.
[] : This operator behaves as array subscription operator.
* : This operator behaves as pointer operator.
Identifier : it is name of pointer variable.
Data type : Data types also includes modifier (like signed int, long double etc.)
How to read following pointer?
char (* ptr)[3]
Step 1: () and [] enjoys equal precedence. So rule of associative will decide the priority. Its
associative is left to right So first priority goes to ().
Step 2: Inside the bracket * and ptr enjoy equal precedence. From rule of associative (right to
left) first priority goes to ptr and second priority goes to *.
Step3: Assign third priority to [].
Step4: Since data type enjoys least priority so assign fourth priority to char.
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Dynamic Memory Allocation
Using pointers, we can create variables which are ready to hold addresses of memory blocks.
The size of memory block specified at runtime through Dynamic memory allocation.
stdlib.h: stdlib.h library contains pre-defined functions to allocate and de-allocate the memory
at runtime.
1. malloc(): allocates memory dynamically to structure variables
2. calloc(): allocates memory dynamically to array variables
3. realloc(): used to modify the size of Array created by calloc()
4. free(): used to release the memory which is allocated.
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Pointer type casting:
One type of pointer can points to same type of data.
Incompatible pointer type error occurs, when we try to access another type of data.
We can typecast from one type to another type as follows.
#include<stdio.h>
int main(){
int x=10;
int* p1;
char* p2;
p1 = &x;
printf("x value is : %d \n", *p1);
p2 = (char*)p1;
printf("x value is : %d \n", *p2);
return 0;
}
#include<stdio.h>
#include<stdlib.h>
struct Emp
{
int num;
char name[20];
float salary;
};
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
int main()
{
struct Emp* p;
p = (struct Emp*)malloc(sizeof(struct Emp));
if(p==NULL)
printf("Memory allocation failed \n");
else
printf("Memory allocation success \n");
return 0;
}
#include<stdio.h>
#include<stdlib.h>
struct Emp{
int num;
char name[20];
float salary;
};
int main(){
struct Emp* p;
p = (struct Emp*)malloc(sizeof(struct Emp));
if(p==NULL){
printf("Memory allocation failed \n");
}
else{
printf("Enter Emp details :\n");
scanf("%d%s%f", &p->num, p->name, &p->salary);
printf("Name is : %s \n", p->name);
}
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
#include<stdio.h>
#include<stdlib.h>
int main()
{
int n, *arr, i;
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
arr = (int*)calloc(n, sizeof(int));
if(arr==NULL){
printf("Failed in memory allocation \n");
}
else{
printf("Enter array elements : \n");
for(i=0 ; i<n ; i++)
scanf("%d", arr+i);
for(i=0 ; i<n ; i++)
sum = sum + *(arr+i);
realloc() :
It is used to increase/decrease the size of array which is created by calloc()
Using calloc(), we can create the size with fixed size
Dynamic memory : Size varies depends on requirement
We can modify the size of array using realloc() function
void* realloc(void* ptr, size_t size);
#include<stdlib.h>
void main(){
int *p1, *p2, m, n;
printf(“enter size of array : “);
scanf(“%d”,&m);
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
p1 = (int*)calloc(m,sizeof(int));
if(p1 == NULL){
printf(“calloc failed\n”);
exit(1);
}
else
printf(“memory allocated..\n”);
p2=(int*)realloc(p1 , n*sizeof(int));
if(p2 == NULL){
printf(“realloc failed\n”);
exit(1);
}
else
printf(“memory re-aquired..\n”);
free(p1);
free(p2);
}
free() :
The memory which has allocated dynamically must be released explicitly using free
function.
Function prototype is:
o void free(void* ptr);
Using free() 147unction , we can de-allocate the memory of any type of pointer.
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
File Handling in C
FILE* pointer:
FILE is a pre-defined structure type variable.
FILE* can points to any type of file.
Once we make the pointer pointing to a file, then we can perform all FILE operations
such as reading, writing, appending and so on.
Modes of Files:
Read mode(“r”):
Opens file in Read mode.
If file is present, it opens and returns pointer to that file.
If file is not present, it returns NULL pointer.
Write mode(“w”):
Opens file in Write mode.
If file is present, it opens and removes the existing contents of File.
If file is not present, it creates the new file with specified name.
Append mode(“a”):
Opens file in append mode.
If file is present, it opens and places the cursor at the end of existing data to add the new
contents.
If file is not present, it creates the new file with specified name.
Opening a File:
fopen() is a pre-defined function that opens a file in specified mode.
On success, it opens and returns the pointer to file.
On failure, it returns NULL pointer.
FILE* fopen(char* path, char* mode);
#include<stdio.h>
int main(){
FILE* p;
p = fopen("c:/users/srinivas/desktop/code.c", "r");
if(p==NULL)
printf("No such file to open \n");
else
printf("File opened in read mode \n");
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Reading File character by character:
fgetc() is a pre-defined function belongs to stdio.h
fgetc() function read the input file character by character.
On success, it reads the character and returns ASCII value of that character
On Failure, it returns -1(EOF)
int fgetc(FILE* stream);
#include<stdio.h>
int main(){
FILE* p;
int ch;
p = fopen("code.c", "r");
if(p==NULL)
{
printf("No such file to open \n");
}
else
{
printf("File contents : \n");
while((ch=fgetc(p)) != -1)
{
printf("%c", ch);
}
}
return 0;
}
#include<stdio.h>
int main(){
printf("EOF value is : %d \n", EOF);
printf("EOF character is : %c \n", EOF);
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Closing the File: fclose() is used to close the file after use.
It is recommended to release every resource(file) after use.
On success, it returns 0.
On Failure, it returns -1.
int fclose(FILE* stream);
We must release Resource (File, Database) after use. Improper shutdown causes loss of data.
#include<stdio.h>
int main(){
FILE* p;
int r1, r2;
p = fopen("code.c", "r");
if(p != NULL){
r1 = fclose(p);
printf("On success : %d \n", r1);
r2 = fclose(p);
printf("On failure : %d \n", r2);
}
return 0;
}
#include<stdio.h>
int main(){
FILE *src, *dest;
int ch;
src = fopen("code.c", "r");
dest = fopen("output.txt", "w");
if(src != NULL){
while((ch = fgetc(src)) != EOF){
fputc(ch, dest);
}
printf("Data copied...\n");
fclose(dest);
fclose(src);
}
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
fseek(): It is used to move the cursor position in the opened file, to perform read and write
operations.
int fseek(FILE* steam, long offset, int origin);
Parameters:
“offset” is a long type variable that represents the number of bytes to move.
o Positive offset moves the cursor in forward direction
o Negative offset moves the cursor in backward direction.
Origin comes with
o SEEK_SET : Start of the file
o SEEK_CURR : Current cursor position
o SEEK_END : End of the file
On success, if specified location is present, it moves the cursor and returns 0
On failure, it returns -1.
#include<stdio.h>
int main(){
FILE* p;
int ch;
p = fopen("code.c", "r");
if(p==NULL){
printf("No such file to open \n");
}
else{
fseek(p, 100, SEEK_SET);
while((ch=fgetc(p)) != -1){
printf("%c", ch);
}
fclose(p);
}
return 0;
}
#include<stdio.h>
int main(){
FILE* p;
int ch;
p = fopen("code.c", "r");
if(p==NULL){
printf("No such file to open \n");
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
}
else{
fseek(p, -50, SEEK_END);
while((ch=fgetc(p)) != -1){
printf("%c", ch);
}
rewind(p);
while((ch=fgetc(p)) != -1){
printf("%c", ch);
}
fclose(p);
}
return 0;
}
It reads “size” bytes from specified “stream” and stores into “str”.
On Success, it returns the pointer to string that has read.
On failure, it returns NULL pointer.
It reads only size-1 characters into String every time. Last character of every string is
null(\0) by default.
#include<stdio.h>
int main(){
FILE* p;
char str[10];
p = fopen("code.c", "r");
if(p==NULL){
printf("No such file to open \n");
}
else{
fgets(str, 10, p);
printf("The string is : %s \n", str);
fclose(p);
}
return 0;
}
Reading the complete file using fgets():
#include<stdio.h>
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
int main(){
FILE* p;
char str[10];
p = fopen("code.c", "r");
if(p==NULL){
printf("No such file to open \n");
}
else{
while(fgets(str, 10, p)){
printf("%s \t", str);
}
fclose(p);
}
return 0;
}
#include<stdio.h>
int main(){
FILE *src, *dest;
char str[10];
src = fopen("code.c", "r");
if(src==NULL){
printf("No such file to open \n");
}
else{
dest = fopen("data.txt", "w");
while(fgets(str, 10, src)){
fputs(str, dest);
}
printf("Contents copied...\n");
fclose(src);
fclose(dest);
}
return 0;
}
feof():
It used to test whether End of File has reached or not
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
It returns -1 when End of File has reached else returns 0
int feof(FILE* stream)
#include<stdio.h>
int main(){
char old[20] = "data.txt";
char new[20] = "modified_data.txt";
if(rename(old, new)==0)
printf("successfully renamed...\n");
else
printf("Failed in renaming the file...\n");
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
On success, it returns 0
On failure, it returns -1
int remove(char* target);
#include<stdio.h>
int main()
{
char target[20] = "data.txt";
if(remove(target)==0)
printf("successfully removed...\n");
else
printf("Failed in removing the file...\n");
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Enumeration in C
Introduction:
An enumeration consists of a set of named integer constants.
Each enumeration-constant in an enumeration-list names a value of the enumeration set.
Syntax:
enum identifier
{
enumerator-list
};
If we don’t set values explicitly, by default values set in increasing order by one:
#include<stdio.h>
int main()
{
enum months {Jan=1, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec};
enum months month;
printf("month=%d\n",month=Feb);
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
By using constant integer values, we can use the functionality of enum set elements:
#include<stdio.h>
enum Days
{
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
};
int main()
{
enum Day today;
int x;
printf("Enter Day of Week(0 to 6) : ");
scanf("%d",&x);
today=x;
if(today==Sunday || today==Saturday)
printf("Enjoy! Its the weekend\n");
else
printf("Week day - do your work\n");
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Typedef in C
Introduction:
typedef is a user-defined data type specifier.
Using typedef we can define identifiers (synonyms) for data types.
We can use synonyms instead of original data types.
Advantage: Synonyms to data types become more readable than complex identities
The main advantage of typedef declaration is giving simple identity for complex types.
For example, char* can simply represent with name String.
#include<stdio.h>
typedef char* String;
String read(void);
int main(){
String name;
name = read();
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
printf("welcome %s\n",name);
}
String read(){
String name;
printf("Enter one name : ");
gets(name);
return name;
}
#include<stdio.h> #include<stdio.h>
typedef struct Emp{ struct Emp{
int eno; int eno;
char* ename; char* ename;
float esal; float esal;
} Employee; };
int main() int main()
{ {
Employee e; typedef struct Emp Employee;
} Employee e;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Storage classes in C
Introduction:
We need to specify the storage class along with datatype in variable declaration.
Storage class describes
o Memory location of variable
o Default value of variable
o Scope of variable
o Lifetime of variable
Storage classes classified into
o Automatic Storage classes
o Register Storage classes
o Static Storage classes
o External Storage classes
Syntax:
storage_class datatype name ;
Example:
auto int a ;
static int b ;
#include<stdio.h>
int main()
{
{
int a=10;
printf("a val : %d \n", a);
}
{
int b=20;
printf("b val : %d \n", b);
printf("a val : %d \n", a); // Error :
}
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Function scope of a variable:
Defining a variable inside the function.
We can have number of blocks inside the function.
Function scope variable can access throughout the function and from all block belongs
to that function.
#include<stdio.h>
int main()
{
int a=10; /* function scope */
{
int a=20; /* block scope */
printf("Inside First block, a val : %d \n", a);
}
{
printf("Inside Second block, a val : %d \n", a);
}
Note: If we don’t provide any value to local variable, by default the value is “Garbage value”
#include<stdio.h>
int main()
{
int a;
{
int a=10;
printf("a val : %d \n", a);
}
{
printf("a val : %d \n", a);
}
return 0;
}
Program scope:
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Defining a variable outside to all function
We can also call it as Global variable
We can access the global variable throughout the program.
#include<stdio.h>
void test(void);
int a=10; /*program scope*/
int main(){
int a=20; /*function scope */
{
int a=30; /*block scope */
printf("In block : %d \n", a);
}
printf("In main : %d \n", a);
test();
return 0;
}
void test(){
printf("In test : %d \n", a);
}
Note: auto variables must be local. If we don’t give storage class to local variable, it is auto
default.
#include<stdio.h>
int main(){
auto int a=10;
{
auto int a;
printf("In block : %d \n", a);
}
printf("In main : %d \n", a);
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
auto int a=30; /* Error : */
int main(){
auto int a=10;
printf("In main : %d \n", a);
return 0;
}
Note: Repeated variables in the logic must be defined as register variables. For example “Loop
counters”
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
register int a=30;
int main()
{
auto int a=10;
printf("In main : %d \n", a);
return 0;
}
#include<stdio.h>
static int x=10;
void test();
int main(){
static int y;
printf("y val : %d \n", y);
test();
return 0;
}
void test()
{
printf("x val : %d \n", x);
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
x=x+2;
printf("x val : %d \n", x);
}
Static variable memory will be deleted only when program execution completes.
#include<stdio.h>
void test();
int main()
{
test();
test();
test();
test();
return 0;
}
void test(){
static int x=5;
x=x+2;
printf("x val : %d \n", x);
}
Note: External variables always global variables. These variables get memory only when we
initialize with any value.
Global variables must be initialized with value. Runtime error raises if we access external
variable without value.
#include<stdio.h>
extern int a;
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
int main()
{
printf("a value is : %d \n", a);
return 0;
}
The declaration statement will not consider, memory allocates only when we assign value:
#include<stdio.h>
extern int a;
extern int a;
extern int a;
extern int a=10;
int main()
{
printf("a value is : %d \n", a);
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Command Line Arguments in C
Accepting Command Line arguments:
Every C application runs by Computer Operating System. OS runs the program from its
environment. Every OS consists CUI and GUI mode. To read command line arguments, we need
to run the C program from CUI OS mode.
Code program:
#include<stdio.h>
int main(){
printf("Hello...\n");
return 0;
}
Note: save into "turboc" folder with name Program.c
Execution:
C:/turboc>Program.exe
-> Generate output.
main() prototype: Regular main() function prototype is slightly different from the main()
function taking command line arguments. We must define main() function as follows
int main(int argc , char* argv[ ])
where:
‘argc’ = argument count ( Number of arguments passed at command line including file
name)
‘argv’ = argument vector(list) (List of arguments - default type is String)
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
main(char* []) --> can hold any type of data.
char* a = "10";
char* b = "23.45";
char* c = "g";
char* d = "CBook";
cmd/> Program
Output : Count is : 1
cmd/> Program 10 20 30 40 50
Output : Count is : 6
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
cmd/> Program
Output : No input values
int x = atoi(s1);
int y = atoi(s2);
printf("Sum is : %d \n" , x+y);
}
return 0;
}
cmd/> Program
Output : Insufficient input values
cmd/> Program 10 20
Output : Sum is : 30
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Pre-Processor in C
Introduction:
Pre-processor program that modifies the text of a C program before it is compiled.
Pre-processing includes
o Inclusion of other files
o Definition of symbolic constants and macros
o Conditional compilation of program code
o Conditional execution of preprocessor directives
and a main program called ‘program.c’ that uses the header file, like this,
#include "header.h"
int main (void)
{
x=biggest(10,20);
printf(“big :%d”,x);
return 0;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Macros(#define):
We use #define to create Macro constants.
Constants recommended to define in Upper case.
At the time or pre-processing all Macros replaced with their values.
Syntax:
#define identifier replacement-text
Example:
#define PI 3.14159
Function-like Macros
You can also define macros looks like a function call.
For example,
#define CIRCLE_AREA( x ) ( PI * ( x ) * ( x ) )
Would cause
area = CIRCLE_AREA( 4 );
To become
area = ( 3.14159 * ( 4 ) * ( 4 ) );
#if directive:
It is conditional compilation directive. If the condition is valid then the code defined
inside the block gets compiled.
Syntax:
#if <Constant_expression>
-------------
-------------
#endif
If constant expression will return 0 then condition will FALSE if it will return any non-zero
number condition will TRUE.
#include<stdio.h>
#if 0
int main(){
printf("HELLO WORLD");
return 0;
}
#endif
Runtime Error: undefined symbol main
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
#else directive: The code which is defined in else-block gets compiled if the condition fails.
#include<stdio.h>
#if(-4)
int main(){
printf("WELCOME TO C-WORLD ");
return 0;
}
#else
int main(){
printf("HELLO WORLD");
return 0;
}
#endif
#include<stdio.h>
int main()
{
int var = 5;
#if var
printf("%d",var);
#else
printf("%d",var);
#endif
return 0;
}
Compile time Error: Directive #if will not think expression constant var as integer variable and
also it will not throw an error. Then what is var for directive #if?
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
int main(){
#ifdef __DATE__
printf("%s",__DATE__);
#else
printf("First define the __DATE__");
#endif
return 0;
}
Output: It will print current system date.
Explanation: __DATE__ is global identifier. It has already defined in the header file stdio.h and it
keeps the current system date.
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.