Course : B. Sc Computer Science

Download 173.54 Kb.
Size173.54 Kb.




Course : B.Sc Computer Science

Semester : I

Unit : I & II

Subject : C Programming


Overview of C - Introduction - Character set - C tokens - keyword & Identifiers -Constants - Variables - Data types - Declaration of variables - Assigning values to variables -Defining Symbolic Constants - Arithmetic, Relational, Logical, Assignment, Conditional,Bitwise, Special, Increment and Decrement operators - Arithmetic Expressions - Evaluation of expression - precedence of arithmetic operators - Type conversion in expression – operator precedence & associativity - Mathematical functions - Reading & Writing a character -Formatted input and output.


Decision Making and Branching : Decision Making with IF statement - Simple IF statement - The IF ELSE Statement – Nesting of IF ... ELSE statements - The ELSE IF ladder -The Switch statement - The ?: operator - The GOTO statement - Decision Making and Looping - The WHILE statement - The DO statement - The FOR statement - Jumps in Loops - Arrays - One Dimensional - Two Dimensional - Multidimensional arrays – Character & String Handling - Declaring and initializing string variables - Reading Strings from Terminal - Writing strings to

Screen - Arithmetic operation on Character - Putting strings together -Comparison of two strings- String handling Functions - Table of Strings.

1. Give the introduction to C programming

C was an offspring of ‘Basic Combined Programming Language’(bcpl) called B, developed in the 1960’s at Cambridge university. B language was modified by Dennis Ritchie and was implemented at Bell Laboratories in 1972.The new language was named as C. since it was developed along with UNIX operating system, it is strongly associated with UNIX. It can run under various operating systems including MSDOS.
2. Define - Importance of C

1. It is robust language.

2. Rich set of built-in functions and operators are available.

3. Easy to create complex programs.

4. Suitable to write both application software as well as system software.

5. It is highly portable. Because C programs written for one computer

can be run on another with little or no modification.

6. It is well suited for structured programming. So that it is easy to debug,

test and maintain a module.

7. It can extend itself.

3. Define the basic structure of C programming:

Documentation section

link section

Definition section

Global declaration section

Main( ) function section


declaration part

executable part

Subprogram section

function 1

function 2

function 3



function n

4. Define - Basic character set

1. Letters:- (upper case A…Z,lower case a..z)

2. Digits:- (all decimal digits 0..9)

3. Special characters:-

. - period $ - dollar sign

, - comma : - colon

; - semi colon ‘ - apostrophe

” - quotation mark # - number sign

+ - plus ( - left parenthesis

- - minus ) - right parenthesis

* - asterisk { - left brace

} - right brace [ - left bracket ]-right bracket

4.white spaces:-

a) blank space

b) horizontal tab

c) carriage return

d) new line

e) form feed etc.

5. What are the different types of Constants

The value of the variable does not change during the execution of program.


1.Numeric constants

a. Integer constants

b. Real constants

2.Character constants

a. Single character constants

b. String constants.
6. Explain Integer constants

It refers to a sequence of digits.

Types of integer constants

1. Decimal integer constants

2. Octal integer constants.

3. Hexa decimal integer constants.

7. Explain Decimal integer constants:-
Valid examples Invalid examples

1. 123 1. 15343

2. –76565 2. 20,000

3. 0 3. $667

4. +736 4. 9-898

8. Define Octal integer constants:

Valid examples Invalid examples

1. 034 1.0X2

2. 07 2.0283

3. 07655 3.0987

9. Define Hexa decimal integer constants:

Valid examples Invalid examples

1. 0x2 1.0xnmjk

2. 0x87665 2.0x1286m

3. 0xabc 3.08972

4. 0x53647 4.0khjdi

10.Define Real constants

The numbers with fractional part is called real or floating-point constants.


1. 54.98

2. 25.75

Notations used to represent real constants are:

1. Decimal notation

2. Scientific notation

1. Explain Decimal & Scientific Notation:

Decimal Notation

1. Whole number followed by a decimal point and fractional part.

2. It is possible to omit the digits before the decimal point.

3. It is possible to omit the digits after the decimal point.


1) 215.

2) 125
Scientific (exponential) notation:

1.The mantissa is either a real number in decimal notation or an integer.

2. The exponent is an integer with an optional plus or minus sign.

3. The letter e separating mantissa and exponent part.

4. The exponent can be written in either lower or upper case.

General form for exponential notation:
mantissa e exponent
Valid examples:

    1. .65e4

    2. 12e-2

    3. 1.5e+3

    4. –1.5e-6

Invalid examples: reasons:

1. .2 3e 4 1. white space is not allowed.

2. 12 e*2 2. white space and * symbol is not allowed.

3. 120$ 3. $ symbol not allowed.

Examples of numeric constants:

Constant Valid Remarks

1. 89283L yes Represents long integer

2. 26,000 no Comma is not allowed

3. 5.3 e 2 no No white space is allowed

4. 0x7b yes Represents hexa decimal integer

5. 077 yes Represents octal integer
2. Explain the types of Constants

A character enclosed by single quote marks is called single character constants.


1) ‘a’

2) ’#’

3) ’2’

4) ’ ’

Points to remember:

1. The character constant ‘2’ is not same as the number 2.

2. Blank space enclosed by single quote is also called as character constant.

3. Character constants have integer values known as ASCII values.

For example

1) Printf (“%d”,’a’); - output will be 97 which is the ASCII value of ‘a’.

2) Printf(“%c”,98); - output will be ‘b’.
String Constants:

A sequence of characters enclosed by double quotes. The character may be any letter,digits,special characters and blank space.


1. “Welcome to c programming”

2. “2001”

3, “Well done”


Backslash character constants:

These are used in output functions. each backslash character constants contains two characters to represent a single character . these combinations are called Escape sequences.


1) ‘\n’- new line

2) ‘\t’-horizontal tab

3) ‘\v’-vertical tab

4) ‘\0’-null
3. Explain Variables

A variable is a data name that may be used to hold a data value. A variable may take different values at different times during the program execution.

Rules for forming a variable:

1.The starting character should be a letter.

2.The maximum number of characters may be 8 characters. it differs

3.Upper and lower case are significant. Example: TOTAL is not same as total or Total.

4.The variable should not be a keyword.

5.White space is not allowed.

6.Special characters except _(underscore) symbol is not allowed.
Valid examples:

    1. john

    2. value

    3. tot_amt

    4. a1

Invalid examples: Reason

  1. 1868 1) The first letter should be a letter

  2. (area) 2) Special characters not allowed

3. 27th 3) Number should not be a first character

4. % 4) Special characters not allowed

4. Explain Data types:

1. Primary data types.

2. User- defined data type

3. Derived data type

4. empty data set
Primary data types:

1. Integral type:

a. Integer size

i. signed int 16 bits

ii.short signed int 8 bits

iii.long signed int 32 bits

iv.unsigned int 16 bits

v.unsigned short int 8 bits

vi.unsigned long int 32 bits
b. Character

i. signed char 8 bits

ii. unsigned char 8 bits
2. Floating-point type

i. float 32 bits

ii. double 64 bits

iii. long double 80 bits

Declaration of variables:


1. It tells the compiler what the variable name is.

2. It specifies what type of data the variable will hold.

Data-type v1,v2,v3….vn;

v1,v2,v3….vn- variables


1. int count;

2. int a,b;

3. float area,volume;

4. char array;

5. double a1;

data type keyword equivalent

character char

unsigned character unsigned char

signed character signed char

signed integer signed int to int

signed short integer signed short int

signed long integer signed ling int

unsigned integer unsigned int or unsigned int

unsigned short integer unsigned short int

unsigned long integer unsigned long int

floating point float

double precision double

extended double precision longdouble

5.Explain the User defined declaration


1. type definition

2. enumerated data type
Type definition:


This allows the user to define the identifier that would represent an existing data type. The user-defined type is later used to declare variables.

General form:

Typedef type identifier;

Typedef - keyword

Type - exiting data type

Identifier –new name given to the data type

Typedef cannot create a new type. Using identifier the variables can be declared using the following syntax:

Identifier var1,var2…var n;


Typedef int units;

Units batch1,batch2;

Units name[10],name1[20];

Enumerated data type:

It is defined as follows

Enum identifier {value1,value2,…valuen};

It is used to declare the variables that can have one of the values enclosed within braces(known as enumerated constants).we can declare variables to be of this ‘new’ type as below:

Enum identifier v1,v2…vn;

The enumerated variables v1,v2,…vn can have one of the values value1,value2,…value n.


1. enum day {monday,tuesday,…sunday};

enum day week_beg,week_end;

we can assign values like

2. week_beg=sunday;


We can compare the values like

3.if (week_beg == friday)


The compiler automatically assigns integer digits beginning with 0 to all the enumeration constants. Thus the enumeration constants assign value1 as 0,value2 as 1 and so on. However the automatic assignments can be overridden by assigning values explicitly to the enumeration constants.


enum day {monday=1,tuesday=5,….sunday};

In the above Wednesday will take the value of 6,Thursday will take 7 and so on.

    1. Explain Global and local variables

Global variable is visible to all functions in the file. It is necessary to declare the variable before the main function. No need to declare the global variables in all functions. It is also known external variable. Local variable is visible and meaningful only inside the function in which they are declared.


/*example of storage classes*/

int m;

main( )


int I;

float balance;



function1( );


function1( )


int i;

float sum;




    1. Explain Storage classes


It provides the information about location and visibility of variables.

Types meaning

1. auto local variable known only to the function where it is declared

default is auto.

2.static local variable which exists and retains it ‘s value even after

control is transferred to the calling function.

3.extern global variable known to all function sin the file

4.register local variable which is stored in the register.


auto int count;

register char ch;

static int x;

extern long total;

    1. Explain the Assignment statement

Purpose : values can be assigned to variables using the assignment operator = as follows

variable _name =constant;




P=s=z=0 ; (multiple assignment statement)

It is possible to assign the values during declaration time as follows:

data type variable_name = constant or

expression or

variable ;


int final=100;

char yes=’x’;

double balance=39.98;

8. How to declare a variable as Constant

Purpose :

To maintain the value of variable throughout the program execution we are declaring the variable as constant.


const int balance=10.98;

Reading the data from the keyboard:

Another way of giving values to variables is to input data through keyboard using the scanf function.


scanf(“control string”,&var1,&var2,…&varn);

The control string contains the format of data being received. The ampersand symbol & before the variable name is an operator that specifies the variable name’s address

Example :


%d- represents integer value

%f- “ float number

%c- “ character

%lf - “ double

%u - “ unsigned int

9. Explain Output using printf:

Purpose :

It is used to display the output as well as to create an interactive program .


printf(“control string”,var1,var2,…varn);

1. Explain Operators

Purpose :

It is used to tell the computer to manipulate data and variables.


1. Arithmetic operators

2. Relational operators

3. Logical operators

4. Assignment operators

5. Increment and decrement operators

6. Conditional operators

7. Bitwise operators

8. Special operators

Arithmetic operators:

Arithmetic operators are used to perform arithmetic operations like addition , subtraction, multiplication and division and to find the remaindering division. The corresponding symbols are +(addition or unary plus),- (subtraction or unary minus),*,/,%(modulo division).C does not have an operator exponentiation.

Relational operators:


To relate any two or more quantities.

Operator Meaning

< is less than

> is greater than

> is greater than or equal to

<= is lesser than or equal to

== is equal to

!= is not equal to

Logical operators:

Purpose :

To combine two or more expressions.

Operator meaning

&& logical and

|| logical or

! logical not
Assignment operators:

= is used to assign value to a variable. In addition to this c has

shorthand operators.


v op =exp;

Statement with simple Statement with short

Assignment operator. Hand operator.

a=a+1 a+=1

a=a-1 a-=1

a=a*1 a*=1

a=a/1 a/=1

a=a%b a%=b

1. No need to repeat the operator again in the right hand side.

2. The statement is more concise and clear.

3. The statement is more efficient.

4. It is easy to read.
Increment and Decrement operators:


To decrement the value of the variable by one or to increment the value of the variable by one.


++ - adds 1 to the operand

-- - subtracts 1 unary operators


++m; (++ used as prefix operator)

m++; (++ as postfix operator)

If they are used independently then meaning is same. Consider the following



In the above case m and y would be 6.



In the above case m would be 6 and y would be 5.

Similarly for the --operator.
Conditional operator:


A ternary operator pair “?:” is used to construct conditional expressions



Example :


In the above the condition is evaluated first .if true then a will be assigned to x or else b will be assigned to x. The above syntax is equivalent to if …else statement.
Bitwise operators:


Manipulating the data at bit level.

Operator Meaning

& bitwise AND

| bitwise OR

^ bitwise EXCLUSIVE OR

<< shift left

>> shift right

~ one’s complement
Special operators:

sizeof - to determine the size of the variable

,(comma) - to link the related expressions together

example : value=(x=10,y=17,x+y)

. and -> - member selection operator

& and * - pointer operator

2. Explain about Expressions

Combination of both operand and operator.


1. Arithmetic

2. Relational

3. Logical

Arithmetic expression:

Operand combined with arithmetic operators called as arithmetic expressions





1. Integer arithmetic

2. Real arithmetic

3. Mixed arithmetic

Integer arithmetic:

Arithmetic operator combined with integer operands.


a + b; where a and b are of type integer.

Real arithmetic:

Arithmetic operator combined with real operands.


a + b where a and b are of type real.

Mixed mode arithmetic:

Expression consists of both integer and real operands.


a-b where a is of type integer and b is of type real.

Evaluation of expression:

Expression evaluation based on the priority of operators.

High priority * / % left to right

Low priority + -

Logical expression:

Whenever the logical operators combine any two relational

expressions then it is called logical expression.



Operator precedence:

1. Logical NOT

2. Logical AND

3. Logical OR

3.Explain the Type conversions in expressions

If operands are of different types then the lower type is automatically converted into higher type before the operation proceeds. The result is of higher type.

1. All short and char to int.

2. If one of the operand is long double then other will be converted into long double.

3. Else if one is double then other will be converted into double.

4. Else if one is float then other will be float.

5. Else if one is unsigned long int then other will be unsigned long int.

6. If one is unsigned long int and other one is long int then

a. Unsigned long int will be converted into long int or

b. Long int will be converted into unsigned long int.

Casting a value:

If we need to force the type conversion explicitly then it is called as coercion.


ratio=(float) number1/number2;

Where number 1 and number2 are of type integer type, ratio is of type float.

General form of Casting:

(type name) expression

3. Explain about the Control/Decision making statements

1.If statement

2.Switch statement

3.Conditional operator statement

4.Goto statement
If statement:


It is a powerful decision making statement to control the flow of execution. It is basically two-way decision statement and is used in conjunction with and expression.


if ( test expression)

It allows the system to evaluate the expression first and then, depending on whether the value is true or false it transfers the Control to the particular statement.




Different forms of IF statement:

1. Simple if statement

2. If …else statement

3. Nested if … else statement

4. Else if ladder
Simple if statement:

if (test expression)


statement block;



In the above statement if test expression is true then statement block

will be executed else statement block will be skipped.

If …else statement:

if (test expression)


true-block statement(s)




false-block statement(s)




Above statement if the test expression is true then true block statement, immediately following by the If statement are executed; otherwise the false block statement are executed. In either case either true block will be executed or false block will be executed but not both.

Nesting of if … else statement:

if (test condition 1)


if (test condition 2)


statement 1;




statement 2;




statement 3;


statement –x;


In the above statement if the condition 1 is true then the second if condition 2 will be tested and if it is also true then the statement 1 will be executed. if the second condition is false then the statement 2 will be executed. If the first condition is false then the statement 3 will be executed.

if (condition 1)


else if (condition 2)


else if (condition 3)



else if (condition n)





lse … if ladder:


The condition are evaluated from the top to bottom as soon as a true condition is found, the statement associated with it is executed and the control is transferred to the statement x. When all the ‘n’ conditions become false then the final else containing the default-statement will be executed.

The Switch statement:


Using the value of any variable or expression uses it to select one branch among several alternatives. The switch tests the value of given variable (or) expression against a list of case values and when a match is found, a block of statements associated with that case is executed.

switch ( expression )


case value-1:



case value-2:










In the above syntax the expression is an integer expression or characters the value-1,value-2,…. are constants or constant expressions and are known as case labels.

Each of these values should be unique within a switch statement. block-1, block-2,….. are statements contain zero or more statements. There is no need to put braces around these blocks. The case labels must end with a colon. When a switch is executed, the value of expression is compared with case values, if matches, then the block of statements that follows the case are executed. The break statement is used to exit from the switch statement.






case 1: c=a+b;


case 2: c=a-b;


default: c=a/b;






4. Explain the Loop constructs


It is used to repeat the block of statements for n number of times.

Process involved in looping statement is as follows:-

1. Setting and initialization of counter.

2. Execution of the statements of the statements in the loop.

3. Test for a specified condition for execution of the loop.

4. Incrementing the counter.


1. While statement

2. Do statement

3. For statement

1) While statement:

    1. The while is an entry- controlled loop statement.

    2. The test -condition is evaluated first and if the condition is true, then the body of

loop is executed. Again the test-condition is tested and body of the loop will be

repeated until the condition becomes false

c. If at the entry condition itself the test-condition is false then body of loop will be


while ( test condition)


body of the loop;



#include < stdio.h>

void main()


int i=1;

while (i<1)


printf(“this is number %d\n”);




2) The do statement:

a. The do is an exit- controlled loop statement.

b. The body of loop will be executed once and the condition is

tested if the condition is true then body will be repeated or

else exit from the loop.



body of the loop


while (test-condition);







printf(“well done!”);





3) For statement :

If we know the exact number of times for repetition of block of statements, then for statement can be used. it is entry controlled control loop.


for (initialization; test condition; increment)


body of loop


Execution of ‘for’ statement as follows:

    1. Initialization of the control variable is done first.

    2. The value of the control variable is tested using the test condition. If the test condition is true then the block is executed otherwise the loop is terminated and the execution continues with the statement immediately follows.

    3. When the body of the loop is executed, then the control is transferred back to the For loop. The control variable will be incremented by using the increment and again tested using the test condition. This will be repeated until the test condition becomes false.

    4. It allows negative increments. In that case the initial value should be greater than the final value.

    5. In normal situation initial value is lesser than the final value.

    6. It allows more than one variable initialization as well as more than one variable incrementation.


for (i=1; i<=10; i++) (positive increment)

for (i=10; i>0; i--) (negative increment)

for (i=0,j=8; i<=j; i++,j--)

7. For statement is not followed by semicolon(;).

8. Nested loop is also possible. (ie.,) loop within a loop.

Example :



for (i=1;i<=n;i++)









9. Break statement is used to exit from the loop. It can be used a part of If statement.





if (a





10. To skip a portion of statements in the for loop continue statement

can be used in conjunction with if statement and will goto the for





if (a





11. Avoid using goto statements in for statements.
Objective answers:

  1. What is the size of long int?

  2. Name any two ascii types of constants.

  3. Must all the variables appearing within a C program be declared ?

  4. What are unary operators?

  5. Give an example for short hand assignment operator.

  6. What is meant by linking

  7. When is the logical expression evaluated in a do..while statement?

  8. Where was C orginally developed and by whom?

  9. What is the name for data type conversion?

  10. What symbol terminates each C statement/

  11. What sre symbols used for logical operators AND & OR?

  12. Give the conversion specifications used for printing octal & hexa decimal values.

  13. every line in c programming should end with a semi colon.- say true or false

  14. in c language , lowercase letters are significant- say true or false

  15. every c program end with and END word.

  16. main() is where the program begins its execution.

  17. a line in c program may have more than oneline of output.

  18. a printf() statement can generate only one line of output.

  19. syntax error will be detected by the compiler.

  20. what are trigraph characters? How are they useful?

  21. what is variable.

  22. what is initialization? Why it is important?

  23. what are enumeration variables? How are they declared?

  24. describe the purpose of the qualifiers const and volatile.

  25. which of the following are invalid constant and why?





  1. which of the following are invalid variable names and why?




Row total

  1. which of the following arithmetic expressions are valid? If invalid, give reason.



21 %(int)3.2

  1. write the c assignment statements to evaluate the following equations.

Area= IIr2+22/7rh



  1. determine the valueof each of the following logical expressions if a=10,b=25and c=-7


b>12&&c<0 ||c<0.0

  1. state errors ,if any, in the following input statements

scanf(“%c %f %d”,city,&price);

scanf (“%s %d”,city,quan);

  1. what is the use of conditional operator?

  2. write the syntax of if.. statement . write the difference between while statement and do…while statement

Short Answers

  1. Explain arithmetic & relational operators?

  2. Explain if statement with an example

  3. Differentiate while & do...while statement

  4. Explain about mixed mode arithmetic operations?

  5. write a program to check whether the given year is a leap year or not

  6. Write short notes on logical operators.

  7. write a program to find largest among three given numbers.

  8. write a program to find reverse of the given digit

  9. write a program to do arithmetic operations for any two given numbers using switch case statement.

  10. write important features of for statement.

  11. write a program to convert the given farenheit temperature to Celsius temperature.

  12. write a program to generate fibanocci numbers

  13. write a program to generate prime numbers.

  14. write a program to calculate simple and compound interest

Essay Answers

  1. Explain about operators supported by C

  2. Explain about looping statements with suitable examples

  3. Explain data types supported by C

  4. Write a program to print the fibonacci series

  5. Write a program to print the prime numbers between 1 to 100

  6. Give the hierarchy of operator precendences covering all of the operators in C

  7. Write a program in c to solve a quadratic equation to check all possibilities of their coefficients

Download 173.54 Kb.

Share with your friends:

The database is protected by copyright © 2020
send message

    Main page