TO Programming: ETCS-154
TO Programming: ETCS-154
TO Programming: ETCS-154
INTRODUCTION
TO
PROGRAMMING
ETCS-154
MAIT/CSE 1|Page
INDEX OF THE CONTENTS
5. Projects to be allotted
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:
C language
AIM
Date
Logic of the program
Input given (code written)
Output
Viva questions
MAIT/CSE 3|Page
2. LAB REQUIREMENTS
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
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.
Front page
Acknowledgement
Index
Abstract
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.
MAIT/CSE 9|Page
INTRODUCTION TO PROGRAMMING
PRACTICAL RECORD
Branch :
Section/ Group :
PRACTICAL DETAILS
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).
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 :
( ) ( )
MAIT/CSE 14 | P a g e
7. MARKING SCHEME FOR THE PRACTICAL EXAMS
There will be two practical exams in each semester.
Total Marks: 40
1. Regularity: 25
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.
Total Marks: 60
b. Viva Voice: 15
c. Experiment performance: 15
d. File submitted: 10
NOTE:
MAIT/CSE 16 | P a g e
8. DETAILS OF DIFFERENT SECTION
ALONGWITH EXAMPLES
&
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
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:
Example:
# include<stdio.h>
1.Header files
#include<conio.h>
clrscr();
}
9. Closing braces
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:
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.
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.
MAIT/CSE 22 | P a g e
SYNTAX : datatype variable name;
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
‘int’ is called as the data type. Various types of data types used in C language are as
follows:
1. Integer int
E.g.2, 3, 4, 5 etc.
2. Floating value
3. Character value
int a;
float b;
char c;
a b c
Integer value float value character
value
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.
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.
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).
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);
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;
Variables
a b c
3 5 8
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.
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 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
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.
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.
MAIT/CSE 32 | P a g e
STATEMENTS
Pre defined functions are those functions which have predefined meaning in the C
language.
There are many other functions which will be taken in the lab in details.
OPERATORS
NOTE:
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.
Condition to be
tested
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;
………………………..
……………………….
while(test condition)
Statement 1;
Statement 2;
Statement 3;
………………………..
……………………….
MAIT/CSE 35 | P a g e
SYNTAX of do-while loop:
do
Statement 1;
Statement 2;
Statement 3;
………………………..
……………………….
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
case 1 : statement 1;
statement 2;
…………..
…………..
break;
case 2 : statement 1;
statement 2;
…………..
…………..
break;
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).
FUNCTION MEANING
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);
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:
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.
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
MAIT/CSE 42 | P a g e
OBJECTIVE:
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.
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: -
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;
getch();
/*Output:
enter a number:5
*/
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.
(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.
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 */
MAIT/CSE 48 | P a g e
OBJECTIVE:
1+1/2+1/3+1/4+1/5+……………….+1/20
MAIT/CSE 49 | P a g e
Flow Chart:
Start
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:
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
Step 1: declare three arrays, two for two matrices and third for the resultant matrix
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;
MAIT/CSE 56 | P a g e
OBJECTIVE:
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.
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.
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
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();
scanf("%d",&a);
scanf("%d",&b);
ch = getche();
switch(ch)
break;
break;
MAIT/CSE 60 | P a g e
break;
break;
ch1 = getche();
clrscr();
getch();
return 0;
/*
OUTPUT
The sum of 12 + 12 = 24
Do u want to continue(Y/N) : n
*/
MAIT/CSE 61 | P a g e
OBJECTIVE:
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
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:
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
*/
MAIT/CSE 67 | P a g e
OBJECTIVE:
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;
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?
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: Nothing.
A: char *(*(*a[N])())();
Using a chain of typedefs, or the cdecl program, makes these
declarations easier.
MAIT/CSE 74 | P a g e
function, but I only define it once.
MAIT/CSE 75 | P a g e
17. Why doesn't "struct x { ... }; x thestruct;" work?
A: C is not C++.
19. What's the best way of implementing opaque (abstract) data types
in C?
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: No.
26. Why does sizeof report a larger size than I expect for a
MAIT/CSE 76 | P a g e
structure type?
29. I have a program which works correctly, but dumps core after it
finishes. Why?
A: No.
Section 3.Expressions
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.
38. Here's a slick expression: "a ^= b ^= a ^= b". It swaps a and b without using a
temporary.
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.
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?
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.
A: No.
Section 4. Pointers
48. I want to use a char * pointer to step over some ints. Why doesn't "((int *)p)++;" work?
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?
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
Transfer interrupted!
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.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.
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?
5.10: But wouldn't it be better to use NULL, in case the value of NULL changes?
5.12: I use the preprocessor macro "#define Nullptr(type) (type *)0" to help me build null
pointers of the correct type.
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)).
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?
5.17: Seriously, have any actual machines really used nonzero null pointers?
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.)
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.
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: 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)).
A: The type.
A: Usually, you don't want to. Consider using a pointer to one of the array's elements instead.
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.
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.
A: Not if the pointer points outside of the block of memory it is intended to access.
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: 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.
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: 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.6: Why am I getting "warning: assignment of pointer from integer lacks a cast" for calls to
malloc()?
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?
7.8: Why does so much code leave out the multiplication by sizeof(char) when allocating
strings?
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?
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.
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.
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.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.27: So can I query the malloc package to find out how big an allocated block is?
A: Not portably.
A: ANSI C sanctions this usage, although several earlier implementations do not support it.
A: calloc() takes two arguments, and initializes the allocated memory to all-bits-0.
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.
8.2: Why won't the test if(string == "value") correctly compare string against the value?
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: 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?
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.
A: There is no good answer to this question. The best all-around solution is probably to
forget about using a macro.
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.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.
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.
A: No.
10.14: Can I use an #ifdef in a #define line, to define something two different ways?
A: No.
A: Unfortunately, no.
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: 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.
10.22: What does the message "warning: macro replacement within a string literal" mean?
10.23-4: I'm having trouble using macro arguments inside string literals, using the `#' operator.
10.25: I've got this tricky preprocessing I want to do and I can't figure out a way to do it.
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.
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.
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.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.
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()?
11.12b: Can I declare main() as void, to shut off these annoying "main returns no value"
messages?
A: No.
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()?
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?
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).
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: Yes, in ANSI C.
A: memmove() offers guaranteed behavior if the source and destination arguments overlap.
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.
11.30: Why are some ANSI/ISO Standard library functions showing up as undefined, even
though I've got an ANSI compiler?
11.31: Does anyone have a tool for converting old-style C programs to ANSI C, or for
automatically generating prototypes?
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.
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.
12.1: What's wrong with the code "char c; while((c = getchar()) != EOF) ..."?
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: "%%".
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.11: How can I print numbers with commas separating the thousands?
A: Unlike printf(), scanf() uses %lf for double, and %f for float.
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.
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()!
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.
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.
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: Use freopen().
12.34: Once I've used freopen(), how can I get the original stream back?
A: You could write your own printf variant which printed everything twice. See question
15.5.
MAIT/CSE 95 | P a g e
A: Just use sprintf().
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.
A: Try strtok().
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.
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.
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.
A: The ANSI/ISO Standard C mktime() and difftime() functions provide some support for
both problems.
A: No, although poorly-written C programs do. Make sure you know that tm_year holds the
value of the year minus 1900.
(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...
13.20: How can I generate random numbers with a normal or Gaussian distribution?
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.
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.
A: Make sure that you have #included <math.h>, and correctly declared other functions
returning double.
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.
MAIT/CSE 98 | P a g e