STUCOR_CS3251-HS
Syllabus
- SUBJECT CODE/NAME: CS3251 - PROGRAMMING IN C
- Topics:
- UNIT I: BASICS OF C PROGRAMMING
- UNIT II: ARRAYS AND STRINGS
- UNIT III: FUNCTIONS AND POINTERS
- UNIT IV: STRUCTURES AND UNION
- UNIT V: FILE PROCESSING
- ANNA UNIVERSITY QUESTION PAPERS R21/R17
CS3251 - PROGRAMMING IN C - SYLLABUS
- COURSE OBJECTIVES:
- Understand C Language constructs.
- Develop C Programs using basic constructs.
- Develop C programs using arrays and strings
- Develop modular applications in C using functions
- Develop applications in C using pointers and structures
- Perform input/output and file handling in C
- UNIT I: BASICS OF C PROGRAMMING
- Introduction to programming paradigms
- Applications of C Language
- Structure of C program
- C programming: Data Types, Constants, Enumeration Constants, Keywords
- Operators: Precedence and Associativity, Expressions
- Input/Output statements, Assignment statements, Decision making statements, Switch statement, Looping statements
- Preprocessor directives
- Compilation process
- UNIT II: ARRAYS AND STRINGS
- Introduction to Arrays: Declaration, Initialization
- One dimensional array
- Two dimensional arrays
- String operations: length, compare, concatenate, copy
- Selection sort, linear and binary search
- UNIT III: FUNCTIONS AND POINTERS
- Modular programming
- Function prototype, function definition, function call
- Built-in functions (string functions, math functions)
- Recursion, Binary Search using recursive functions
- Pointers
- Pointer operators
- Pointer arithmetic
- Arrays and pointers
- Array of pointers
- Parameter passing: Pass by value, Pass by reference
- UNIT IV: STRUCTURES AND UNION
- Structure
- Nested structures
- Pointer and Structures
- Array of structures
- Self referential structures
- Dynamic memory allocation
- Singly linked list
- typedef
- Union
- Storage classes and Visibility
- Structure
- UNIT V: FILE PROCESSING
- Files
- Types of file processing:
- Sequential access
- Random access
- Sequential access file
- Random access file
- Command line arguments
- COURSE OUTCOMES:
- CO1: Demonstrate knowledge on C Programming constructs
- CO2: Develop simple applications in C using basic constructs
- CO3: Design and implement applications using arrays and strings
- CO4: Develop and implement modular applications in C using functions.
- CO5: Develop applications in C using structures and pointers.
- CO6: Design applications using sequential and random access file processing.
- TEXT BOOKS:
- 1. ReemaThareja, "Programming in C", Oxford University Press, Second Edition, 2016.
- 2. Kernighan, B.W and Ritchie, D.M, "The C Programming language", Second Edition, Pearson Education, 2015.
- REFERENCES:
- 1. Paul Deitel and Harvey Deitel, "C How to Program with an Introduction to C++", Eighth edition, Pearson Education, 2018.
- 2. Yashwant Kanetkar, Let us C, 17th Edition, BPB Publications, 2020.
- 3. Byron S. Gottfried, "Schaum's Outline of Theory and Problems of Programming with C", McGraw-Hill Education, 1996.
- 4. Pradip Dey, Manas Ghosh, "Computer Fundamentals and Programming in C", Second Edition, Oxford University Press, 2013.
- 5. Anita Goel and Ajay Mittal, "Computer Fundamentals and Programming in C", 1st Edition, Pearson Education, 2013
UNIT I - BASICS OF C PROGRAMMING
- Introduction to programming paradigms
- Applications of C language
- Structure of C Program
- Data types
- Constants
- Enumeration Constants
- Keywords
- Operators: precedence and Associativity
- Expression
- Input / output Statements, Assignment Statements
- Decision making statement
- Switch statement
- Looping Statement
- preprocessor directives
- Compilation process
PART-A
1) What is the importance of keyword?
- Keywords are reserved words already explained to the Compiler.
- Keywords are also called reserved words.
- Examples:
auto,else,long,for,float,int,char,continue,goto, etc.
2) What do you mean by C tokens?
- The smallest individual units of a C Program are known as C tokens.
- Examples: keywords, identifier, constants, string, operators, special character.
3) What are variables? Give example.
- A variable is an identifier used to represent a specific type of information within a portion of the program.
- Example:
int Sum;number = 10;
4) Write a loop statement to print 10 to 1.
```c
#include <stdio.h>
void main()
{
int i;
for(i = 10; i >= 1; i--)
printf("%d", i);
}
```
5) Give the use of pre processor.
- A pre processor is a translator that converts a program written in one high-level language into an equivalent program written in another high-level language.
6) Difference between while and do…while
| While | do… while |
|---|---|
| This is the top tested loop | This is bottom tested loop |
| The condition is first tisted | It executes the body once, after it checks the condition |
| Loop will not be executed if condition false | Loop is executed at least once, even if the condition is false |
7) What is the use of "break" statement?
- The break statement is used to terminate the loop.
- When the keyword
breakis used inside any loop, control is automatically transferred to the first statement after the loop.c while (condition) { if (condition) break; }
8) Define delimiters in C
#- Pre-Processor directive,- Comma - Separate list:- Colon - Label delimiters;- Semicolon - Statement delimiter()- Parenthesis - Used in expression{}- Curly braces - Used blocking[]- Square braces - Used with arrays
9) What is the use of #define processor
- The
#definepreprocessor directive is used to define a global constant or macro.c #define PI 3.14 #define big(a,b) ((a) > (b) ? (a) : (b)) - When a Compile reads the macro name, it replaces the macro name by its expression.
- When it reads the constant label, it replaces the label by its value.
10) List out various Input & output statements in c
- The input & output statements are classified into formatted & unformatted I/O.
- Formatted I/O: User can design / format the output.
scanf(),printf()
- Unformatted I/O: doesn't allow the users to design the output.
getch(),gets(),putch(),puts()
- Formatted I/O: User can design / format the output.
PART B
1) Explain the decision making statement in C with example programs.
- Decision making is about deciding the order of execution of statements based on certain conditions.
- C language handles decision-making by supporting the following statements:
Simple-if statement:
- The
ifstatement is a selection statement, simplest form of decision making.c if (condition) { Statement; }c #include <stdio.h> void main() { int n; printf("Enter the number"); scanf("%d", &n); if (n > 0) printf("No is positive"); }
If-else Statement:
- If else statement evaluates the condition, if it is true, the true block will be executed, otherwise, the false block will be executed.
c if (condition) { statement 1; } else { statement 2; }c #include <stdio.h> #include <conio.h> void main() { int n; printf("Enter number"); scanf("%d", &n); if (n > 0) printf("No is positive"); else printf("No is negative"); }
Nested-if
- If one or more if statements are embedded within the
ifStatement is called nested if statement.c if (condition1) { if (condition2) { if (condition3) { Stmt3; } } else stm2; } else stm1;c #include <stdio.h> void main() { int a, b, c; printf("Enter three numbers"); scanf("%d%d%d", &a, &b, &c); if (a > b) { if (a > c) printf("A is big"); else printf("c is big"); } else { if (b > c) printf("B is big"); else printf("c is big"); } }
if-else-if ladder:
- Control structure to represent multiple condition scenarios.
c if (cond1) stm1; else if (cond2) stm2; else if (cond3) stm3; else default_stm;c #include <stdio.h> void main() { int avg; printf("Enter the avg marks"); scanf("%d", &avg); if (avg > 90) printf("O Grade"); else if (avg > 80) printf("A+ Grade"); else if (avg > 70) printf("A Grade"); else if (avg > 60) printf("B+ Grade"); else if (avg >= 50) printf("B Grade"); else printf("Fail"); }
Switch case statement:
- The switch case statement is a multiple branching (multiple decision making) statement.
- The switch Statement Select a particular group of statements from several available groups.
c switch (exp) { case const1: Stmt; break; case Const2: Stmt; break; default: stmt; }c #include <stdio.h> void main() { int a, b, c; char op; printf("+ Add\n - Sub\n * mul \n"); printf("Enter the case value"); scanf("%c", &op); printf("Enter the values"); scanf("%d%d", &a, &b); switch (op) { case '+': c = a + b; break; case '-': c = a - b; break; case '*': c = a * b; break; } printf("Result = %d", c); }
2) Explain the looping statement in c with example programs.
- Looping is the process of repeating the same set of statements again and again until the specified condition hold true.
- Loop Types:
- Counter Controlled
- Sentinel Controlled
- Counter Controlled Loop: The number of iterations to be performed is known in advance; also called a definite repetition loop.
- Sentinel Controlled Loop: The number of iterations to be performed is not known in advance; also called an indefinite repetition Loop.
- Looping Statements:
- while loop
- do..while loop
- for loop
while loop:
- Entry controlled loop.
c initialization; while (Condition) { Body of the loop; inc/dec; }c #include<stdio.h> void main() { int n = 0; while (n <= 5) { Printf("%d", n); n++; } }
do…while loop:
- Exit Controlled loop because the test condition is evaluated at the end the loop.
- The body of the loop gets executed at least one time.
c initialization; do { body of loop; inc/dec; } while (cond);c #include <stdio.h> void main() { int n = 0; do { printf("%d", n); n++; } while (n <= 5); }
For loop:
- It is definite loop. It is used to execute a set of instructions repeatedly, until the condition becomes false.
c for (initialization; condition; increment /decrement) { body of the loop; }c #include <stdio.h> void main() { int i; for (i = 1; i <= 5; i++) { printf("%d", i); }
Nested for loop:
- The loop within the loop is called husted loop.
- Iterations is equal to the number of iterations in the outer loop multiplied by the number of iteration in the inner loop.
c #include <stdio.h> void main() { int i, j; for (i = 1; i <= 3; i++) { printf("\n"); for (j = 1; j <= 3; j++) Printf("%d", j); }
3) Explain different types of operators in c with example programs.
- An operator is a symbol that specifies an operation to be performed on the operand. An operand is defined as a variable (data items).
- Types of operator:
- Arithmetic Operator
- Relational operator
- Logical operator
- Assignment operator
- Increment / decrement operator
- Conditional operator
- Bitwise operator
- Special operator
Arithmetic operator:
- Allows to carryout basic arithmetic operations like addition, subtraction, multiplication and division.
c #include <stdio.h> void main() { int a = 5, b = 3; printf("Sum=%d", a + b); printf("Diff=%d", a - b); printf("Mul = %d", a * b); printf("Div = %d", a / b); Printf("Modular Div: %d", a % b); }
Relational Operator:
- (
- Relational operators are used to Compare two or more operands. Operands may be var, Constant, Expressions. The result of relational expression is either one (01) zero.
c #include <stdio.h> void main() { int a = 5, b = 10; printf("a>b=%d", a > b); printf("a!=b%d", a != b); printf(" a <= b = %d", a <= b); }
Logical operator:
- (&&, ||, !)
- are used to Compare two or more conditions.
| Operator | Meaning | Eg | |
|---|---|---|---|
&& | logical AND | (9>2) && (5<2) | |
|| | logical OR | (5>2) || (5==4) | |
! | logical NOT | !(5!=2) | |
c
#include <stdio.h>
void main()
{
int a = 9, b = 2, c = 5;
Printf("%d", (a > 2) && (c < b));
Printf("%d", (a > 2) || (b < c));
Printf("%d", !(a > 2));
}
| |||
Assignment operator: |
are used to assign a value of a Variable to another variable.
var = exp;
Compound assignment:
- c Provides compound assignment operator to assign a value to the variable in order to assign a new value to variable after performing a specified operation.
| Example | Meaning | |
|---|---|---|
x += y | x=x+y | |
x -= y | x=x-y | |
x *= y | x=x*y | |
x /= y | x=x/y | |
x %= y | x=x%y | |
c
#include <stdio.h>
void main()
{
int a = 50, b = 5;
b += a;
Printf("%d", b);
}
| ||
Nested co. Multiple Assignment: |
- assign a single value to multiple variables.
Varl = var2 = var3 = exp
Increment and Decrement Operator (Unary oprty):
- The increment operator
++adds one to the variable and decrement operator Subtract one from the variable.
| Operator | Meaning | |
|---|---|---|
++a | Pre-Increment | |
a++ | post-Increment | |
--a | pre-decrement | |
a-- | post-decrement | |
c
Void main ()
{
int a = 5;
printf ("%d", a++);
printf("%d", ++a);
printf("%d", --a);
}
| ||
Conditional operator (os) Ternary operator: |
- operator, It check the Conditim, If it is true, expl is evaluated. If it is false empa is evaluated.
Condition ? exp1 : exp2;
#include <stdio.h>
void maint()
{
int a = 5, b = 3, big;
printf("Brgrid", big = a > b ? a : b);
Printf ("Big %d", big);
}
```
#### Bitwise Operator:
* is used to manipulat the data at bit level.
| Operator | Meaning |
| :------- | :-------------- |
| `&` | Bitwise AND |
| `\|` | Bitwise OR |
| `^` | Bitwise XOR |
| `<<` | Shift left |
| `>>` | Shift Right |
| `~` | Onis Complement |
c
#include
void main()
{
int n = 7, y = 8;
printf("n&y: %d", n & y);
printf("n|y: %d", n | y);
printf("x^y:%d", n ^ y);
}
#### Special operator:
* Member ulation operator `(., ->)` used to access elements from a Structure.
* Comma operator `(,)` used to separate the Statment elements such as var, Constants, exp.
* Size of` ()` Operator: Return the length of the specified variable.
* Pointer operator: `(&, *)` `&` specify address of variable. `*` Specify value of the variable
### 4) Explain about Ilo Statements in & with example program
* The input \ output function permit the transfer between the Computer and the Standard input/output devices.
* It classified into two types.
* Formatted Ilo statements
* `scanf()`
* `printf()`
* Unformatted Ilo Statements
* `gets()`
* `getchar()`
* `putcha()`
* `puts()`
* It is simplest form of all input/output operations are reading a character from the Standard input unit and writing it to the standard output unit.
#### getchar():-
* It reads a single character from a standard input device ( keyboard).
```c
Var-name = getchar();
```
#### getche():-
* read a Single keyboard.
* is displayed on the output screen without waiting for the press they enter key.
```c
Var-name = getchers;
```
#### Putchar():-
* Single character can be displayed
```c
putchar (var-name);
```
#### gets():-
* It is accept the name of the String as a parameter, till a newline character is encountered.
```c
gets (str);
```
#### puts():-
* It is used to display the string to the standard output device.
putsc):
c
puts (str);
```
5) Write short note on following statements i) goto ii) break iii) Continue
- The inconditional Statument transfer the control from one point to another without checking any condition.
goto statement:
- The goto statement is used to branch unconditionally from one point to another point in the program.
- The goto statement require lable in order to identify the place where the control to be transferred.
goto label;
label:
```c
#include <stdio.h>
void main()
{
int a = 50, b = 20;
if (a > b)
goto big;
else
printf("B is big");
big: printf("A is big");
}
```
Break Statement:-
- It is used to terminate the loop, where the keyword
breakis used inside any c loop.
break;
```c
#include <stdio.h>
void main()
{
for (i = 1; i <= 5; i++)
{
if (i == 3)
break;
Printf("%d", 1);
}
}
```
Continue Statement:-
- used to nest iteration of loop statement when it occur in the loop.
- It skip the Statement after this statement.
Continue;
```c
include
void main()
{
int i;
for(i=1;i<= 5; i++)
{
if(i==3)
Continue;
Printf("%d", i);
}
}
### 6) Explain the structure of a C program
* Documentation Section
* Pre processor Section
* Definition Section
* Global declaration Section
* main() function section
{
declaration part;
Executable part;
}
* Subprogram Section user defined
{
body
}
#### Documentation Section:
* The documentation section consist of Comment lines giving the name of program and other detail.
* Comment is a non-executable statement. It is placed between /* and */
### Pre processor Section:-
* In a pre processor section which direct the compile to link functions from the system library.
```c
#include <stdio.h>
#define P2 3.14
```
#### Global declaration Section :-
* There are some variable that are used more than One function. Such variables are called global variable and are declared in the global declaration section.
* It is declared outside all the functions.
#### Function main():-
* must Contain two parts.
* Declaration part
* Executable part
* Declaration part contains the statements following main. It declares all the variable used in the progam
* Enecutable part Contain the statements declaration part. Here logic of the they provide a instruction to the Computer to perform a specific task.
#### Subprogram Section :-
* It contains all the defined functions that are called in the main function.
* User defined functions are generally placed immediatly after the main function., although they may appear in any order.
```c
/* Sum of two numbers */Document Section
#include <stdio.h> Preprocessor Section
#define A 5 Definition Seelim.
int c; Global variable declaration.
int add (int); //prototyping
main()
{
int b; //variable declaration
printf("Enter the value of b");
scanf (" %d", &b);
c=add(b); //function calling
printf("Sum=%d", c);
}
int add (int b)
{
c = A+b;
return c;
}
Applications of C:
- Used in operating system
- Used in GUI
- Used in New Programming platform
- Used in Embedded system
- Used in Compitur design
- Used in Gaming and Animation
7) Explain the different types of data available in C
- Datatypes are the type of data, that are going to access within the program.
- c supports different data types, each data type may have predefined memory requirement and storage representation.
Primary datatype:-
intfloatdoublechar
Intigers:-
- are the numbers with supported range.
- Integer occupied one word of storage. Sizes of integers vary from 16 bit or 32 bits.
c int a
Float :-
- floating point number are stored in 32 bit, with 6 digits precision.
- It is used to store numeric values with decimal point.
c float n
Double:-
- number uses 64 bit giving a precision of 14 digits, known as double precision number.
c double y
Character:-
- A single character can be defined as char datatype character are usually stored in 8 bit.
c char a;
Type qualifier:
- Sort
- Long
- Signed
- Unsigned
- The declaration of long and unsigned integer permits increase the range of values.
User defined datatype - User defined datatype is used to Creat New data typer, `type allows declaration user to define an identifier that would represent an existing datatype.
Syntax:- typedef type identifier. - type refers to the existing datatype,
- identifier refers to new name given to the datatype
typedef int marks
Another user defined datatype is enumerated data type.
Syntan:
enum identifier { vari, var2,...varn }
enum day { Monday, Tuusday, Wednesday }
enum Color { blue=2, black=0, green = 1 }
Derived datatype:
Datatype that are derived from fundamental datatype are Called derivea datatype. Derived datatype add some ofunctionality to the basic datatypes.
Array: Collection of variables of sametype
Pointer: Hold a memory address of another variable
Structure: Collection of variables under Single name
Union: Multiple values of different data types under a same name.
Void datatype is used to represent
an empty or null value
C program to find Square root of value
#include <stdio.h>
Void main()
{
float n; `
printf ("Entor n value");
scanf (“%-f", &n) ;
Printf (“Square root is %f",asqrt(x);
}
UNIT - II ARRAYS AND STRINGS
- Introduction to Arrays;
- Declaration, initialization - One Dimensional array-
- Two dimensional array
- String Operations, length, Compare, Concatenate, Copy-
- Selection Sort, linear and bisary Search.
PART-A
1) What is an array? Write down the Syntax for array declaration (AU- Apr/May - 2022).
- Array is a collection of of Similar type All Values are stored in Continuous memory Locations. All Values share a Common name.
- The elements are Organized in sequential area.
Syntax : datatype array-name [size];
Example:
int a [10];
2) Write a c function to compare two Strings
- Strcmp() function is Used to Compares two strings two strings are Compared Character by character.
- If the function returns 0 Value. Otherwise it returns the numerical difference between the first matching characters.
Syntax : Stremp ( stringl