Unit 1
Unit 1
Unit 1
BASICS OF C PROGRAMMING
PART A
1. What is external storage class? [APR/MAY 2018]
An external variable definition must be defined outside the functions. That
access the external variables and usually before the function definitions. The
external variables can be accessed from the point of its definition to any within
the program.
An external variable declaration must begin with the storage class
specified extern.
2. How does the preprocessor work? [APR/MAY 2018]
Preprocessor is a program that processes the source code before it passes
through the compiler. This is known as preprocessor.
It operates under the control of preprocessor command lines or directives.
Preprocessor directives are placed in the source program before the main
line.
Before the source code passes through the compiler, it is examined by the
preprocessor for any preprocessor directives.
Preprocessor directives begin with the symbol # in column and do not
require a semicolon at the end.
Arithmetic operators:
Binary operators
Unary operators
Binary operators:
operator meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo operation
Example program:
#include<stdio.h>
#include<conio.h>
void main()
clrscr();
printf(“\n Addition=%d”,a+b);
printf(“\n Subtraction=%d”,a-b);
printf(“\n Multiplication=%d”,a*b);
printf(“\n Division=%d”,a/b);
printf(“\n Modulo=%d”,a%b);
getch();
Unary operator:
The operators that acts upon a single operand to produce a new value are
called as unary operators. Unary operators usually precede its operands, though
some unary operators are written after their operators.
+ Unary plus
- Unary minus
++ Increment
-- Decrement
sizeof Return the size of the operand
& Address operator
Example:
sizeof operator
The sizeof operator is not a library function but a keyword, which returns
the sizeof the operand in bytes. The Sizeof operator always procedes its
operand.
Expression Result
sizeof(char) 1
sizeof(int) 2
sizeof(float) 4
sizeof(double) 8
Ampersand operator
The ampersand operator ‘&’ prints the address of the variable in the memory.
Relational operators:
Relational operators are symbols that are used to test the relationship
between two variables or between a variable and a constant.
operator meaning
< less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== equal to
!= Not equal to
Example:
#include <stdio.h>
main() /* Program introduces the for statement, counts to ten */
{
int count;
Logical Operator:
Operators which are used to combine two or more relational operations
called logical operators. These operators are used to test more than one
condition at a time.
Operators Meaning
&& Logical AND
|| Logical OR
! Logical NOT
#include <stdio.h>
main()
{
int number;
int valid = 0;
while( valid == 0 )
{
printf("Enter a number between 1 and 10 -->");
scanf("%d", &number);
if( (number < 1 ) || (number > 10) )
{
printf("Number is outside range 1-10. Please re-enter\n");
valid = 0;
}
else valid = 1;
}
printf("The number is %d\n", number );
}
Assignment operator:
Assignment operators are used to assign the result of an expression to a
variable. The equal(=) sign is used as an assignment operator. It is used to form
an assignment expression, which assigns the value of an expression to an
identifier which may be written in the form of
identifier= expression
1. increment (++)
2. decrement (--)
Operator meaning
++x pre-increment operation
x++ post-increment operation
--x pre-decrement operation
x-- post-decrement operation
Conditional operator:
Syntax:
Bitwise operator:
Bitwise operator is used to manipulate the date at bit level. It operates only
integers.
Operator Meaning
~ One’s Complement
<< Left Shift
>> Right Shift
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
The one’s complement operator (~) is an unary operator which causes the
bits of the operand to be instead. ie., one’s become zero’s and zero’s
become one’s.
Program:
#include<stdio.h>
void main()
int a;
scanf(“%d”,&a);
getch();
Comma operator:
Example:
#include <stdio.h>
void main()
{
int n, reverse = 0, t;
scanf("%d", &n);
t = n;
while (t != 0)
t = t/10;
if (n == reverse)
else
return 0;
C has some kind of statements that permit the execution of a single statement ,
or a block of statements, based on the value of a conditional expression or selection
among several statements based on the value of a conditional expression or a
control variable.
i) if statement
ii) if-else statement
iii) nested if-else statement
iv) if else-if statement
v) switch case statement
i) if statement:
It is also known as one-way decisions. It is used to control the flow of
execution of the statements. The decision is based on a “test expression
or condition” that evaluates to either true or false.
If the test condition is true, the corresponding statement is
executed.
If the test condition is false, control goes to the next executable
statement.
Syntax:
if(expression)
block of statements;
}
#include <stdio.h>
int main()
{
int number;
printf("Enter an integer: ");
scanf("%d", &number);
// Test expression is true if number is less than 0
if (number < 0)
{
printf("You entered %d.\n", number);
}
printf("The if statement is easy.");
return 0;
}
Output 1
Enter an integer: -2
You entered -2.
The if statement is easy.
Output 2
Enter an integer: 5
The if statement is easy.
#include <stdio.h>
int main()
{
int number;
printf("Enter an integer: ");
scanf("%d",&number);
// True if remainder is 0
if( number%2 == 0 )
printf("%d is an even integer.",number);
else
printf("%d is an odd integer.",number);
return 0;
}
Output
Enter an integer: 7
7 is an odd integer.
SYNTAX:
if(expression1)
{
statement1:
}
else
{
If(expression2)
{
satatement2;
}
else
{
statement3;
}
}
#include <stdio.h>
int main()
{
int number1, number2;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);
return 0;
}
Output
iv) if else-if:
SYANTAX:
if(expression1)
{
statement1;
}
else if(expression2)
{
statement2;
}
else if(expression3)
{
Statement3;
}
else
{
statement4;
}
Flowchart:
Program:
#include <stdio.h>
int main()
{
int var1, var2;
printf("Input the value of var1:");
scanf("%d", &var1);
printf("Input the value of var2:");
scanf("%d",&var2);
if (var1 !=var2)
{
printf("var1 is not equal to var2\n");
}
else if (var1 > var2)
{
printf("var1 is greater than var2\n");
}
else if (var2 > var1)
{
printf("var2 is greater than var1\n");
}
else
{
printf("var1 is equal to var2\n");
}
return 0;
}
Output:
v) switch case:
SYNTAX:
switch<exprn>
{
case 0:
{
statement ;
break;
}
case 1:
{
statement ;
break;
}
case 2:
{
statement ;
break;
}
case n:
{
statement ;
break;
}
default:
{
statement;
break;
}
}
The switch() case statement is like the if statement that allows us to make the
decision from a number of choices. The switch statements require only one
argument of any data type, which is checked with a number of case options.
The switch statement evaluates the expression and then looks for its value
among the case constants. If the value matches with a case constant, this
particular case statement is executed. If not, the default is executed .
Example:
// Program to create a simple calculator
// Performs addition, subtraction, multiplication or division depending the input
from user
# include <stdio.h>
int main()
{
char operator;
double firstNumber,secondNumber;
printf("Enter an operator (+, -, *, /): ");
scanf("%c", &operator);
printf("Enter two operands: ");
scanf("%lf %lf",&firstNumber, &secondNumber);
switch(operator)
{
case '+':
printf("%.1lf + %.1lf = %.1lf",firstNumber, secondNumber,
firstNumber+secondNumber);
break;
case '-':
printf("%.1lf - %.1lf = %.1lf",firstNumber, secondNumber, firstNumber-
secondNumber);
break;
case '*':
printf("%.1lf * %.1lf = %.1lf",firstNumber, secondNumber,
firstNumber*secondNumber);
break;
case '/':
printf("%.1lf / %.1lf = %.1lf",firstNumber, secondNumber,
firstNumber/firstNumber);
break;
// operator is doesn't match any case constant (+, -, *, /)
default:
printf("Error! operator is not correct");
}
return 0;
}
Output
Enter an operator (+, -, *,): -
Enter two operands: 32.5
12.4
32.5 - 12.4 = 20.1
1. for statement:
The for loop allows to execute a set of instructions until a certain condition
is satisfied.condition may be predefined or open-ended.
Syntax:
for(<initial value>;<condition>;<incrementation/decrementation>)
block of statement;
}
Here the initial value means the starting value assigned to the variable and
condition in the loop counter to determine whether the loop should continue or not.
Incrementation/ decrementation is to Increment/decrement the loop counter value each
time the program segment has been executed.
Program:
#include<stdio.h>
void main()
int i,n;
scanf(“%d”,&n);
for(i=1;i<=n;i++)
printf(“%d\n”,i;
getch;
}
Output:
2. while statement:
Syntax:
while(condition)
Block of statement;
increment/decrement;
If the test expression is true (nonzero), codes inside the body of while loop are
executed. The test expression is evaluated again. The process goes on until the
test expression is false.
#include<stdio.h>
void main()
int i,n;
scanf(“%d”,&n);
i=1;
while(i<=n)
if(i%2==0)
printf(“%d\t”,i);
i++;
}
getch();
Output:
2 4 6 8 10
3. do-while statement:
The do-while loop varies from the while loop in the checking condition. The
condition of the loop is not tested until the body of the loop has been
executed once. If the condition is false, after the first iteration the loop
terminates. The statement are executed atleast once even if the condition
fails for the first time itself. It is otherwise called as exit control loop.
Syntax:
do
{
statement;
}while(condition);
Program:
#include<stdio.h>
#include<conio.h>
void main
{
int a,b,c,r;
clrscr();
printf(“Enter the range:”);
scanf(“%d”,&r);
a=0; b=1;
printf(“%d”,a);
printf(“\n%d”,b);
printf(“\n”);
c=0;
do
{
c=a+b;
if(c<=r)
printf(“%d\n”,c);
a=b;
b=c;
}while(c<=r);
getch();
}
OUTPUT:
Enter the range: 10
0
1
1
2
3
5
8
documentation section
preprocessor section
definition section
global declaration section
main
{
declaration part
executable part
}
sub program
{
Body of the program
}
Documentation section
Preprocessor section
Example
#include<stdio.h>
#include<conio.h>
#include<string.h>
Definition section
Example
#define PI 3.41
#define x (x*x*x)
Example
int a;
main()
{
………….
………….
main() function
Each and every C program should have only one main() function.
Without main() function, the program cannot be executed.
The main function should be written in lowercase only.
It should not be terminated with semicolon.
Declaration part
Each and every variable should be declared before going to use those variables
in execution part.
Execution part
Subprogram section
The subprogram section contains all the user-defined functions that are called in
the main() function.
User defined functions are generally placed immediately after the main() function,
although they may appear in any order.
Example Program
int b;
c=sum(b);
getch();
int sum(int y)
Return(c);
#include<ctype.h>
Similarly the getc(), getch() and getche() functions can be used for reading a
character.
Writing a character
The function putchar() is used for writing characters one at a time to the
terminal. The general form of the putchar() function is
Putchar(variable_name);
Where variable_name is a char type variable. This statement displays the
character contained in the variable at the terminal.
Similarly the putc and outch() functions can be used for writing a character.
For example,
char c;
c= ‘x’;
putchar(c);
will display the character x on the screen.
The statement
putchar(“\n”);
would cause the cursor on the screen to move to the beginning of the next
line.
Example program:
#include<stdio.h>
void main()
char c;
do
c=getchar();
putchar(c);
}while(c!=’\n’);
getch();
#include<stdio.h>
void main()
char a[10];
gets(a);
gets(a);
getch();
Output:
The gets() and puts() functions are similar to the scanf() and printf() function but
the difference is in scanf() input statements. When there is a blank space in tnput
text, then it takes the space as encoding the string, the remaining string is not taken.
Example program:
#include<stdio.h>
void main()
int a,b,c;
scanf(“%d%d%d”,&a,&b,&c);
The control string should be used that are relevant to corresponding variable.
The control strings are enclosed with double quotes.
No.Of input variables are used that are separated by comma.
Variable are preceded with (&) sign except string variable.
The control strings and variables should match with each other.
Scanf() statement should terminated with semi-colan(;).
Printf() function is used to print the character, string, float, integer, octal
and hexa decimal values on to the output screen.
We use printf() function with %d format specifier to display the value of an
integer variable
Similarly %c is used to display the character, %f for float variable, %s for
string variable, %1f for double and %x for hexadecimal variable.
To generate a newline, we use “\n” in C printf() statement.
8. Explain about Pre-processor and its directives?
Preprocessor is a program that processes the source code before it passes
through the compiler. This is known as preprocessor.
It operates under the control of preprocessor command lines or directives.
Preprocessor directives are placed in the source program before the main
line.
Before the source code passes through the compiler, it is examined by the
preprocessor for any preprocessor directives.
Preprocessor directives begin with the symbol # in column and do not
require a semicolon at the end.
Syntax:
#define COUNT 50
#define FALSE 0
#define SUBJECTS 4
#define PI 3.14
#define A (55-33)
#define B (55+33)\
#define AND
volume= (side*side*side)
Nesting of macro:
We can also use one macro in the definition of another macro. That is
macro definition may be nested.
#define M 5
#define N M+1
Undefining a macro
#undef identifier
Where the file name is the name of the file containing the required definitions or
functions.
Example:
#include<stdio.h>
#include<conio.h>
#include “SYNTAX.C”
Main()
………….
…………..
These are the directives meant for controlling the compiler actions. A
preprocessor offers a feature known as conditional compilation, which can be used to
switch off or on a particular line or group of lines in a program.
Preprocessor
Preprocessor processes the program before compilation. Preprocessor
include header files, expand the macros.
Compiler
The generated output files after preprocessing (with source code) will be
passed to the compiler for compilation. Compiler will compile the program,
checks the errors and generates the object file (this object file contains
assembly code).
Linker
Linker links the more than one object files or libraries and generates the
executable file.
Loader
Loader loads the executable file into the main/ primary memory and program
run.
Preprocessor reads the file and generates the sample.i file, this file
contains the preprocessed code (expanded source code).
Compiler reads the sampli.i file and converts into assemply code and
generates sample.s and then finally generates object code in sample.o file.
Linker reads sample.o file and links the other assemply/object code or
library files and generates executable file named sample.exe.
Loader loads the sample.exe file into the main/primary memory and then
it is executed. After the execution, output is sent to console. One more file is
created that contains the source code named sample.bak; it’s a backup file of the
program files.
10. Write the program to find the given number is even or odd?
#include <stdio.h>
int main()
{
int number;
printf("Enter an integer: ");
scanf("%d",&number);
// True if remainder is 0
if( number%2 == 0 )
printf("%d is an even integer.",number);
else
printf("%d is an odd integer.",number);
return 0;
}
Output
Enter an integer: 7
7 is an odd integer.
11. Write the program to find the Fibonacci serious for the given range?
#include<stdio.h>
#include<conio.h>
void main
{
int a,b,c,r;
clrscr();
printf(“Enter the range:”);
scanf(“%d”,&r);
a=0; b=1;
printf(“%d”,a);
printf(“\n%d”,b);
printf(“\n”);
c=0;
do
{
c=a+b;
if(c<=r)
printf(“%d\n”,c);
a=b;
b=c;
}while(c<=r);
getch();
}
OUTPUT:
Enter the range: 5
0
1
1
2
3
5