Vous êtes sur la page 1sur 98

LAB MANUAL OF

INTRODUCTION
TO
PROGRAMMING

ETCS-154

Maharaja Agrasen Institute of Technology, PSP area,


Sector – 22, Rohini, New Delhi – 110085
(Affiliated to Guru Gobind Singh Indraprastha University,
New Delhi)

MAIT/CSE 1|Page
INDEX OF THE CONTENTS

1. Introduction to the lab

2. Lab requirements (details of H/W & S/W to be used)

3. List of experiments (as per syllabus prescribed by G.G.S.I.P.U)

4. List of experiments (beyond the syllabus prescribed by G.G.S.I.P.U)

5. Projects to be allotted

6. Format of lab record to be prepared by the students.

7. Marking scheme for the practical exam

8. Details of different section along with examples & expected viva

questions.

MAIT/CSE 2|Page
1. INTRODUCTION TO THE LAB

C LANGUAGE

C language is the extra section, which is added to this lab so that the students can be familiar
with the basic programming language and can be expertise in this language, as C language is the
basis for all the other languages. C language is to be covered in the lab only.

In this section few topics of C Language which are covered are as follows:

 Getting started with (Basic Building Blocks of C Language)


 Decision Control Structure (if-else, ternary operator)
 Loop Control Structure (do-while, while, for)
 Case control Structure (switch-case)
 Arrays
 Strings
 Functions
 Pointers
 Structure and Unions
 File Handling
 Basic graphics functions

C language
 AIM
 Date
 Logic of the program
 Input given (code written)
 Output
 Viva questions

MAIT/CSE 3|Page
2. LAB REQUIREMENTS

Software requirements: Turbo C++ or Turbo C compiler

Operating System: Windows 2000

Hardware requirements: P-III 650 MHz

Intel 810 MB/10 GB HDD/ 64 MB RAM

Cabinet/1.44 FDD

LAN Card

MAIT/CSE 4|Page
3. LIST OF EXPERIMENTS
(As prescribed by G.G.S.I.P.U)
Paper Code: ETCS 154 L P C
Paper: C Programming Lab. 0 2 1
1. Write a program to produce ASCII equivalent of given number
2. Write a program to find divisor or factorial of a given number.
3. Write a program to evaluate the following algebraic expressions after reading necessary values
from the user
(ax+b)/(ax-b)
2.5 log x-cos 30+|x^2-y^2|+sqrt (2xy)
(x^5+10x^4+8x^3+4x+2
4. Write a program to find sum of a geometric series
5. Write a program to cipher a string
6. Write a program to check whether a given string follows English capitalization rules
7. Write a program to find sum of the following series
1+ ½ + 1/3 +________+1/20
8. Write a program to search whether a given substring exist in an input string or not and then delete
this string from input string.
9. Write a recursive program for tower of Hanoi problem
10. The fibonacci sequence of numbers is 1,1,2,3,5,8……. Based on the recurrence relation
F(n)=F(n-1)+F(n-2)for n>2
Write a recursive program to print the first m Fibonacci number
11. Write a menu driven program for matrices to do the following operation depending on whether
the operation requires one or two matrices
a) Addition of two matrices
b) Subtraction of two matrices
c) Finding upper and lower triangular matrices
d) Trace of a matrix
e) Transpose of a matrix
f) Check of matrix symmetry
g) Product of two matrices.
12. Write a program that takes two operands and one operator from the user perform the operation
and then print the answer
13. Write a program to print the following outputs:
1 1
2 2 2 2
3 3 3 3 3 3
4 4 4 4 4 4 4 4
5 5 5 5 5 5 5 5 5 5
14. Write functions to add, subtract, multiply and divide two complex numbers (x+iy) and (a+ib)
Also write the main program.
15. Write a menu driven program for searching an sorting with following options:-
a) Searching (1) Linear searching (2) Binary searching
b) Sorting (1) Insersection sort (2) Selection sorting
16. Write a program to copy one file to other, use command line arguments.
17. Write a program to mask some bit of a number (using bit operations)
18. An array of record contains information of managers and workers of a company. Print all the data
of managers and workers in separate files.

MAIT/CSE 5|Page
4. LIST OF EXPERIMENTS
(Beyond the syllabus prescribed by G.G.S.I.P.U)
1. W.A.P to print the ASCII value of the character entered by the user.
2. W.A.P to solve the following equation where value of a & b are entered by the user:
C= 2a + b/a – a/2.5 * b * (a/3 – b)
3. W.A.P to solve the following expression ( where value of x & y is entered by the user & the result
is stored in a variable ):-
i) 3x3 + x34y2 - 6y + 2xy - y2
ii) 2.5 log(x) – cos30 + (x3- y2)
4. W.A.P to convert temperature in degree into Fahrenheit.
5. W.A.P to convert the number entered in bytes into bits, kilobytes, gigabytes & nibble.
6. W.A.P to find whether the number entered by the user is even or odd.
7. W.A.P to find whether the number entered by the user is positive or negative.
8. W.A.P to swap two numbers without using third variable.
9. W.A.P to find roots of the quadratic equation entered by the user.
10. W.A.P to find the largest of three numbers entered by the user.
11. W.A.P to find whether a three digit number entered by the user is a palindrome or not. ( only
using if- else)
12. W.A.P to find whether the year entered in dd/mm/yy form is a leap year or not.
13. W.A.P to find out how many days and how many weeks has passed between nay two dates
entered by the user.
14. W.A.P to make a calculator where the operator is entered by the user ( using switch)
15. W.A.P to find whether the character entered by the user is a vowel (using switch).
16. W.A.P the program such that it prints digit of a number entered by the user in words. For
example, if the number entered by the user is 123 then ‘one two three’ should be printed as an
output.
17. W.A.P to round off an integer to the next largest multiple of another integer j. For example 256
days when rounded off to next largest multiple divisible by a week results into 259.
18. W.A.P to find to print the table of the number entered by the user.
19. W.A.P to generate a Fibonacci series.
20. W.A.P to find the factorial of the number entered by the user.
21. W.A.P to find the sum of ‘n’ terms of the following series, where the value of ‘n’ is entered by
the user :
x + x2/2! + x3/3! + x4/4! + ………
22. W.A.P to reverse a number entered by the user and then finds whether the number is a
palindrome or not.
23. W.A.P to find the factors of the number entered by the user.
24. W.A.P to do binary operations on the binary number entered by the user.
25. W.A.P to find the average of ‘n’ numbers entered by the user.
26. W.A.P to generate an Armstrong series.
27. W.A.P to find the number of digits present in the number entered by the user.
28. W.A.P to find the sum of the digits of the number where the number and the number of the digits
of that number are entered by the user.
29. W.A.P which finds four digit perfect squares where the number represented by the first two digits
and the number represented by the last two digits are also perfect squares.
30. A positive integer is entered by the user along with the base in which that number needs to be
converted. W.A.P to display the number entered, the base of the number system in which it is
converted and also the converted number (using switch).

MAIT/CSE 6|Page
31. W.A.P to generate the following patterns using switch.
i) *
**
***
****
*****

ii) 1
121
12321
1234321

32. W.A.P to swap two numbers using pointers.


33. W.A.P to make a pointer to a pointer and display the value stored in both the pointers.
34. W.A.P to store the values entered by the user in an array and then displays the position of those
elements in an array.
35. W.A.P to replace the duplicate elements of an array with any character.
36. W.A.P to find the minimum and maximum values entered by the user in a matrix.
37. W.A.P to find the average of elements entered by the user in an array.
38. W.A.P to display the position of the elements entered by the user in a string along with the
addresses of those elements.
39. W.A.P to cipher a string entered by the user.
40. W.A.P to copy a string entered by the user without using string functions.
41. W.A.P to calculate the length of a string entered by the user without using string functions.
42. W.A.P to compare two strings entered by the user without using string functions.
43. W.A.P to find the location of the word in a string entered by the user. For example, if the string
entered is “somewhere over the rainbow” and the word whose location is to be found is “over”.
So the output should be 11.
44. W.A.P to find whether the string entered by the user is a palindrome or not.
45. W.A.P to find factorial of a number entered by the user using functions.
46. W.A.P to swap two numbers using call by value.
47. W.A.P to reverse a number using functions.
48. W.A.P to that inputs & displays the information of students using structures.
49. W.A.P to copy the contents of a file to another file having 10 records of employee using file
handling.
50. W.A.P to make various figures using graphics functions.

MAIT/CSE 7|Page
5. PROJECTS TO BE ALLOTTED

Students will be divided into groups of at most four and projects are allotted to those groups.
This project is to be submitted at the end of the semester along with a project report by the
individual student.

List of projects:
 Hotel management
 Calculator
 Calendar
 Banking
 Future forecast
 Library management
 Consumer Exp. Survey
 Hotel Management
 Periodic Table
 Central Bureau of Investigation
 Student’s Management
 Employee Management
 Online Examination
 Temperature Graph
 Railway Management
 Superposition of Waves

Students can select any of the above according to their choice but none of the student’s group
should have the same project.
NOTE: The project is to be made in C Language only. If any other programming language is
used then the project will not be considered for evaluation. Project report should be added at last
page.

FORMAT FOR THE PROJECT REPORT

 Front page

 Acknowledgement

 Index

 Abstract

 List of functions/structure (user defined) used in the project

 Output screens

 Bibliography

MAIT/CSE 8|Page
6. FORMAT OF THE LAB RECORD TO BE
PREPARED BY THE STUDENTS

1. The front page of the lab record prepared by the students should have a cover
page as displayed below.

NAME OF THE LAB


Font should be (Size 20”, italics bold, Times New Roman)

Faculty name Student name


Font should be (12”, Times Roman) Roll No.:
Semester:
Group:
Font should be (12”, Times Roman)

Maharaja Agrasen Institute of Technology, PSP Area,


Sector – 22, Rohini, New Delhi – 110085
Font should be (18”, Times Roman)
2. The second page in the record should be the index as displayed below.

MAIT/CSE 9|Page
INTRODUCTION TO PROGRAMMING

PRACTICAL RECORD

PAPER CODE : ETCS - 156

Name of the student :

University Roll No. :

Branch :

Section/ Group :

PRACTICAL DETAILS

a) Experiments according to the list provided by GGSIPU

Exp. no Experiment Name Date of Date of Remarks Marks


performance checking (10)

MAIT/CSE 10 | P a g e
Exp. no Experiment Name Date of Date of Remarks Marks
performance checking (10)

MAIT/CSE 11 | P a g e
b) Experiments beyond the list of experiments provided by GGSIPU (practical in C
language as well as in other programming language).

Exp. no Experiment Name Date of Date of Remarks Marks


performance checking (10)

MAIT/CSE 12 | P a g e
Exp. no Experiment Name Date of Date of Remarks Marks
performance checking (10)

MAIT/CSE 13 | P a g e
PROJECT DETAILS

1. TITLE :

2. MEMBERS IN THE PROJECT GROUP :

3. PROJECT REPORT ATTACHED :


a) YES b) NO

4. SOFT COPY SUBMITTED :


a) YES b) NO

Signature of the lecturer Signature of the student

( ) ( )

MAIT/CSE 14 | P a g e
7. MARKING SCHEME FOR THE PRACTICAL EXAMS
There will be two practical exams in each semester.

 Internal Practical Exam


 External Practical Exam

INTERNAL PRACTICAL EXAM

It is taken by the concerned lecturer of the batch.

MARKING SCHEME FOR THIS EXAM IS:

Total Marks: 40

Division of 40 marks is as follows

1. Regularity: 25

 Performing program in each turn of the lab


 Attendance of the lab
 File

2. Viva Voice: 10

3. Project: 5

NOTE: For the regularity, marks are awarded to the student out of 10 for each
experiment performed in the lab and at the end the average marks are
giving out of 25.

MAIT/CSE 15 | P a g e
EXTERNAL PRACTICAL EXAM

It is taken by the concerned lecturer of the batch and by an external examiner. In this exam
student needs to perform the experiment allotted at the time of the examination, a sheet will
be given to the student in which some details asked by the examiner needs to be written and
at the last viva will be taken by the external examiner.

MARKING SCHEME FOR THIS EXAM IS:

Total Marks: 60

Division of 60 marks is as follows

a. Sheet filled by the student: 20

b. Viva Voice: 15

c. Experiment performance: 15

d. File submitted: 10

NOTE:

 Internal marks + External marks = Total marks given to the students


(40 marks) (60 marks) (100 marks)

 Experiments given to perform can be from any section of the lab.

MAIT/CSE 16 | P a g e
8. DETAILS OF DIFFERENT SECTION

ALONGWITH EXAMPLES

&

EXPECTED VIVA QUESTIONS

MAIT/CSE 17 | P a g e
Basic Building Blocks of C Language
Program in C language can be written in notepad (editor) and can be saved
as .c extension but the best way of writing a C language is to write the
program in the C editor under C or C++ compiler

How to start C?
 Click on the shortcut on the desktop

OR

Open the drive in which C compiler is loaded

Click on TC ---- click on bin -- click on after that


you will get the following screen.

After that check the included directories for working further:


 Click on options---- click on directories

MAIT/CSE 18 | P a g e
Check the path of the directories. It should be as displayed in the window below. Here
‘G’ is drive in which C compiler is loaded, ‘TC’ is the folder containing the compiler
include, bin, lib are the including files.

After that click on ‘ok’ and write the code in the screen.
1. Writing, saving, compiling and running a program in C language (getting starting
with C)
 Click on file ----- click on new

MAIT/CSE 19 | P a g e
After clicking on ‘new’, screen displayed will be:

MAIT/CSE 20 | P a g e
Writing the Code or the program:

EXPLANATION OF THE CODE WRITTEN IN C LANGUAGE

Example:

# include<stdio.h>
1.Header files

#include<conio.h>

void main( ) 2. Starting function


{ 3. Opening braces

clrscr();

int a,b,c; 4. Declaration of variables used in the program

printf( “ enter the value of a & b” ); 5. Output function used


for displaying some text
on the output screen
scanf (“ %d %d “,&a,&b);
6. Input function used for
taking input from the user
c = a + b;
7. Arithmetic statement used for calculating the sum
of two numbers
printf( “ the value stored in the variable c is : %d “,c); 8. Output function used
for displaying the output
on the output screen
getch();

}
9. Closing braces

Steps to write the program in C language:

a) To start writing a c program first we need to include the header files which
contain the predefined function in c language, which perform their defined
functions. Include the header files by writing:

# include < stdio.h>

# include < conio.h>

MAIT/CSE 21 | P a g e
 stdio.h (standard input/output) header file contains all the basic function like
input and output functions which are necessary for running a c program.
 conio.h (console input/output) header file contains input/output functions which
are related to output screen.

Most commonly function included in this is: getch ()


b) After including the header files start the main function by writing:

void main( )
 void is included before main because main does not return any value.
 Other method to start main is by simply writing only main( ) in the starting
and writing return(0) at the end of the program.
 There should be only one main( ) in the whole program because the compiler
starts executing the statements from the main( ) function.
c) Now start the code by including the opening curly brackets. By doing this a
separate block of memory will be allocated according to the statements including
in the opening and closing curly brackets.

Note: More than one statement in C language code is always included


in opening and closing curly brackets.

Clrscr() function is used to get a clear output screen.(not including


the output of the previous program).
d) After this, the most important thing to do is to declare the variables used in your
code. Variables are the names given to the space allocated in the memory. This
means that if you have to do some work in the system you need to store that value
in the memory. So we need to make memory spaces in the system to store the
values inputted by the user and also the result values. For this you need to give the
name to the spaces and also you should know the type of value which you need to
store. This can be done by declaring the variables. Like:

MAIT/CSE 22 | P a g e
SYNTAX : datatype variable name;

When you write int a,b,c;

Then

‘int’ indicates that the value stored in the spaces can only be of integer type
and a, b, c are the names given respectively.

Variables

a b c
Integer value Integer value Integer value

Spaces allocated in the memory with a, b & c names


respectively

‘int’ is called as the data type. Various types of data types used in C language are as
follows:

Sr.No VALUES DATA TYPE USED

1. Integer int

E.g.2, 3, 4, 5 etc.

2. Floating value

E.g.2.36,3.56, 0.4E20 float


etc.

3. Character value

MAIT/CSE E.g. A,a,B,c,d, etc. char 23 | P a g e


Therefore, if we want to use variables which contain a floating value, character and
integer value, then the declaration will be:

int a;
float b;
char c;

And in the memory the location will be as follows:


Variables

a b c
Integer value float value character
value

Spaces allocated in the memory with a, b & c names


respectively

Note: every statement in C language is to be ended by a semicolon.

e) Now after this, you have to decide that value of which variable you want to get
inputted by the user and which one you want to get stored while executing the
program. If you want the user to input the value for some variable then, it should
be mentioned in the output screen that which value needs to be inputted.

To display anything on the output screen printf( ) function (also called as output
function) is used.

SYNTAX: printf(“The text which you want to get displayed “);

MAIT/CSE 24 | P a g e
There is escape sequences used in printf in order to modify the way to
display output on the screen.

Escape Sequences Use

1. \n displays the text or the output in the


next line
2. \t displays the text or the output after 8
spaces.
3. \b used for backspace

There are many other escape sequences which will be discussed in the lab.

f) Now when the user inputs the value we need that value to be stored in the
memory space which we have allocated during the declaration. This is done by
using the scanf( ) function (also called as input function).

SYNTAX: scanf(“format specifiers of the variables where value needs


to get stored”,&name of the variable);
Format specifier is different for each data type.

Sr.No Data Type Format Specifier

1. int %d

2. float %f

3. char %c
For
example, if we want to input float, int & char value then the scanf( )
function will be written like:

Scanf(“ %f %d %c”,&a,&b,&c);

Here a, b & c will be declared as float, int & char respectively.

g) Now after this, you will write those statements which when get executed will
generate a value which will get stored in the variable in which the value is not
entered by the user.

MAIT/CSE 25 | P a g e
For example

C = a + b;

NOTE: the value of the variables entered by the user is always on


the R.H.S and value of the variable to be taken out is
always on the L.H.S.

Variables

a b c
3 5 8

Value generated and stored in variable C


by using the statement
Values entered by the user C = a + b;

h) After this we need to display the values generated on the output screen. So we
will use the output function printf( ).For example:
Printf(“ the value of sum is : %d “,c);

Here format specifier is used to display the output generated in the specified format
(integer, float, character) and remember this that the formatspecifier should be of the type,
by which that particular variable isdeclared. For example if in the output screen we want
to display the values entered by the user as well as the output generated by the user then
the printf function syntax will be : Printf(“ the value of addition of %d & %d is
: %d”,a,b,c);

MAIT/CSE 26 | P a g e
NOTE: the names of the variables should be written in the same
sequence as the respective format specifiers are written in
the printf function.

After this write getch( ); function so as to return back to the input screen while
getting the output on the same output screen.
i) Last step is to close the program by using the closing curly bracket.

The screen will look like this :

 After writing the code save the code which you have written by clicking on file
and selecting save option or by pressing F2 key. After clicking on save or by
pressing F2 key window displayed will
be:

MAIT/CSE 27 | P a g e
Write the name by which you want to save the program with an extension ‘.c’ for
example: sum.c And then click on ‘ok’. After doing this you will get a window
displayed containing the name displayed on the top of the window in the following
way:

 After saving the code compile the code by clicking on compile or by


pressing Alt and F9 keys
together.

 After compiling you will get a window displayed indicating whether there
are any errors in your program or not.

MAIT/CSE 28 | P a g e
If there are no errors then you can run the program otherwise a window will
be displayed indicating your errors and you have to remove those errors.
Repeat the compiling process until you get no errors.

MAIT/CSE 29 | P a g e
 When you have compiled the code and you get now errors then run the
code by clicking on ‘run’ or press Ctrl+F9 keys together. After doing this
you will get the output screen showing you the output of your code:As
printf function is used to
display:

MAIT/CSE 30 | P a g e
Enter the values and hit the enter key:

After getting the result hit the enter key again. You will be returning back to the initial
screen where you where writing the code.

MAIT/CSE 31 | P a g e
2. Details of how to write a program in a C language

The basic elements required to write a program in C language are:


 Data types
 Keywords
 Constants
 Variables
 Statements
 Pre defined functions (input/output and many more)
 Operators
 Format specifiers

DATA TYPES & FORMAT SPECIFIER

They are used to describe the type of the data which you are using in the program and
format specifier is used to define the data type in the printf and scanf functions.

KEY WORDS

They are the words which have predefined meaning in C language. They are always
written in small case.

Example: break, int, float, switch, for, while, do-while etc.

CONSTANTS & VARIABLES

Data in C language can be defined as constants and variables. Constant data means that
the value of that data can not be changed through out the program but variables means that
the value of the data can be changed through out the program.

Example: a=2.5 is indicating that ‘a’ is a constant.

C = d + e is indicating that ‘c’ is a variable whose value depends upon the


value of‘d’ and ‘e’.

NOTE:value of a variable is always executed by the system or it is entered by the user at


the output screen.

MAIT/CSE 32 | P a g e
STATEMENTS

Statements in C languages are always terminated by a semi colon.

PRE DEFINED FUNCTIONS

Pre defined functions are those functions which have predefined meaning in the C
language.

Example: printf( ) output function

Scanf( ) input function

There are many other functions which will be taken in the lab in details.

OPERATORS

Various types of operators in C language are:


 Arithmetic operators +, -, *, /, %
 Assignment operators =
 Logical operators &&, ||, !
 Relational operators <=, >=, = =, <, >, !=

NOTE:

First of all before making any program following things should be


considered:
1. Develop the logic of the program which you have to make. That
means, you should know
 How many variables you will need in the program?
 Which variables values will be entered by the user and which
variables value will be calculated during the execution of the
program?
 What is the type of value will be stored in the each variable?
 Which operators you will need?
 Where you will need to get the output?
 Statements should be written in the proper order.

MAIT/CSE 33 | P a g e
3. Decision control in C language
Decision control can be done using if-else statement while making programs.

In this a test condition is written in ‘if’, if that statement is true then the statements in that
if block gets executed and if it is not true then ‘else’ block gets executed.

Syntax for if-else statement:

Condition to be
tested

if( equation using relational operator )


{
Statement 1;
Statement1 2; Statements to be
Statement 3; executed if the
……………………….. condition in the ‘if’
………………………. statement is true
}
else
{
Statement 1;
Statement1 2;
Statements to be
Statement 3; executed if the
……………………….. condition in the ‘if’
………………………. statement is no
} true

4. Loop control in C language


Loop control means running particular block of statements specific number of times until
the value of certain expression becomes ‘not true’. This can be done using ‘for’, ‘while’
and ‘do-while’ loops.

MAIT/CSE 34 | P a g e
SYNTAX of for loop:

for(initial value of the counter ; test condition ; incrementing /decrementing of counter value)

Statement 1;

Statement 2;

Statement 3;

Statement 4;

………………………..

……………………….

SYNTAX of while loop:

Initial value of the counter;

while(test condition)

Statement 1;

Statement 2;

Statement 3;

………………………..

……………………….

Incrementing /decrementing of counter value;

MAIT/CSE 35 | P a g e
SYNTAX of do-while loop:

Initial value of the counter;

do

Statement 1;

Statement 2;

Statement 3;

………………………..

……………………….

Incrementing /decrementing of counter value;

while(test condition);

MAIT/CSE 36 | P a g e
5. Case control in C language
In C language case control means that according to your choice you can run the block of
statements.

SYNTAX OF SWITCH

switch(name of the variable name which contains the choice as a value)

case 1 : statement 1;

statement 2;

…………..

…………..

break;

case 2 : statement 1;

statement 2;

…………..

…………..

break;

default: statement for wrong choice

6. Graphics in C language

By using graphics we can make different figures and graphical projects by using C
language.

For using graphics in C we need to include graphics.h header file and also we need to
call a graphics library graphics.lib. This header file includes all the graphics function.
Both these files are provided as a part of TURBO C.

First thing that we need to do before we can carry out any drawing activity is to switch
over to the graphics mode. To switch over to graphics mode that offers best graphics we
need to call the function initgraph( ). It figures out the best resolution and puts the
number corresponding to that mode in the variable gm(graphics mode), the number in

MAIT/CSE 37 | P a g e
this variable tells us which monitor we are using. Other variable which is used is
gd(graphics driver).

BASIC TOOLS OR GRAPHIC FUNCTIONS USED

FUNCTION MEANING

putpixel(x1,y1); Display a point at (x1,y1)

line(x1,y1,x2,y2); Draws a line from


(x1,y1) to (x2,y2)

circle(xc,yc,rad); Draws a circle with


center (xc,yc) and radius
rad

rectangle(x1,y1,x2,y2); Draws a rectangle


with(x1,y1) and (x2,y2)
as corners

ellipse(xc,yc,start,end,xrad,yrad); Draws an ellipse with


(xc,yc) as center with
xrad and yrad as x and y
radius. If start is 0 and
end is 180 only upper
half of the ellipse is
drawn.

MAIT/CSE 38 | P a g e
OTHER FUNCTIONS USED ARE:
1. outtextxy(x1,y1,”text to be displayed”);

This function is used to display text on the graphics mode screen. ‘x1’ & ‘y1’
are the coordinates from where the text is going to start.
2. setcolor(name of the color);

name of the color can be : RED,BLUE,GREEN,YELLOW & MAGENTA


3. delay(time for which you want the delay); Time of delay should be in seconds and
‘dos.h’ header file should be included in the beginning where other header files
are included.

NOTE: When you have completed the work on graphics then you have to close
the graphics mode by calling the closegraph( ) function but remember this before closing
the graphics mode use the getch() function.

MAIT/CSE 39 | P a g e
OBJECTIVE:

WRITE A PROGRAM TO FIND OUT THE ASCII VALUE OF THE INPUT


CHARACTER.

The basic aim of this program is to find out the ASCII VALUE of a given character. To facilitate
exchange of recorded data between computers the coding of character has been standardized.
The most common code is known as ASCII CODE(AMERICAN STANDARD CODE FOR
INFORMATION AND INTERCHANGE).

This code uses 7 bits to code each character which is there in the character sets.

Steps to write a program:

First step take the input character from the user and then output its ASCII CODE. For this
purpose we can declare an int type variable(say a) and assigning to it into character variable(say
ch).While assigning the integer variable is going to store ASCII CODE equivalent to character
variable. So, when this integer variable is displayed on the screen using printf statement, it prints
the ASCII code of the character.

Other way to solve this problem is to output this character variable using printf statement with
conversion character %d. It will automatically print ASCII code equivalent to the input
character.

MAIT/CSE 40 | P a g e
FLOWCHART

START

Int a

Char ch

Read ch

a=ch

Print a

STOP

MAIT/CSE 41 | P a g e
//programe to find ascii value of characters

#include<stdio.h>
#include<conio.h>

void main()
{
clrscr();
char a;
printf("please enter the character");
scanf("%c",&a);
printf("the ascii value is %d ",a);
getch();
}

**********************************OUTPUT****************************

Enter a character :a

ASCII value is :97

MAIT/CSE 42 | P a g e
OBJECTIVE:

WRITE A PROGRAM TO CALCULATE THE FACTORIAL OF A NUMBER.

The aim of this program is to implement the concept of the loop statement. There are three types
of loop statement: - for , while , do-while.
Student can use any one of the loop statements to calculate the factorial of the program.

Steps to write the program:

For this program students should know the concept of the factorial of a numbers. Factorial of a
number of a number is calculated by multiplying all the numbers starting from 1 to that number.
For example: -

Factorial of 5 (5!) = 1*2*3*4*5


Factorial of 3 (3!) = 1*2*3 and so on.

One should remember that 0! = 1.

Student can use any one of the loop statements to calculate the factorial of the program.

MAIT/CSE 43 | P a g e
PROGRAM TO FIND THE FACTORIAL OF A NUMBER

FLOWCHART

START

READ n

FACT=1

I=1

I<=n

PRINT FACT

FACT=FACT*I

STOP
I=I+1

MAIT/CSE 44 | P a g e
//rogram to find factorial or divisor of a given number

#include<stdio.h>

#include<conio.h>

void main()

int a,b;

float f;

clrscr();

printf("enter a number:");

scanf("%d",b);

f=1;

for(a=1;a<=b;a++)

f=f*a;

printf("the factorial of b is:%f",f);

getch();

/*Output:

enter a number:5

the factorial of b is:120

*/

MAIT/CSE 45 | P a g e
OBJECTIVE:

Write a program to evaluate the following algebraic expressions after reading necessary
values from the user

a) (ax+b)/(ax-b)
b) 2.5log(x)+cos30 +x^2-y^2-sqrt(2xy)
c) x^4+x^3+10x^2

this a program aimed to solve the mathematical expression for the particular value of x. basic
aim of the program is to show the students how to take input from the user, how to solve the
mathematical expression and how to output the answer to user using c language.

Students have to use printf scanf statements for input and output purpose.
And to solve the expression for a particular value of x, students have to use the pow ()
function.when students are going to use the function it is necessary to include the file math.h.

TO SOLVE THE EXPRESSION

X^4 +X^3 +10X^2


For this program students should know the implementation of the pow().these function are
defined in math.h and are used to calculate the power and square root of a varaible to the other
variable.

Double pow (double a, double b)


This function takes two double variables as parameters and returns the double value as answer.

TO SOLVE THE EXPRESSION

(ax+b)/(ax-b)

program should take the input for a, b and x from the user and after solving the expression
program should output the answer using c language.
Students should use the printf and scanf statements for taking input and output from the user.
Declaration of the variables a, b and x can be int or float type one should remember that the
expression return a real value. Therefore another variable of float type should be declared.

For this basic operators(*,+,_) are to be used. Header file stdio.h should be included.

TO SOLVE THE EXPRESSION

20log(x) +cos30+x^2-y^2-sqrt(2xy)

MAIT/CSE 46 | P a g e
Program should take input value for variables x and y from the user first ,then it have to solve the
expression mentioned above.

For this program students should know the implementation of the functions log(), cos() and sqrt
().

Function log() is used to calculate the logarithm of the variable. the implementation of this
function is double log(double).but one should know that this function calculate the natural
logarithm.

Function cos() is used to calculate the cosine of the variable. This implementation of this
function is double cos(double)
i.e , it takes variable of double types as parameter and retuns its cosine value which is again
double type .but one should know that this function takes parameter value in radians.

Function sqrt() is used to calculate the square root of the variable. The implementation of this
function is double sqrt (double) hence it takes variable of double types as parameter and returns
its square root which is again double type.

Students should use other operator (+,-,*) for solving the expression and output the result to the
user. Students should include the header files stdio.h and math.h.

MAIT/CSE 47 | P a g e
//program to evaluate ( a * x + b ) / ( a * x - b )
#include<stdio.h>
#include<conio.h>
main( )
{
const a = 10;
const b = 20;
float x,y;
clrscr( );
ams:
printf("\nEnter the value of x : ");
scanf("%f",&x);
if(a*x-b ==0)
{
printf("\n\aThe denoinator is 0...\n Enter the value of x again...");
goto ams;
}
y = (a * x + b) / (a * x - b);
printf("\n The value of (%d * %f + %d)/(%d * %f - %d) is : %f", a, x, b, a, x, b, y );
getch ( );
return 0;
}
/* OUTPUT
Enter the value of x: 1
The value of (10 * 1.000000 + 20)/(10 * 1.000000 - 20) is : -3.000000 */

//programe to solve maths problems


#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
clrscr();
int x,y,z;
printf("enter the value of x & y");
scanf("%d%d",&x,&y);
z=((2.5*log(x)-cos30+(x*x)-(y*y)+pow((2*x*y),0.5));
printf("the value obtained will be %d",z);
getch();
}
/* OUTPUT
To calculate
2.5*logx - cos30 + |x^2 - y^2| + sqrt(2*x*y)
enter the value of x & y 2 6
The value obtained will be 38.477596 */

MAIT/CSE 48 | P a g e
OBJECTIVE:

WRITE A PROGRAM TO FIND THE SUM OF THE FOLLOWING SERIES-

1+1/2+1/3+1/4+1/5+……………….+1/20

Steps to write the program:


1. Store the result of the series in the variable.
2. Let the variable be ‘sum’.
3. Initially assign the ‘sum’ as ‘0’ and use the loop for incrementing the next term.
4. Use the expression:
Sum = sum+1.0/i
Where 1.0/i is used to increment the terms.
For e.g. If u r using ‘for’ loop the syntax will be:
for (i=1;i<=20; i++)
Here i=1 initially
5. Assign the sum type as float.
6. Use the ‘printf’ statement to print the result of series on the screen.

MAIT/CSE 49 | P a g e
Flow Chart:

Start

Let sum=0, i=1

i<=20

Print sum
sum=sum+1.0/i

Stop
i=i+1

MAIT/CSE 50 | P a g e
//programe: to calculate the sum of 1+1/2+1/3+----+1/20

#include<stdio.h>
#include<conio.h>

main()
{
int i=1;
double sum = 0.0;
clrscr();
while(i<=20)
{
sum+= (1.0/i);
i++;
}
printf("\n\n\t\tThe sum of the series 1+1/2+1/3+----+1/20 is %lf",sum);
getch();
return 0;
}

/*
OUTPUT
The sum of the series 1+1/2+1/3+----+1/20 is 3.597740
*/

MAIT/CSE 51 | P a g e
OBJECTIVE:

To perform following operations on one or two matrices :


1 addition of two matrices
2 subtraction of two matrices
3 trace of a matrix
4 transpose of a matrix
5 check of matrix symmetry
6 product of two matrices

The aim of this program is to implement the concept of matrix calculation using arrays(2-d
arrays). For handling the matrix calculations students have to use 2-d arrays for storing a matrix.
for example
Int mat[m][n]
Where mat is int type array (storing integer type values)
m represents no. of columns
n represents no. of rows

Steps for writing the program


For this program switch case should be used. First of all menu should be given to user and
his/her choice should be asked. There should be six cases corresponding to six different
operations, each depending upon user choice desired operation should be performed.

Step 1: declare three arrays, two for two matrices and third for the resultant matrix

Step 2: apply switch case for performing different operations.

For addition and subtraction, number of rows and columns in the two matrices should be equal.
Trace is the sum of diagonal elements.
Transpose of a matrix is obtained by interchanging elements of rows and columns in the matrix.

MAIT/CSE 52 | P a g e
/* operations on a matrix*/
#include<stdio.h>
#include<conio.h>
void main()
{ clrscr();
int A[10][10],B[10][10],C[10][10],m,n,p,q,i,j,k,ch;
int sum1=0,sum2=0,flag=0;
printf("Enter the order of matrix A :");
scanf("%d%d",&m,&n);
printf("\nEnter the matrix A : \n");
for(i=1;i<=m;i++)
{ printf("\n");
for(j=1;j<=n;j++)
scanf("%d",&A[i][j]);
}
printf("\nEnter the order of matrix B :");
scanf("%d%d",&p,&q);
printf("\nEnter the matrix B : \n");
for(i=1;i<=p;i++)
{ printf("\n");
for(j=1;j<=q;j++)
scanf("%d",&B[i][j]);
}
printf("\n\nPress 1 for addition.");
printf("\nPress 2 for subtraction.");
printf("\nPress 3 for upper and lower triangular matrix.");
printf("\nPress 4 for trace of matrix.");
printf("\nPress 5 for transpose.");
printf("\nPress 6 for checking matrix symmetry.");
printf("\nPress 7 for product.");
printf("\nEnter your choice :");
scanf("%d",&ch);
switch(ch)
{ case 1:if(m==p&&n==q)
{ printf("\nThe sum of the matrices are :");
for(i=1;i<=m;i++)
{ printf("\n");
for(j=1;j<=n;j++)
{ C[i][j]=A[i][j]+B[i][j];
printf(" %d",C[i][j]);
}
}
}
else
printf("\nMatrix cannot be added.");
break;

MAIT/CSE 53 | P a g e
case 2:if(m==p&&n==q)
{ printf("\nThe difference of the matrices are :");
for(i=1;i<=m;i++)
{ printf("\n");
for(j=1;j<=n;j++)
{ C[i][j]=A[i][j]-B[i][j];
printf(" %d",C[i][j]);
}
}
}
printf("\nMatrix cannot be subtracted.");
break;
case 3:printf("UPPER TRIANGULAR MATRICES ARE :");
if(m==n)
{ printf("\nMATRIX A :");
for(i=1;i<=m;i++)
{ printf("\n");
for(k=0;k<=i;k++)
printf(" ");
for(j=i;j<=n;j++)
printf("%d",A[i][j]);
}
}
if(p==q)
{ printf("\nMATRIX B :");
for(i=1;i<=p;i++)
{ printf("\n");
for(k=0;k<=i;k++)
printf(" ");
for(j=i;j<=q;j++)
{
printf("%d",B[i][j]);
}
}
}
printf("\nLOWER TRIANGULAR MATRICES ARE :");
if(m==n)
{ printf("\nMATRIX A :");
for(i=1;i<=m;i++)
{ printf("\n");
for(j=1;j<=i;j++)
printf(" %d",A[i][j]);
}
}
if(p==q)
{ printf("\nMATRIX B :");

MAIT/CSE 54 | P a g e
for(i=1;i<=p;i++)
{ printf("\n");
for(j=1;j<=i;j++)
printf(" %d",B[i][j]);
}
}
break;
case 4:for(i=1;i<=m;i++)
{ for(j=1;j<=n;j++)
if(i==j)
sum1=sum1+A[i][j];
}
printf("\nThe sum of trace of matrix A is :%d",sum1);

for(i=1;i<=p;i++)
{ for(j=1;j<=q;j++)
if(i==j)
sum2=sum2+B[i][j];
}
printf("\nThe sum of trace of matrix B is :%d",sum2);
break;
case 5:printf("\n MATRIX A :");
for(i=1;i<=m;i++)
{ printf("\n");
for(j=1;j<=n;j++)
printf("%d",A[j][i]);
}
printf("\n MATRIX B :");
for(i=1;i<=p;i++)
{ printf("\n");
for(j=1;j<=q;j++)
printf("%d",B[j][i]);
}
break;
case 6:for(i=1;i<=m;i++)
{ for(j=1;j<=n;j++)
{ if(A[i][j]==A[j][i])
flag=1;
else
{ flag=0;
break;
}
}
}
if(flag)
printf("\nThe matrix A is symmetric.");

MAIT/CSE 55 | P a g e
else
printf("\nThe matrix A is not symmetric.");
for(i=1;i<=p;i++)
{ for(j=1;j<=q;j++)
{ if(B[i][j]==B[j][i])
flag=1;
else
{ flag=0;
break;
}
}
}
if(flag)
printf("\nThe matrix B is symmetric.");
else
printf("\nThe matrix B is not symmetric.");
break;

case 7:if(m==q&&n==p)
{ for(i=1;i<=m;i++)
{ for(j=1;j<=n;j++)
C[i][j]=0;
}
for(i=1;i<=m;i++)
{ for(j=1;j<=n;j++)
{ for(k=1;k<=n;k++)
{ C[i][j]=C[i][j]+A[i][k]*B[k][j];
}
}
}
}
printf("\nThe product of the two matrices are :");
for(i=1;i<=m;i++)
{ printf("\n");
for(j=1;j<=n;j++)
printf(" %d",C[i][j]);
}
break;

default:printf("SORRY!!! WRONG CHOICE...");


}
getch();
}

MAIT/CSE 56 | P a g e
OBJECTIVE:

WRITE A PROGRAM THAT TAKES TWO OPERANDS AND ONE OPERATOR


FROM THE USER. PERFORM THE OPERATION AND PRINT THE ANSWER

The aim of this program is to use concept of switch case and to show its implementation. In the
program some basic mathematical operations like ADDITION, SUBTRACTION,
MULTIPLICATION and DIVISION are to perform over two operands and the result is to
output. Choice of operation is decided by the user by giving the operator also as input.

Switch case is the condition based control statement which allows user to make a decision from
the number of choices.

Switch( integer expression )


{
case constant 1 :
do this
break;

case constant 2 :
do this;
break;

case constant 3 :
do this;
break;

default
do this;
break;
}

This is necessary for students to get knowledge of the switch case statement. Importance of break
statement also needs to be understood.

STEPS TO CREATE THE PROBLEM:

For programming the problem, number of cases to be included in switch case should be equal to
the number of operations for which the user is going to have choice.
case 1 for addition
case 2 for subtraction
case 3 for multiplication
case 4 for division

Then the user would have a choice of giving the operator +, _, *, / as input.

MAIT/CSE 57 | P a g e
So we have

Switch(ch) // ch is a character variable take opearator


// input from the user
{
case’*’ :
// when user enter * as operator
// multipliacation

case ‘+’ :
// when user enter + as operator
// addition is done in this case.

case’-’ :
// when the user enter – as operator
// subtraction is done in this case.

case‘/’:
// when user enter / as operator
// division is done in this case.

Initially two variables have to be declared which are going to store the value of two numbers
given by the user. Another variable (say choice) is also need to be declared which is used to take
input of operator of the users choice. Depending upon the choice, one of the case from switch
case statement is executed and operation is performed.

MAIT/CSE 58 | P a g e
Flow Chart to make a calculator in which operator is entered by the user.

Flow Chart

START

Read a,b

Enter the
operator

C=+ C=a+b

Print
C= - sum=c
C=a-b

Print C=a*b
C= *
diff=c

Print
prod=c
C=a/b C= /

Print
div=c

STOP

MAIT/CSE 59 | P a g e
//program: to build a calculator

#include<stdio.h>

#include<conio.h>

main()

int a,b;

char ch,ch1;

clrscr();

do

clrscr();

printf("\n\t\tEnter the value of a : ");

scanf("%d",&a);

printf("\n\t\tEnter the value of b : ");

scanf("%d",&b);

printf("\n\t\tEnter the operator(+|-|*|/) : ");

ch = getche();

switch(ch)

case '+' : printf("\n\n\t\tThe sum of %d + %d = %d",a,b,a+b);

break;

case '-' : printf("\n\n\t\tThe difference of %d - %d = %d",a,b,a-b);

break;

case '*' : printf("\n\n\t\tThe product of %d * %d = %d",a,b,a*b);

MAIT/CSE 60 | P a g e
break;

case '/' : printf("\n\n\t\tThe quotient of %d / %d = %d",a,b,a/b);

break;

default : printf("\a\a\n\n\t\tWrong operator...");

printf("\n\n\t\tDo u want to continue(Y/N) :");

ch1 = getche();

}while(ch1 == 'Y' || ch1 == 'y');

clrscr();

printf("\n\n\n\n\t\tThe programe is terminated...");

getch();

return 0;

/*

OUTPUT

Enter the value of a : 12

Enter the value of b : 12

Enter the operator(+|-|*|/) : +

The sum of 12 + 12 = 24

Do u want to continue(Y/N) : n

The programe is terminated...

*/

MAIT/CSE 61 | P a g e
OBJECTIVE:

WRITE A PROGRAMTO DRAW ATREE LIKE STRUCTURE AS SHOWN BELOW:

a) 1
22
333
4444

b) 1
2 2
3 3 3
4 4 4 4

LOGIC APPLIED:
The aim of this program is to draw a tree like structure using the for loop i.e the program
needs the logical concept for the loop. the students have to think the logic of using the
nested for the loop ,how and when to change the line using new line character ,where and
how to leave the spaces.

Program should take the input for a variable (which tell that how much lines should be
printed as 4 in above shown figure) from the user. and then make the tree like structure.

MAIT/CSE 62 | P a g e
FLOWCHART

START

I=1

J=1

PRINT I
PRINT”I”
J=J+1

J<=1

Print new line

I=I+1

I<=4

STOP

MAIT/CSE 63 | P a g e
//programe : to print a triangle of specified pattern

#include<stdio.h>
#include<conio.h>

main()
{
int n,i=1,x=0;
clrscr();
printf("\n\n\t\tEnter the no. of lines : ");
scanf("%d",&n);
while(i<=n)
{
x=1;
printf("\n");
while(x<=i)
{
printf("%d ",i);
x++;
}
i++;
}
getch();
return 0;
}

/*OUTPUT
Enter the no. of lines : 5
1
22
333
4444
55555
*/

MAIT/CSE 64 | P a g e
OBJECTIVE:

TO FIND THE SUM OF GEOMETRIC SERIES

Logic-
this program can be done in two ways either by direct formula or by using for loop.

1.using for loop we can add the terms of the series one by one.and can get the sum.
2.there is a direct formula i n mathematics in which no for loop is required.
Formula is- sum=a*((pow(r,n)-1)/(r-1)
Where a=the first term of the series.
R=common ratio
N=no. Of terms
we have to use a header file <math.h>.so that we can used the power function and hence the
result can be displayed on the screen.

To solve the sum of the series-value of a,r,n are entered by the user .and the computer compile
it and either by using any of the two methods we can get the output which is displayed on the
screen.

MAIT/CSE 65 | P a g e
FLOW CHART

START

INPUT
a,r,n

i=0
i=i+1

Is
I<=n-1

Sum=sum+ a*pow(r,I)

PRINT
SUM

STOP

MAIT/CSE 66 | P a g e
//program to print the sum of a geometric series
#include<stdio.h>
#include<conio.h>
#include<iostream.h>
#include<math.h>

main()
{
int a,n;float r,t;
float s=0.0;
clrscr();
printf("Enter the first term :");
scanf("%d",&a);
printf("\nEnter common ratio :");
scanf("%f",&r);
printf("\nEnter number of terms :");
scanf("%d",&n);
printf("\nThe geometric series is :\n");
for(int i=0;i<n;i++)
{
t=a*pow(r,i);
printf("%f\n", t);
s+=t;
}
printf("\nThe sum of the series is :%f",s);
getch();
return 0;
}

/*
OUTPUT

Enter the value of a : 2

Enter the common ratio : 3

Enter the no. of terms : 5

The sum of the series is : 242

*/

MAIT/CSE 67 | P a g e
OBJECTIVE:

TO FIND WHEATHER A GIVEN THREE DIGIT NUMBER IS PALINDROME OR


NOT.

In the given program the user has to input a three digit integer and it will check wheather the
number is a palindrome or not.A PALINDROME is a word,phrase or a number that reads the
same backwards as forwards.For example madam or number 343.
The logic behind the program is to check the digit at the one's place and at hundred's place for
equality.If the two digits are equal the the number is a palindrome.
In the program,three variables of type integer are declared say num,a and b.In num the number is
entered,then using the statement:

a=num/100;

The value of digit at hundred's place is taken as another integer for checking.
Similarly using the statement:

b=num%10;

The value of digit at one's place is taken.


These two numbers are compared using if-else:

if(a==b)
{
printf("The number is a palindrome.");
}
else
{
printf("The number is not a palindrome.");
}

MAIT/CSE 68 | P a g e
MAIT/CSE 69 | P a g e
//Program to find wheather the number is palindrome or not

#include<stdio.h>
#include<conio.h>
void main()
{
int n1,a,b;
clrscr();
printf("Enter the three digit number: ");
scanf("%d",&n1);
a=n1/100;
b=n1%10;
if(a==b)
{
printf("The number is a palindrome.");
}
else
printf("The number is not a palindrome.");
getch();
}

/*OUTPUT
Enter the three digit number: 232
The number is a palindrome.
Enter the three digit number: 648
The number is not a palindrome. */

MAIT/CSE 70 | P a g e
Viva Questions
 Complete the following:
1. C has been developed by ______________ in the year _______ while working at
_____________.
2. Maximum allowable width of a variable in Turbo C is ______ characters.
3. First characters in any variable name must always be an __________.
4. C variables are case ____________.
5. A character variable can at a time store _____ character(s).
 What do you mean by data types? Explain different types of data types with examples?
 What do you mean by operators? What is precedence of operators?
 What are different input and output functions?
 Deference between while and do-while loop control structures?
 What do you mean by Break?
 What do you mean by Continue?
 Explain the difference between Break and Continue?
 What do you mean by ternary operator?
 Explain drawbacks of switch-case structure?
 Explain drawbacks of decision control structures?
 What do you mean by arrays? Explain with example? Different types and uses of arrays?
 What are functions? Different types of this and why we use it?
 What do you mean by recursion?
 What do you mean by preprocessor? Explain different directives with examples?
 What are different storage classes in C?
 What are structures?
 What are unions?
 Explain the difference between structures and unions?
 What do you mean by strings? Explain with examples?

 What will be the output of the following programs?


1.

MAIT/CSE 71 | P a g e
Main()
{
char j=1;
while(j<=255)
{
printf(“%d\n”, j);
j=j+1;
}
}

2.
main()
{
int j=1;
while(j<=255)
{
printf(“%c %d\n”, j, j);
j++;
}
}

3.
main()
{
int j=1;
while(j<=255)
printf(“%d\n”, ++j);
}

4.
main()
{
int a;
for(a=1;a<=32767;a++)
printf(“%d”, a);
}

5.
main()
{
int I;
for(I =1;I++<=5;printf(“%d”, I ));
}

6.
main()

MAIT/CSE 72 | P a g e
{
int I=1, j=1;
for(;j;printf(“%d %d\n”, I, j))
j=I++<=5;
}

7.
main()
{
int I=1;
for(;I++;)
printf(“%d”, i);
}

8.
main()
{
int a=5;
do
{
printf(“%d\n”, a);
a=-1;
}while(a>0);
}
9.

main()
{
int a=3,b=4;
b%=3+4;
a*=a+5;
printf(“b=%d a =%d”, b, a);
}

10.
main()
{
int x=3;
x*=x+4;
printf(“x=%d”,x);
}

MAIT/CSE 73 | P a g e
Questions with answers:
Section 1
1. How do you decide which integer type to use?

A: If you might need large values (tens of thousands), use long.


Otherwise, if space is very important, use short. Otherwise,
use int.
2. What should the 64-bit type on a machine that can support it?

A: C9X specifies long long.

3. What's the best way to declare and define global variables?

A: The best arrangement is to place each definition in some


relevant .c file, with an external declaration in a header file.

4. What does extern mean in a function declaration?

A: Nothing, really; the keyword extern is optional here.

5. What's the auto keyword good for?

A: Nothing.

6. I can't seem to define a linked list node which contains a


pointer to itself.

A: Structures in C can certainly contain pointers to themselves;


the discussion and example in section 6.5 of K&R make this
clear. Problems arise if an attempt is made to define (and use)
a typedef in the midst of such a declaration; avoid this.

7. How do I declare an array of N pointers to functions returning


pointers to functions returning pointers to characters?

A: char *(*(*a[N])())();
Using a chain of typedefs, or the cdecl program, makes these
declarations easier.

8. How can I declare a function that returns a pointer to a


function of its own type?

A: You can't quite do it directly. Use a cast, or wrap a struct


around the pointer and return that.

9. My compiler is complaining about an invalid redeclaration of a

MAIT/CSE 74 | P a g e
function, but I only define it once.

A: Calling an undeclared function declares it implicitly as


returning int.

10. What's the right declaration for main()?

A: See questions 11.12a to 11.15.

11. What am I allowed to assume about the initial values


of variables which are not explicitly initialized?

A: Uninitialized variables with "static" duration start out as 0,


as if the programmer had initialized them. Variables with
"automatic" duration, and dynamically-allocated memory, start
out containing garbage (with the exception of calloc).

12. Why can't I initialize a local array with a string?

A: Perhaps you have a pre-ANSI compiler.

13. What's wrong with "char *p = malloc(10);" ?

A: Function calls are not allowed in initializers for global or


static variables.

14. What is the difference between char a[] = "string"; and


char *p = "string"; ?

A: The first declares an initialized and modifiable array; the


second declares a pointer initialized to a not-necessarily-
modifiable constant string.

15. How do I initialize a pointer to a function?

A: Use something like "extern int func(); int (*fp)() = func;" .

Section 2. Structures, Unions, and Enumerations

16. What's the difference between struct x1 { ... }; and


typedef struct { ... } x2; ?

A: The first structure is named by a tag, the second by a typedef


name.

MAIT/CSE 75 | P a g e
17. Why doesn't "struct x { ... }; x thestruct;" work?

A: C is not C++.

18. an a structure contain a pointer to itself?

A: See question 1.14.

19. What's the best way of implementing opaque (abstract) data types
in C?

A: One good way is to use structure pointers which point to


structure types which are not publicly defined.

20. I came across some code that declared a structure with the last
member an array of one element, and then did some tricky
allocation to make it act like the array had several elements.
Is this legal or portable?

A: An official interpretation has deemed that it is not strictly


conforming with the C Standard.

21. I heard that structures could be assigned to variables and


passed to and from functions, but K&R1 says not.

A: These operations are supported by all modern compilers.

22. Is there a way to compare structures automatically?

A: No.

23. Can I pass constant values to functions which accept structure


arguments?

A: Not yet. As of this writing, C has no way of generating


anonymous structure values.

24. How can I read/write structures from/to data files?

A: It is relatively straightforward to use fread and fwrite.

25. How can I turn off structure padding?

A: There is no standard method.

26. Why does sizeof report a larger size than I expect for a

MAIT/CSE 76 | P a g e
structure type?

A: The alignment of arrays of structures must be preserved.

27. How can I determine the byte offset of a field within a


structure?

A: ANSI C defines the offsetof() macro, which should be used if


available.

28. How can I access structure fields by name at run time?

A: Build a table of names and offsets, using the offsetof() macro.

29. I have a program which works correctly, but dumps core after it
finishes. Why?

A: Check to see if a structure type declaration just before main()


is missing its trailing semicolon, causing main() to be declared
as returning a structure. See also questions 10.9 and 16.4.

30. Can I initialize unions?

A: The current C Standard allows an initializer for the first-named


member.

31. What is the difference between an enumeration and a set of


preprocessor #defines?

A: At the present time, there is little difference. The C Standard


states that enumerations are compatible with integral types.

32. Is there an easy way to print enumeration values symbolically?

A: No.

Section 3.Expressions

33. Why doesn't the code "a[i] = i++;" work?

A: The variable i is both referenced and modified in the same expression.

34. Under my compiler, the code "int i = 7;


printf("%d\n", i++ * i++);" prints 49. Regardless of the order
of evaluation, shouldn't it print 56?

MAIT/CSE 77 | P a g e
A: The operations implied by the postincrement and postdecrement operators ++ and -- are
performed at some time after the operand's former values are yielded and before the end of the
expression, but not necessarily immediately after, or before other parts of the expression are
evaluated.

35. What should the code "int i = 3; i = i++;" do?

A: The expression is undefined.

36. Here's a slick expression: "a ^= b ^= a ^= b". It swaps a and b


without using a temporary.

A: Not portably; its behavior is undefined.

37. Don't precedence and parentheses dictate order of evaluation?

38. Here's a slick expression: "a ^= b ^= a ^= b". It swaps a and b without using a
temporary.

A: Not portably; its behavior is undefined.

39. Don't precedence and parentheses dictate order of evaluation?

A: Operator precedence and explicit parentheses impose only a partial ordering on the
evaluation of an expression, which does not generally include the order of side effects.

40. But what about the && and || operators?

A: There is a special exception for those operators: left-to-right evaluation is guaranteed.

41. What's a "sequence point"?

A: A point (at the end of a full expression, or at the ||, &&, ?: or comma operators, or just
before a function call) at which all side effects are guaranteed to be complete.

42. So given a[i] = i++; we don't know which cell of a[] gets written to, but i does get
incremented by one, right?

A: *No*. Once an expression or program becomes undefined, *all* aspects of it become


undefined.

43. If I'm not using the value of the expression, should I use i++ or ++i to increment a
variable?

MAIT/CSE 78 | P a g e
A: Since the two forms differ only in the value yielded, they are entirely equivalent when only
their side effect is needed.

44. Why doesn't the code "int a = 1000, b = 1000;


long int c = a * b;" work?

A: You must manually cast one of the operands to (long).

45. Can I use ?: on the left-hand side of an assignment expression?

A: No.

Section 4. Pointers

46. What's wrong with "char *p; *p = malloc(10);"?

A: The pointer you declared is p, not *p.

47. Does *p++ increment p, or what it points to?

A: *p++ increments p. To increment the value pointed to by p, use


(*p)++ .

48. I want to use a char * pointer to step over some ints. Why doesn't "((int *)p)++;" work?

A: In C, a cast operator is a conversion operator, and by definition it yields an rvalue, which


cannot be assigned to, or incremented with ++.

49. I have a function which accepts, and is supposed to initialize, a pointer, but the pointer
in the caller remains unchanged.

A: The called function probably altered only the passed copy of the pointer.

50. Can I use a void ** pointer as a parameter so that a function can accept a generic
pointer by reference?

A: Not portably.

51. I have a function which accepts a pointer to an int. How can I pass a constant like 5 to
it?

A: You will have to declare a temporary variable.

52. Does C even have "pass by reference"?

MAIT/CSE 79 | P a g e
A: Not really, though it can be simulated.

53. I've seen different methods used for calling functions via

A: The extra parentheses and explicit * are now>

Transfer interrupted!

older implementations require them.

Section 5. Null Pointers

5.1: What is this infamous null pointer, anyway?

A: For each pointer type, there is a special value -- the "null pointer" -- which is
distinguishable from all other pointer values and which is not the address of any object or
function.

5.2: How do I get a null pointer in my programs?

A: A constant 0 in a pointer context is converted into a null pointer at compile time. A


"pointer context" is an initialization, assignment, or comparison with one side a variable or
expression of pointer type, and (in ANSI standard C) a function argument which has a prototype
in scope declaring a certain parameter as being of pointer type. In other contexts (function
arguments without prototypes, or in the variable part of variadic function calls) a constant 0 with
an appropriate explicit cast is required.

5.3: Is the abbreviated pointer comparison "if(p)" to test for non- null pointers valid?

A: Yes. The construction "if(p)" works, regardless of the internal representation of null
pointers, because the compiler essentially rewrites it as "if(p != 0)" and goes on to convert 0 into
the correct null pointer.

5.4: What is NULL and how is it #defined?

A: NULL is simply a preprocessor macro, #defined as 0 (or ((void *)0)), which is used (as a
stylistic convention, in preference to unadorned 0's) to generate null pointers.

5.5: How should NULL be defined on a machine which uses a nonzero bit pattern as the
internal representation of a null pointer?

A: The same as on any other machine: as 0. (The compiler makes the translation, upon seeing
a 0, not the preprocessor; see also question 5.4.)

MAIT/CSE 80 | P a g e
5.6: If NULL were defined as "((char *)0)," wouldn't that make function calls which pass an
uncast NULL work?

A: Not in general. The complication is that there are machines which use different internal
representations for pointers to different types of data. A cast is still required to tell the compiler
which kind of null pointer is required, since it may be different from (char *)0.

5.9: If NULL and 0 are equivalent as null pointer constants, which should I use?

A: Either; the distinction is entirely stylistic.

5.10: But wouldn't it be better to use NULL, in case the value of NULL changes?

A: No. NULL is a constant zero, so a constant zero is equally sufficient.

5.12: I use the preprocessor macro "#define Nullptr(type) (type *)0" to help me build null
pointers of the correct type.

A: This trick, though valid, does not buy much.

5.13: This is strange. NULL is guaranteed to be 0, but the null pointer is not?

A: A "null pointer" is a language concept whose particular internal value does not matter. A
null pointer is requested in source code with the character "0". "NULL" is a preprocessor macro,
which is always #defined as 0 (or ((void *)0)).

5.14: Why is there so much confusion surrounding null pointers?

A: The fact that null pointers are represented both in source code, and internally to most
machines, as zero invites unwarranted assumptions. The use of a preprocessor macro (NULL)
may seem to suggest that the value could change some day, or on some weird machine.

5.15: I'm confused. I just can't understand all this null pointer stuff.

A: A simple rule is, "Always use `0' or `NULL' for null pointers, and always cast them when
they are used as arguments in function calls."

5.16: Given all the confusion surrounding null pointers, wouldn't it be easier simply to require
them to be represented internally by zeroes?

A: Such a requirement would accomplish little.

5.17: Seriously, have any actual machines really used nonzero null pointers?

A: Machines manufactured by Prime, Honeywell-Bull, and CDC, as well as Symbolics Lisp


Machines, have done so.

MAIT/CSE 81 | P a g e
5.20: What does a run-time "null pointer assignment" error mean?

A: It means that you've written, via a null pointer, to an invalid location. (See also question
16.8.)

Section 6. Arrays and Pointers

6.1: I had the definition char a[6] in one source file, and in another I declared extern char *a.
Why didn't it work?

A: The declaration extern char *a simply does not match the actual definition. Use extern
char a[].

6.2: But I heard that char a[] was identical to char *a.

A: Not at all. Arrays are not pointers. A reference like x[3] generates different code
depending on whether x is an array or a pointer.

6.3: So what is meant by the "equivalence of pointers and arrays" in C?

A: An lvalue of type array-of-T which appears in an expression decays into a pointer to its
first element; the type of the resultant pointer is pointer-to-T. So for an array a and pointer p,
you can say "p = a;" and then p[3] and a[3] will access the same element.

6.4: Why are array and pointer declarations interchangeable as function formal parameters?

A: It's supposed to be a convenience.

6.7: How can an array be an lvalue, if you can't assign to it?

A: An array is not a "modifiable lvalue."

6.8: What is the real difference between arrays and pointers?

A: Arrays automatically allocate space which is fixed in size and location; pointers are
dynamic.

6.9: Someone explained to me that arrays were really just constant pointers.

A: An array name is "constant" in that it cannot be assigned to, but an array is *not* a pointer.

6.11: I came across some "joke" code containing the "expression" 5["abcdef"] . How can this
be legal C?

MAIT/CSE 82 | P a g e
A: Yes, array subscripting is commutative in C. The array subscripting operation a[e] is
defined as being identical to *((a)+(e)).

6.12: What's the difference between array and &array?

A: The type.

6.13: How do I declare a pointer to an array?

A: Usually, you don't want to. Consider using a pointer to one of the array's elements instead.

6.14: How can I set an array's size at run time?

A: It's straightforward to use malloc() and a pointer.

6.15: How can I declare local arrays of a size matching a passed-in array?

A: Until recently, you couldn't; array dimensions had to be compile- time constants. C9X
will fix this.

6.16: How can I dynamically allocate a multidimensional array?

A: The traditional solution is to allocate an array of pointers, and then initialize each pointer
to a dynamically-allocated "row." See the full list for code samples.

6.17: Can I simulate a non-0-based array with a pointer?

A: Not if the pointer points outside of the block of memory it is intended to access.

6.18: My compiler complained when I passed a two-dimensional array to a function expecting a


pointer to a pointer.

A: The rule by which arrays decay into pointers is not applied recursively. An array of arrays
(i.e. a two-dimensional array in C) decays into a pointer to an array, not a pointer to a pointer.

6.19: How do I write functions which accept two-dimensional arrays when the width is not
known at compile time?

A: It's not always particularly easy.

6.20: How can I use statically- and dynamically-allocated multidimensional arrays


interchangeably when passing them to functions?

A: There is no single perfect method, but see the full list for some ideas.

6.21: Why doesn't sizeof properly report the size of an array which is a parameter to a function?

MAIT/CSE 83 | P a g e
A: The sizeof operator reports the size of the pointer parameter which the function actually
receives.

Section 7. Memory Allocation

7.1: Why doesn't the code "char *answer; gets(answer);" work?

A: The pointer variable answer has not been set to point to any
valid storage. The simplest way to correct this fragment is to use a local array, instead of a
pointer.

7.2: I can't get strcat() to work. I tried "char *s3 = strcat(s1, s2);" but I got strange results.

A: Again, the main problem here is that space for the concatenated result is not properly
allocated.

7.3: But the man page for strcat() says that it takes two char *'s as arguments. How am I
supposed to know to allocate things?

A: In general, when using pointers you *always* have to consider memory allocation, if only
to make sure that the compiler is doing it for you.

7.3b: I just tried the code "char *p; strcpy(p, "abc");" and it worked. Why didn't it crash?

A: You got "lucky".

7.3c: How much memory does a pointer variable allocate?

A: Only enough memory to hold the pointer itself, not any memory for the pointer to point to.

7.5a: I have a function that is supposed to return a string, but when it returns to its caller, the
returned string is garbage.

A: Make sure that the pointed-to memory is properly (i.e. not locally) allocated.

7.5b: So what's the right way to return a string?

A: Return a pointer to a statically-allocated buffer, a buffer passed in by the caller, or memory


obtained with malloc().

7.6: Why am I getting "warning: assignment of pointer from integer lacks a cast" for calls to
malloc()?

A: Have you #included <stdlib.h>?

MAIT/CSE 84 | P a g e
7.7: Why does some code carefully cast the values returned by malloc to the pointer type being
allocated?

A: Before ANSI/ISO C, these casts were required to silence certain warnings.

7.8: Why does so much code leave out the multiplication by sizeof(char) when allocating
strings?

A: Because sizeof(char) is, by definition, exactly 1.

7.14: I've heard that some operating systems don't actually allocate malloc'ed memory until the
program tries to use it. Is this legal?

A: It's hard to say.

7.16: I'm allocating a large array for some numeric work, but malloc() is acting strangely.

A: Make sure the number you're trying to pass to malloc() isn't bigger than a size_t can hold.

7.17: I've got 8 meg of memory in my PC. Why can I only seem to malloc 640K or so?

A: Under the segmented architecture of PC compatibles, it can be difficult to use more than
640K with any degree of transparency. See also question 19.23.

7.19: My program is crashing, apparently somewhere down inside malloc.

A: Make sure you aren't using more memory than you malloc'ed, especially for strings (which
need strlen(str) + 1 bytes).

7.20: You can't use dynamically-allocated memory after you free it,
can you?

A: No. Some early documentation implied otherwise, but the claim is no longer valid.

7.21: Why isn't a pointer null after calling free()?

A: C's pass-by-value semantics mean that called functions can never permanently change the
values of their arguments.

7.22: When I call malloc() to allocate memory for a local pointer, do I have to explicitly free()
it?

A: Yes.

MAIT/CSE 85 | P a g e
7.23: When I free a dynamically-allocated structure containing pointers, do I also have to free
each subsidiary pointer?

A: Yes.

7.24: Must I free allocated memory before the program exits?

A: You shouldn't have to.

7.25: Why doesn't my program's memory usage go down when I free memory?

A: Most implementations of malloc/free do not return freed memory to the operating system.

7.26: How does free() know how many bytes to free?

A: The malloc/free implementation remembers the size of each block as it is allocated.

7.27: So can I query the malloc package to find out how big an allocated block is?

A: Not portably.

7.30: Is it legal to pass a null pointer as the first argument to realloc()?

A: ANSI C sanctions this usage, although several earlier implementations do not support it.

7.31: What's the difference between calloc() and malloc()?

A: calloc() takes two arguments, and initializes the allocated memory to all-bits-0.

7.32: What is alloca() and why is its use discouraged?

A: alloca() allocates memory which is automatically freed when the function which called
alloca() returns. alloca() cannot be written portably, is difficult to implement on machines
without a stack, and fails under certain conditions if implemented simply.

Section 8. Characters and Strings

8.1: Why doesn't "strcat(string, '!');" work?

A: strcat() concatenates *strings*, not characters.

8.2: Why won't the test if(string == "value") correctly compare string against the value?

A: It's comparing pointers. To compare two strings, use strcmp().

8.3: Why can't I assign strings to character arrays?

MAIT/CSE 86 | P a g e
A: Strings are arrays, and you can't assign arrays directly. Use strcpy() instead.

8.6: How can I get the numeric (character set) value corresponding to a character?

A: In C, if you have the character, you have its value.

8.9: Why is sizeof('a') not 1?

A: Character constants in C are of type int.

Section 9. Boolean Expressions and Variables

9.1: What is the right type to use for Boolean values in C?

A: There's no one right answer; see the full list for some discussion.

9.2: What if a built-in logical or relational operator "returns" something other than 1?

A: When a Boolean value is generated by a built-in operator, it is guaranteed to be 1 or 0.


(This is *not* true for some library routines such as isalpha.)

9.3: Is if(p), where p is a pointer, valid?

A: Yes. See question 5.3.

Section 10. C Preprocessor

10.2: I've got some cute preprocessor macros that let me write C code that looks more like
Pascal. What do y'all think?

A: Bleah.

10.3: How can I write a generic macro to swap two values?

A: There is no good answer to this question. The best all-around solution is probably to
forget about using a macro.

10.4: What's the best way to write a multi-statement macro?

A: #define Func() do {stmt1; stmt2; ... } while(0) /* (no trailing ;) */

10.6: What are .h files and what should I put in them?

MAIT/CSE 87 | P a g e
A: Header files (also called ".h files") should generally contain common declarations and
macro, structure, and typedef definitions, but not variable or function definitions.

10.7: Is it acceptable for one header file to #include another?

A: It's a question of style, and thus receives considerable debate.

10.8a: What's the difference between #include <> and #include "" ?

A: Roughly speaking, the <> syntax is for Standard headers and "" is for project headers.

10.8b: What are the complete rules for header file searching?

A: The exact behavior is implementation-defined; see the full list for some discussion.

10.9: I'm getting strange syntax errors on the very first declaration in a file, but it looks fine.

A: Perhaps there's a missing semicolon at the end of the last declaration in the last header file
you're #including.

10.10b: I'm #including the header file for a function, but the linker keeps saying it's undefined.

A: See question 13.25.

10.11: Where can I get a copy of a missing header file?

A: Contact your vendor, or see question 18.16 or the full list.

10.12: How can I construct preprocessor #if expressions which compare strings?

A: You can't do it directly; try #defining several manifest constants and implementing
conditionals on those.

10.13: Does the sizeof operator work in preprocessor #if directives?

A: No.

10.14: Can I use an #ifdef in a #define line, to define something two different ways?

A: No.

10.15: Is there anything like an #ifdef for typedefs?

A: Unfortunately, no.

10.16: How can I use a preprocessor #if expression to detect endianness?

MAIT/CSE 88 | P a g e
A: You probably can't.

10.18: How can I preprocess some code to remove selected conditional compilations, without
preprocessing everything?

A: Look for a program called unifdef, rmifdef, or scpp.

10.19: How can I list all of the predefined identifiers?

A: If the compiler documentation is unhelpful, try extracting printable strings from the
compiler or preprocessor executable.

10.20: I have some old code that tries to construct identifiers with a macro like "#define Paste(a,
b) a/**/b", but it doesn't work any more.

A: Try the ANSI token-pasting operator ##.

10.22: What does the message "warning: macro replacement within a string literal" mean?

A: See question 11.18.

10.23-4: I'm having trouble using macro arguments inside string literals, using the `#' operator.

A: See questions 11.17 and 11.18.

10.25: I've got this tricky preprocessing I want to do and I can't figure out a way to do it.

A: Consider writing your own little special-purpose preprocessing tool, instead.

10.26: How can I write a macro which takes a variable number of arguments?

A: Here is one popular trick. Note that the parentheses around printf's argument list are in the
macro call, not the definition.

#define DEBUG(args) (printf("DEBUG: "), printf args)

if(n != 0) DEBUG(("n is %d\n", n));

Section 11. ANSI/ISO Standard C

11.1: What is the "ANSI C Standard?"

MAIT/CSE 89 | P a g e
A: In 1983, the American National Standards Institute (ANSI) commissioned a committee to
standardize the C language. Their work was ratified as ANS X3.159-1989, and has since been
adopted as ISO/IEC 9899:1990, and later amended.

11.2: How can I get a copy of the Standard?

A: Copies are available from ANSI in New York, or from Global Engineering Documents in
Englewood, CO, or from any national standards body, or from ISO in Geneva, or republished
within one or more books. See the unabridged list for details.

11.2b: Where can I get information about updates to the Standard?

A: See the full list for pointers.

11.3: My ANSI compiler is complaining about prototype mismatches for parameters declared
float.

A: You have mixed the new-style prototype declaration "extern int func(float);" with the old-
style definition "int func(x) float x;". "Narrow" types are treated differently according to which
syntax is used. This problem can be fixed by avoiding narrow types, or by using either new-style
(prototype) or old-style syntax consistently.

11.4: Can you mix old-style and new-style function syntax?

A: Doing so is currently legal, for most argument types (see question 11.3).

11.5: Why does the declaration "extern int f(struct x *p);" give me a warning message?

A: A structure declared (or even mentioned) for the first time within a prototype cannot be
compatible with other structures declared in the same source file.

11.8: Why can't I use const values in initializers and array dimensions?

A: The value of a const-qualified object is *not* a constant expression in the full sense of the
term.

11.9: What's the difference between "const char *p" and "char * const p"?

A: The former declares a pointer to a constant character; the latter declares a constant pointer
to a character.

11.10: Why can't I pass a char ** to a function which expects a const char **?

A: The rule which permits slight mismatches in qualified pointer assignments is not applied
recursively.

MAIT/CSE 90 | P a g e
11.12a: What's the correct declaration of main()?

A: int main(int argc, char *argv[]) .

11.12b: Can I declare main() as void, to shut off these annoying "main returns no value"
messages?

A: No.

11.13: But what about main's third argument, envp?

A: It's a non-standard (though common) extension.

11.14: I believe that declaring void main() can't fail, since I'm calling exit() instead of returning.

A: It doesn't matter whether main() returns or not, the problem is that its caller may not even
be able to *call* it correctly.

11.15: The book I've been using always uses void main().

A: It's wrong.

11.16: Is exit(status) truly equivalent to returning the same status from main()?

A: Yes and no. (See the full list for details.)

11.17: How do I get the ANSI "stringizing" preprocessing operator `#' to stringize the macro's
value instead of its name?

A: You can use a two-step #definition to force a macro to be expanded as well as stringized.

11.18: What does the message "warning: macro replacement within a string literal" mean?

A: Some pre-ANSI compilers/preprocessors expanded macro parameters even inside string


literals and character constants.

11.19: I'm getting strange syntax errors inside lines I've #ifdeffed out.

A: Under ANSI C, #ifdeffed-out text must still consist of "valid preprocessing tokens." This
means that there must be no newlines inside quotes, and no unterminated comments or quotes
(i.e. no single apostrophes).

11.20: What are #pragmas ?

A: The #pragma directive provides a single, well-defined "escape hatch" which can be used
for extensions.

MAIT/CSE 91 | P a g e
11.21: What does "#pragma once" mean?

A: It is an extension implemented by some preprocessors to help make header files


idempotent.

11.22: Is char a[3] = "abc"; legal?

A: Yes, in ANSI C.

11.24: Why can't I perform arithmetic on a void * pointer?

A: The compiler doesn't know the size of the pointed-to objects.

11.25: What's the difference between memcpy() and memmove()?

A: memmove() offers guaranteed behavior if the source and destination arguments overlap.

11.26: What should malloc(0) do?

A: The behavior is implementation-defined.

11.27: Why does the ANSI Standard not guarantee more than six case-insensitive characters of
external identifier significance?

A: The problem is older linkers which cannot be forced (by mere words in a Standard) to
upgrade.

11.29: My compiler is rejecting the simplest possible test programs, with all kinds of syntax
errors.

A: Perhaps it is a pre-ANSI compiler.

11.30: Why are some ANSI/ISO Standard library functions showing up as undefined, even
though I've got an ANSI compiler?

A: Perhaps you don't have ANSI-compatible headers and libraries.

11.31: Does anyone have a tool for converting old-style C programs to ANSI C, or for
automatically generating prototypes?

A: See the full list for details.

11.32: Why won't frobozz-cc, which claims to be ANSI compliant, accept this code?

A: Are you sure that the code being rejected doesn't rely on some non-Standard extension?

MAIT/CSE 92 | P a g e
11.33: What's the difference between implementation-defined, unspecified, and undefined
behavior?

A: If you're writing portable code, ignore the distinctions. Otherwise, see the full list.

11.34: I'm appalled that the ANSI Standard leaves so many issues undefined.

A: In most of these cases, the Standard is simply codifying existing practice.

11.35: I just tried some allegedly-undefined code on an ANSI-conforming compiler, and got the
results I expected.

A: A compiler may do anything it likes when faced with undefined behavior, including doing
what you expect.

Section 12. Stdio

12.1: What's wrong with the code "char c; while((c = getchar()) != EOF) ..."?

A: The variable to hold getchar's return value must be an int.

12.2: Why won't the code "while(!feof(infp)) {


fgets(buf, MAXLINE, infp); fputs(buf, outfp); }" work?

A: EOF is only indicated *after* an input routine fails.

12.4: My program's prompts and intermediate output don't always show up on the screen.

A: It's best to use an explicit fflush(stdout) whenever output should definitely be visible.

12.5: How can I read one character at a time, without waiting for the RETURN key?

A: See question 19.1.

12.6: How can I print a '%' character with printf?

A: "%%".

12.9: How can printf() use %f for type double, if scanf() requires %lf?

A: C's "default argument promotions" mean that values of type float are promoted to double.

12.9b: What printf format should I use for a typedef when I don't know the underlying type?

MAIT/CSE 93 | P a g e
A: Use a cast to convert the value to a known type, then use the printf format matching that
type.

12.10: How can I implement a variable field width with printf?

A: Use printf("%*d", width, x).

12.11: How can I print numbers with commas separating the thousands?

A: There is no standard routine (but see <locale.h>).

12.12: Why doesn't the call scanf("%d", i) work?

A: The arguments you pass to scanf() must always be pointers.

12.13: Why doesn't the code "double d; scanf("%f", &d);" work?

A: Unlike printf(), scanf() uses %lf for double, and %f for float.

12.15: How can I specify a variable width in a scanf() format string?

A: You can't.

12.17: When I read numbers from the keyboard with scanf "%d\n", it seems to hang until I type
one extra line of input.

A: Try using "%d" instead of "%d\n".

12.18: I'm reading a number with scanf %d and then a string with gets(), but the compiler seems
to be skipping the call to gets()!

A: scanf() and gets() do not work well together.

12.19: I'm re-prompting the user if scanf() fails, but sometimes it seems to go into an infinite
loop.

A: scanf() tends to "jam" on bad input since it does not discard it.

12.20: Why does everyone say not to use scanf()? What should I use instead?

A: scanf() has a number of problems. Usually, it's easier to read entire lines and then interpret
them.

12.21: How can I tell how much destination buffer space I'll need for an arbitrary sprintf call?
How can I avoid overflowing the destination buffer with sprintf()?

MAIT/CSE 94 | P a g e
A: Use the new snprintf() function, if you can.

12.23: Why does everyone say not to use gets()?

A: It cannot be prevented from overflowing the input buffer.

12.24: Why does errno contain ENOTTY after a call to printf()?

A: Don't worry about it. It is only meaningful for a program to inspect the contents of errno
after an error has been reported.

12.25: What's the difference between fgetpos/fsetpos and ftell/fseek?

A: fgetpos() and fsetpos() use a special typedef which may allow them to work with larger
files than ftell() and fseek().

12.26: Will fflush(stdin) flush unread characters from the standard input stream?

A: No.

12.30: I'm trying to update a file in place, by using fopen mode "r+", but it's not working.

A: Be sure to call fseek between reading and writing.

12.33: How can I redirect stdin or stdout from within a program?

A: Use freopen().

12.34: Once I've used freopen(), how can I get the original stream back?

A: There isn't a good way. Try avoiding freopen.

12.36b: How can I arrange to have output go two places at once?

A: You could write your own printf variant which printed everything twice. See question
15.5.

12.38: How can I read a binary data file properly?

A: Be sure to specify "rb" mode when calling fopen().

Section 13. Library Functions

13.1: How can I convert numbers to strings?

MAIT/CSE 95 | P a g e
A: Just use sprintf().

13.2: Why does strncpy() not always write a '\0'?

A: For mildly-interesting historical reasons.

13.5: Why do some versions of toupper() act strangely if given an upper-case letter?

A: Older versions of toupper () and tolower () did not always work as expected in this regard.

13.6: How can I split up a string into white space-separated fields?

A: Try strtok().

13.7: I need some code to do regular expression and wildcard matching.

A: regexp libraries abound; see the full list for details.

13.8: I'm trying to sort an array of strings with qsort(), using strcmp() as the comparison
function, but it's not working.

A: You'll have to write a "helper" comparison function which takes two generic pointer
arguments, converts them to char **, and dereferences them, yielding char *'s which can be
usefully compared.

13.9: Now I'm trying to sort an array of structures, but the compiler is complaining that the
function is of the wrong type for qsort().

A: The comparison function must be declared as accepting "generic pointers" (const void *)
which it then converts to structure pointers.

13.10: How can I sort a linked list?

A: Algorithms like insertion sort and merge sort work well, or you can keep the list in order
as you build it.

13.11: How can I sort more data than will fit in memory?

A: You want an "external sort"; see the full list for details.

13.12: How can I get the time of day in a C program?

A: Just use the time(), ctime(), localtime() and/or strftime() functions.

13.13: How can I convert a struct tm or a string into a time_t?

MAIT/CSE 96 | P a g e
A: The ANSI mktime() function converts a struct tm to a time_t. No standard routine exists
to parse strings.

13.14: How can I perform calendar manipulations?

A: The ANSI/ISO Standard C mktime() and difftime() functions provide some support for
both problems.

13.14b: Does C have any Year 2000 problems?

A: No, although poorly-written C programs do. Make sure you know that tm_year holds the
value of the year minus 1900.

13.15: I need a random number generator.

A: The Standard C library has one: rand().

13.16: How can I get random integers in a certain range?

A: One method is something like

(int)((double)rand() / ((double)RAND_MAX + 1) * N)

13.17: Each time I run my program, I get the same sequence of numbers back from rand().

A: You can call srand() to seed the pseudo-random number generator with a truly random
initial value.

13.18: I need a random true/false value, so I'm just taking rand () % 2, but it's alternating 0, 1, 0,
1, 0...

A: Try using the higher-order bits: see question 13.16.

13.20: How can I generate random numbers with a normal or Gaussian distribution?

A: See the longer versions of this list for ideas.

13.24: I'm trying to port this old program. Why do I get "undefined external" errors for some
library functions?

A: Some semi standard functions have been renamed or replaced over the years; see the full
list for details.

13.25: I get errors due to library functions being undefined even though I #include the right
header files.

MAIT/CSE 97 | P a g e
A: You may have to explicitly ask for the correct libraries to be searched.

13.26: I'm still getting errors due to library functions being undefined, even though I'm
requesting the right libraries.

A: Library search order is significant; usually, you must search the libraries last.

13.28: What does it mean when the linker says that _end is undefined?

A: You generally get that message only when other symbols are undefined, too.

Section 14. Floating Point

14.1: When I set a float variable to 3.1, why is printf printing it as 3.0999999?

A: Most computers use base 2 for floating-point numbers, and many fractions (including 0.1
decimal) are not exactly representable in base 2.

14.2: Why is sqrt(144.) giving me crazy numbers?

A: Make sure that you have #included <math.h>, and correctly declared other functions
returning double.

14.3: I keep getting "undefined: sin" compilation errors.

A: Make sure you're actually linking with the math library.

14.4: My floating-point calculations are acting strangely and giving me different answers on
different machines.

A: First, see question 14.2 above. If the problem isn't that simple, see the full list for a brief
explanation, or any good programming book for a better one.

14.5: What's a good way to check for "close enough" floating-point equality?

A: The best way is to use an accuracy threshold which is relative to the magnitude of the
numbers being compared.

14.6: How do I round numbers?

A: For positive numbers, try (int)(x + 0.5) .

14.7: Where is C's exponentiation operator?

A: Try using the pow() function.

MAIT/CSE 98 | P a g e

Vous aimerez peut-être aussi