UNIT 1 C PRogramming Fundamentals
UNIT 1 C PRogramming Fundamentals
Structure of a C Program:
Documentation Section
Definition Section
main()Function
{
Declaration part;
Executable Part;
}
sub program section
{
Body of the subprogram;
}
Documentation section
It contains a set of comment lines used to specify the name of program the author and other
details etc.,
It will not be executed in the program.
Ex:-
// single line command
/* Multiple line commands */
Definition section:-
We can define all constants here. These values will not be changed in the program
Ex:
#define a 10
Main function():
It is must for all the programs.
A program cannot run without main().
Program starts to run from main() only.
Ex:-
main()
{
…..
…..
}
Declaration part:-
The declaration part declares the entire variables that are used in the Executable part.
The initialization of variables is also done in this section. This also called as local variable
declaration.
Ex:
int a;
int a=10;
Executable section:-
It contains atleast one valid „C‟ statement.
Execute the statements in this section.
Ex:
C=a+b;
printf(“%d”, c);
PROGRAMMING RULES
While writing a program, a programmer should follow the following rules.
1. All statements should be written in lowercase letters.
2. Uppercase letters are only used for symbolic constants
3. Blank space may be inserted between words. But blank space is not used
while declaring a variable, keyword, constant and function.
4. The programmers can write the statement anywhere between the two
braces.
5. We can write one or more statements in a same line by separating each
statement in a same line by separating each statement with semicolon (:)
6. The opening and closing braces should be balanced.
+ Addition 2+9 = 11
- Subtraction 9-2= 7
* Multiplication 2*9= 18
/ Division 9/3= 3
Operator Meaning
< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to
== is equal to
!= is not equal to
Logical operators are used to combine the results of two or more conditions.
Compound assignment
Assign a value to variable.
Nested assignment
Assign a value (or) Expression to variable.
Syntax: Ex:
i=j=k=1 x=y=z=(i+j+k)
(v) Increment & Decrement Operator
'C' has two way useful operators not generally found in other languages, these are
the increment (++) and decrement (--) operators. „+‟ & „-‟ operators are called
unary operators.
Because they acts upon only one variable.
++x Pre increment
--x Pre decrement
x++ Post increment
x-- Post decrement.
(vi) Conditional Operator
Checks the condition and executes the statement.
Ternary Operator
( condition ? Exp1:Exp2)
Eg:
big=(a>b )? a:b;
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
<< Shift left
>> Shift right
~ One's complement
Operators Meaning
, Comma Operator
Sizeof size of operator
& and * Pointer Operator
. and Member selection operators
Sizeof() Operator:
sizeof() is a unary operator, that returns the length in bytes of the specified variable, and
it is very useful to find the bytes occupied by the specified variable in the memory.
Expressions
An expression represents data item such as variables, constants and are interconnected
with operators as per the syntax of the language.
Example:
y=(a/b)+c; z=(a*b)-d;
1. if statements:
if is a c keyword.
The if statement is a decision making statement
Used to control the flow of execution by executing statements when the logical
condition is true (or) false.
It has only one option.
The set of command lines are executed only when logical condition is true.
Syntax Example
if(Condition) if(a>10)
{ {
/* true statement(s) */ Printf(“a is bigger”);
} }
Flow Diagram:
2. if...else statements:
It is two way decision making statement
if…..else statement take care of true as well as false condition.
It has two block else
if block is executed when the condition is true, else block is executed when the
condition is false.
An if statement can be followed by an optional else statement, which executes when
the Condition is false
Flow Diagram:
Syntax Example
if(Condition) if(a%2)
{ {
/*true statement(s) */ printf(“given no is Even”);
} }
else else
{ {
/*falsestatement(s) */ printf(“given no is Odd”);
} }
FLOWCHART
Syntax Example
if(Condition 1) if(n>5)
{ {
/*true statement(s) */ printf("Number is greater than 5”);
if(Condition2) }
{ else
/*true statement(s) */ {
} if(n==5)
else {
{ printf("Number is 5”);
/*false statement(s) */ }
} else
} {
else printf("Number is lesser than 5”);
{ }
/* false statement(s) */ }
}
Syntax: Example
if(Condition 1) if(a>b && a>c)
{ {
/*true statement(s) */ printf("a is Biggest Number:%d\n", a);
else if(Condition2) }
{ else if(b>c)
/*true statement(s) */ {
} printf("b is Biggest Number: %d \n", b);
else if(Condition3) }
{ else
/*false statement(s) */ {
} printf("c is Biggest Number: %d \n", c);
} }
else
{
/*false statement(s) */
}
Flowchart:
Switch-Case Statements:
The switch statement is used to pickup or executes a particular group of statements from
several available groups of statements.
It allows us to make a decision from the number of choices.
Syntax:
Flow Diagram:
2. DO WHILE LOOP IN C:
Like a while statement, except that it tests the condition at the end of the loop body
Syntax Example
do do
{ {
statements; fact=fact*i;
} i++;
while (condition); } while(i<=num);
3. FOR LOOP IN C:
The for loop is another repetitive control structure and is used to execute set of
instructions repeatedly until the condition becomes false.
For loop has three parts:
1. Initialize counter is used to initialize counter variable.
2. Test condition is used to test the condition.
3. Increment/decrement counter is used to increment or decrement counter variable.
Syntax:
for (variable initialization; condition checking; increment/decrement)
{
Statements;
}
Example:
for(i=1;i<=num; i++)
{
fact=fact*i;
}
The value to these functions has to be given in a particular order. They are classified as follows:
Input Output
scanf() printf()
fscanf() fprintf()
Input Function:
i. scanf() Function:
o scanf() function is used to read a character, string, numeric data from keyboard.
syntax:
scanf(“control string”, address of the variable);
Example:
int a;
scanf(”%d”,&a);
where & - The address of the variable a.
Rules to be followed:
1. The control string must be given within double quotation.
2. The variables can be separated by using comma.
3. It should be terminated by a semi colon.
4. No empty space should be given between two control strings.
ii. fscanf() Function: This function is used to read the data from a file.
Output Function:
i. printf() Function:
The printf() function is used to print the character, string, float, integer, octal and hexadecimal
values onto the output screen.
syntax:
Example;
int a=10;
printf(“The value is :%d”,a);
3. Any number of values can be displayed. The variables must be separated by comma.
ii. fprintf() Function: This function is used to write data into a file.
Sample Program using scanf() and printf() functions:
#include<stdio.h>
void main()
{
int a;
printf(“\nEnter the value for a”);
scanf(“%d”,&a);
printf(“\n The value entered is %d”,a);
}
Output:
Enter the value for a 7
The value entered is 7
putc(c);
2. putchar() :
Syntax:
putchar( character variable);
Example :
char x;
putchar(x);
String Function gets() and puts():
1. gets():
It is used to read the string (string is a group of character) from the standard input device.
Syntax:
gets(char type of array variable);
Example :
char c[10];
gets(c);
2. puts() : It display the string to the standard output device.
Syntax:
puts(char type array variable);
Example :
char c[];
puts(c);
1. OPERATOR PROGRAMS
{ { { {
{ {
printf (“b is greater ”) printf(" \n a is biggest");
} }
} } } }
{ { { {
} } } }
Output:
Post increment Value:5 Output: Output:
Output:
Pre increment Value:7 value a&b is: 0 The Larger Value is 10
size of int is: 2
Pre decrement Value:6
Post decrement Value:6
else else
{ {
printf(“c is printf(" b is
greater”); greater");
}
getch( ); getch( ); getch( ); getch( );
} } } }
Output:
Output: Output: Output:
The sum of the two
a is bigger than 10 a is bigger than b a is bigger than b
values:15
3. LOOPING PROGRAM
{ { {
while(i<=n) do
for(i=1;i<=n;i++)
{ {
{
fact =fact *i; fact =fact *i;
fact =fact *i;
i++; // i=i+1 i++; // i=i+1
}
} }while(i<=n);
printf("\n The value of %d! is:%d", printf("\n The value of %d! printf("\n The value of %d!
n,fact); is:%d", n,fact); is:%d", n,fact);
} } }
{ { {
printf (“Enter any variable either in lower printf (“Enter any variable either in
gets(scientist) ;
case or uppercase:”) lower case or uppercase:”);
puts(“print the
C = getchar () ; C = getc() ;
name”);
if (islower(C)) if (islower(C))
Putchar(toupper(C); Putc(toupper(C);
puts(scientist);
else else
Putchar(tolower(C); Putc(tolower(C);
} } }
Functions
Function is a set of instruction that are used to perform specified tasks which repeatedly occurs in
the main program.
Functions are 2 types,
o Pre defined functions.
o User defined functions.
Function definition
Defining its element and characteristics.
Function Declaration
Like the normal variables in a program, the function can also be declared before they defined
and invoked.
Syntax
Function call
The function can be called by simply specifying the name of the function,return value and the
parameters if presence.
func_name();
func_name(parameter);
return value=func_name(parameter);
TYPES OF VARIABLE
LOCAL AND GLOBAL VARIABLES
There are two kinds of varibles.
o Local variable. Global variables.
(i) Local variable:
The local variable are defined within the body of the function. These variables are defined
local to that function only or block only, other function cannot access these variables.
Eg:
Value (int a,int b)
{
int c, d;
}
c and d local variables.
2. Global variables.
Global variables are defined outside the main() function. multiple function can use these
variables.
Program to demonstrate local and global variables
#include<stdio.h>
#include<conio.h>
void main()
{
int i=0; Void f1(void)
void f1(); {
i=o; int k;
clrscr(); i=50;
printf(“value of i in main:%d\n”,i); }
f1(); Output:
printf(“value of i after call:%d\n”,i); Value of i in main:0
getch(); Value of i after call:50
}
RETURN statement
The return statement may or may not send back any values to main program.
The return statement can take the form:
Syntax:
return; or return(exp);
Eg:
if(x <= 0)
return(0);
else
return(1);
FUNCTION calling
A function can be called by simply using the function name in the statement.
Example:
main() message()
{ {
message(); printf(“function
printf(“main message”); message\n”);
} }
Calling Function Called Function
Function prototypes
The functions are classified into the following types depending on the arguments are present or
not and whether the value is returned or not.
These are also called function prototypes.
A function prototype declaration consists of the function return type, name and arguments list.
Prototype:
Function with no arguments & no return value.
Function with arguments & no return value.
Function no arguments & with return value.
Function with arguments & return value.
(i) Function with No Arguments and No Return Values
In this prototype, no data transfer takes place between the calling function and the called function.
i.e... The called program does not receive any data from the calling program and does not send
back any value to the calling program.
These functions act independently, i.e. they get input and display output in the same block.
Syntax
void add()
#include<stdio.h> {
main() int a, b, c ; /* Local definitions */
Sum is...30
(ii) Function with Arguments and No Return Values
In this prototype, data is transferred from calling function to called function but don‟t have return
values.
It is a one way data communication, i.e. the called program receives data from calling program
but it does not return any value to the calling program.
Syntax:
#include<stdio.h>
main() void add (int x, int y)
{ {
void add(int,int); int z;
int a,b;
z=x +y:
printf(“enter the values”);
scanf(“%d %d”,&a,&b); printf(“the sum is%d:”,
add(a,b) ; /* add function with argument */ z);
}
}
Output
Enter two number: 2 4
Sum is: 6
Syntax:
Output
Enter two number: 2 4
Sum is: 6
(iv) Function with arguments and return Value
In this prototype, the data is transferred between the calling function and called function.
Here data transfer takes place between the calling function and the called function as well as
between called function and calling function .
It is a two way data communication, i.e. the called program receives data from calling program
and it returns some value to the calling program.
Syntax:
#include <stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
int add(int,int); int add (int x, int y)
printf("\nEnter two number:"); {
scanf("%d%d", &a, &b); int z;
c=add(a,b); z=x+y;
printf("\nSum is:%d", c); return(z);
} }
Output
Enter two number: 2 4
Sum is: 6
1. Recursion
Recursion is the process of calling the same function itself again and again until some condition is
satisfied.
Syntax:
func1()
{
………..
func1();
…………
}
Output:
Output:
Enter value of x:5
Enter value of y:6
Values in the Function -->x=6,y=5
Values in the Main()-->x=5,y=6
#include <stdio.h>
#include<conio.h>
void main()
{
int x,y,change(int*,int*);
printf("\nEnter value of x:"); int change(int *a,int *b)
scanf("%d",&x); {
printf("\nEnter value of y:"); int c;
scanf("%d",&y); c=*a;
change(&x, &y); *a=*b;
printf("Values in the Main()-->x=%d, *b=c;
y=%d",x,y); printf("Values in the Function -->x=
} %d,
y=%d",*a,*b);
}
Output:
Enter value of x:5
Enter value of y:6
Values in the Function -->x=6,y=5
Values in the Main()-->x=6,y=5
ARRAYS
An array is a collection of similar data items that are stored under a common name in which each
element is located in separate memory locations.
Array index always start from „0‟
It is represented using [ ] – square brackets
FEATURES OF ARRAYS:
1. Array is a derived data type.
2. String array always terminates with null character ('\0').
3. Array elements are countered from 0 to n-1.
4. Array elements can be accessed with base address (index) and subscripts defines the position of the
element.
5. In array the elements are stored in continuous memory locations.
CLASSIFICATIONS OF ARRAY:
1. Single / One- Dimensional Array
2. Two – Dimensional Array
3. Multi – Dimensional Array
Array Declaration:
Syntax:
Data-type array-variable[array-size];
Eg: int X[4];
Address Element
1000 X[0]
1002 X[1]
1004 X[2]
1006 X[3]
Array Initialization:
Syntax:
Data-type array-variable[array-size]={list of values};
Example 1:
/* Array Initialization using Run time */
#include<stdio.h>
#include<conio.h>
void main()
{
int x[2],i;
printf("\nEnter the inputs:");
for(i=0;i<2;i++)
{
scanf("%d",&x[i]);
}
for(i=0;i<2;i++)
{
printf("\nThe value in x[%d] is %d",i,x[i]);
}
getch();
}
Output:
Enter the inputs:
3
6
The value in x[0] is 3
The value in x[1] is 6
Example 2:
/* Array Initialization using compile time */
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
char x[5]={'a','b','c','d','e'};
clrscr();
for(i=0;i<5;i++)
{
printf("\nThe value in x[%d] is %c",i,x[i]);
}
getch();
}
Output:
The value in x[0] is a
The value in x[1] is b
The value in x[2] is c
The value in x[3] is d
The value in x[4] is e
Array Declaration:
Syntax:
Data-type array-variable[row size][column size];
Array Initialization:
Syntax:
Data-type array-variable[row size][column size]={list of values};
Example :
/* Two dimensional Array */
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
int x[2][2]={ {1,50},{2,75}};
clrscr();
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf("\nThe value in x[%d][%d] is %d",i,j,x[i][j]);
}
}
getch();
}
Output:
The value in x[0][0] is 1
The value in x[0][1] is 50
The value in x[1][0] is 2
The value in x[1][1] is 75
#include <stdio.h>
#include <conio.h>
void main()
{
int a[10],i,min,max,n;
clrscr();
printf("Enter number of elements : ");
scanf("%d",&n);
printf("\nEnter Array Elements\n");
for(i=0; i<n; i++)
scanf("%d",&a[i]);
min = max = a[0];
for(i=1; i<n; i++)
{
if (max < a[i])
max = a[i];
if (min > a[i])
min = a[i];
}
printf("\nMaximum value = %d \n Minimum value = %d", max, min);
getch();
}
Output
Enter number of elements: 6
Enter Array Elements 115
38
-7
11
-9
0
Maximum value = 115
Minimum value = -9 43
Program
/* Matrix Manipulation*/
#include <stdio.h>
#include <conio.h>
void main()
{
int a[10][10], b[10][10], add[10][10],sub[10][10],mul[10][10],t[10][10];
int r1, c1, r2, c2;
int i, j, k;
clrscr();
}
}
}
printf("\nProduct matrix \n");
for(i=0; i<r1; i++)
{
for(j=0; j<c2; j++)
{
printf("%-4d",mul[i][j]);
}
printf("\n");
}
Output
Enter order of matrix A : 3 3
Enter order of matrix B : 3 3
C PROGRAMS
Example: 1/*Calculate Total and Average*/
# include <stdio.h>
# include <conio.h>
Void main ( )
{
int r,b,c,d, tot, avg;
clrscr();
printf (“ENTER STUDENT RNO ; “);
scanf (“%d”,&r);
printf(“ENTER FIRST SUBJECT MARKS ;”);
scanf(“%d”,&b);
printf(“ENTER SECOND SUBJECT MARKS;”);
scanf(“%d”,&c);
printf(“ENTER THIRD SUBJECT MARKS ;”);
scanf(“%d”,&d);
tot=b+c+d;
avg=tot/3;
printf(“\n\n\t\t STUDENT DETAILS \n\n”);
printf(“\t STUDENT RNO ; %d “,r);
printf(“\t FIRST SUBJECT MARKS ;%d “,b);
printf(“\t SECOND SUBJECT MARKS ;%d “,C);
printf(“\t THIRD SUBJECT MARKS ;%d “,d);
}
Example: 2/*Biggest of two nos*/
#include<stdio.h>
#include<conio.h>
Void main ( )
{
int a,b;
printf("\n\nenter the value of a,b : ");
scanf("%d %d",&a,&b);
if(a>b)
printf("\n\n%d is big",a);
else
printf("\n\n%d is big",b);
getch( );
}
Example: 3 /*Biggest of three no*/
#include<stdio.h>
#include<conio.h>
Void main ( )
{
int a,b,c;
printf("\n\nenter the value of a,b,c : ");
scanf("%d %d %d",&a,&b,&c);
if(a>b)
{
if(a>c)
printf("\n\n%d is big",a);
else
printf("\n\n%d is big",c);
}
Else
{
if(b>c)
printf("\n\n%d is big",b);
else
printf("\n\n%d is big",c);
}
getch( );
}
else if(avg>60&&avg<=70)
printf(“You got C Grade- Congtrats !”);
else if(avg>50&&avg<=60)
printf(“You got D Grade- Congtrats !”);
else
printf(“You got U Grade- Sorry !”);
getch( );
}
{
int n, i=1, a=0,fib=1;
clrscr( );
printf(“Enter the limit to find Fibonacci:”);
scanf(“%d”,&n);
printf(“ Fibonacci Series \n“);
printf(“%d\n”,a);
printf(“%d\n”,fib);
while(i<n)
{
fibo=a+fib;
a=fib;
fib=fibo;
i=i+1;
printf(“%d\n”,fibo);
}
getch( );
}
Example 12./* To find the roots of the quadratic equation */
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int a,b,c,d;
float root1,root2;
printf(“Enter the values of a,b,c\n”);
scanf(“%d %d %d”,&a,&b,&c);
d=b*b-4*a*c;
if(d>=0)
{
root1=(-b+sqrt(d))/(2*a);
root2=(+b+sqrt(d))/(2*a);
printf(“root1= %f/n root2=%f”,root1, root2);
}
else
printf(“The roots are imagenary”);
getch();
}
OUTPUT:
Enter the values of a,b,c 1 0 -9
root1=3.000000
root2=3.000000
#include<stdio.h>
#include<conio.h>
int main()
{
int N, i, j, isPrime, n;
printf("To print all prime numbers between 1 to N\n");
printf("Enter the value of N\n");
scanf("%d",&N);
printf("Prime numbers between %d to %d\n", 1, N);
{
if(str[i]!=str[j])
{
printf("\n The String is not a palindrome");
getch();
exit(0);
}
}
printf("\n The String is a palindrome");
getch();
}
Output:
Enter the string: abcba
The String is a palindrome
**************************