SlideShare a Scribd company logo
3
Most read
6
Most read
12
Most read
C Programming
(Assignment –I)
Submitted in partial fulfilment of the requirements for the degree of
Post Graduate Diploma in Information Technology
by
Vijayananda D Mohire
(Registration No.200508208)
Information Technology Department
Symbiosis Bhavan,
1065 B, Gokhale Cross
Road, Model Colony, Pune – 411016,
Maharashtra, India
(2007)
2
3
C Programming
4
Table of Contents
QUESTION 1 ......................................................................................................................................................................... 6
ANSWER 1(A)....................................................................................................................................................................... 6
ANSWER 1(B)....................................................................................................................................................................... 6
QUESTION 2 ......................................................................................................................................................................... 7
ANSWER 2 ............................................................................................................................................................................ 7
QUESTION 3 .......................................................................................................................................................................10
ANSWER 3 ..........................................................................................................................................................................10
QUESTION 4 .......................................................................................................................................................................11
ANSWER 4 ..........................................................................................................................................................................11
QUESTION 5 .......................................................................................................................................................................12
ANSWER 5 ..........................................................................................................................................................................12
QUESTION 6 .......................................................................................................................................................................13
ANSWER 6 ..........................................................................................................................................................................13
QUESTION 7 .......................................................................................................................................................................15
ANSWER 7 ..........................................................................................................................................................................15
QUESTION 8 .......................................................................................................................................................................16
ANSWER 8 ..........................................................................................................................................................................16
QUESTION 9 .......................................................................................................................................................................18
ANSWER 9 ..........................................................................................................................................................................18
QUESTION 10.....................................................................................................................................................................19
ANSWER 10........................................................................................................................................................................19
QUESTION 11.....................................................................................................................................................................20
ANSWER 11........................................................................................................................................................................20
5
C Programming
6
Question 1 Write algorithm for the following:
a) To check whether an entered number is odd / even.
b) To calculate sum of three numbers.
Answer 1(a)
Code:
# include <stdio.h>
main (void)
{
int input; /* define variable to store user input */
int mod; /* define variable to store modulus 2 output */
clrscr(); /* Clear screen*/
do
{
printf ("n Please enter a Number(Enter Zero to Quit): n");
scanf("%d", &input); /* Get the formatted Input number */
mod = input%2; /* Modulus 2 operation that returns 0 if number is even.*/
if (mod == 0) /* Check if the return value and output as Even or Odd */
printf ("%s", "Number is Evenn");
else
printf("%s", "Number is oddn");
} while (input != 0);
}
Answer 1(b)
Code:
# include <stdio.h>
# include <math.h>
main(void)
7
{
int i,j,k,sum; /* define variable to store user inputs and sum */
clrscr(); /* Clear screen*/
printf (" Enter Number 1:n");
scanf ("%d",&i); /* Get the formatted Input number 1 */
printf ("n Enter Number 2:n");
scanf ("%d",&j); /* Get the formatted Input number 2 */
printf ("n Enter Number 3:n");
scanf ("%d",&k); /* Get the formatted Input number 3 */
sum = i+j+k; /* Calculate the Sum of the 3 inputs */
printf ("Sum of 3 Numbers is:n%d",sum); /* Prints the calculated sum */
getch(); /* Pause so that results are visible */
}
HINT: You can put this in a do while loop and check an increment counter
Evaluator‟s Comments if any:
Question 2 Write short notes on the following:
a) C Variables
Answer 2
Like most programming languages, C is able to use and process named variables and
their contents.
8
Variables are most simply described as names by which we refer to some location in
memory - a location that holds a value with which we are working. It often helps to
think of variables as a "pigeonhole", or a placeholder for a value. You can think of a
variable as being equivalent to its value. So, if you have a variable i that is initialized
to 4, i+1 will equal 5.
All variables in C are typed. That is, you must give a type for every variable you
declare.
C data types
In Standard C there are four basic data types. They are int, char, float, and double.
The int type
The int type stores integers in the form of "whole numbers". An integer is typically
the size of one machine word, which on most modern home PCs is 32 bits (4 octets).
Examples of literals are whole numbers (integers) such as 1, 2, 3, 10, 100... When int
is 32 bits (4 octets), it can store any whole number (integer) between -2147483648
and 2147483647. A 32 bit word (number) has the possibility of representing
4294967296 numbers (2 to the power of 32).
If you want to declare a new int variable, use the int keyword. For example:
int numberOfStudents, i, j=5;
In this declaration we declare 3 variables, numberOfStudents, i & j, j here is assigned
the literal 5.
The char type
The char type is similar to the int type, yet it is only big enough to hold one ASCII
character. It stores the same kind of data as an int (i.e. integers), but always has a
size of one byte. It is most often used to store character data, hence its name.
Examples of character literals are 'a', 'b', '1', etc., as well as special characters such
as '0' (the null character) and 'n' (endline, recall "Hello, World").
When we initialize a character variable, we can do it two ways. One is preferred,
the other way is bad programming practice.
The first way is to write : char letter1='a';
This is good programming practice in that it allows a person reading your code to
understand that letter is being initialized with the letter "a" to start off with.
9
The second way, which should not be used when you are coding letter characters, is
to write : char letter2=97; /* in ASCII, 97 = 'a' */
This is considered by some to be extremely bad practice, if we are using it to store a
character, not a small number, in that if someone reads your code, most readers are
forced to look up what character corresponds with the number 97 in the encoding
scheme.
There is one more kind of literal that needs to be explained in connection with
chars: the string literal. A string is a series of characters, usually intended to be
output to the string. They are surrounded by double quotes (" ", not ' '). An example
of a string literal is the "Hello, world!n" in the "Hello, World" example.
The float type
float is short for Floating Point. It stores real numbers also, but is only one machine
word in size. Therefore, it is used when less precision than a double provides is
required. float literals must be suffixed with F or f, otherwise they will be
interpreted as doubles. Examples are: 3.1415926f, 4.0f, 6.022e+23f. float variables
can be declared using the float keyword.
The double type
The double and float types are very similar. The float type allows you to store single-
precision floating point numbers, while the double keyword allows you to store
double-precision floating point numbers - real numbers, in other words, both integer
and non-integer values. Its size is typically two machine words, or 8 bytes on most
machines. Examples of double literals are 3.1415926535897932, 4.0, 6.022e+23
(scientific notation). If you use 4 instead of 4.0, the 4 will be interpreted as an int.
Evaluator‟s Comments if any:
10
Question 3 Accept principal amount, rate of interest, and duration from the
user. Display Interest Amount and Total Amount (Principal + Interest).
Answer 3
Code:
#include <stdio.h>
main (void)
{
/* define variable to store Principal, Percentage Rate of Interest,Time, Interest
amount and Total amount */
float PrincipalAmt, PercRateofInt, RateofInt, Time, IntAmt, TotalAmt;
clrscr(); /* Clear screen*/
printf("Enter Principal Amount:n");
scanf("%f", &PrincipalAmt); /* Get the formatted Principal Amount */
printf("Enter Percentage Rate of Interest:n");
scanf("%f", &PercRateofInt); /* Get the formatted Percentage rate of Interest*/
printf("Enter the Duration in years:n");
scanf("%f", &Time);/* Get the formatted Time period in years */
RateofInt = PercRateofInt/100; /* Convert Percentage to float equivalent for Rate
of Interest*/
IntAmt = PrincipalAmt*RateofInt*Time; /* Compute Interest Amount using P*R*T
formula */
TotalAmt = PrincipalAmt+IntAmt; /* Compute Total Amount using P+I formula */
printf("Interest Amt is:n%fn",IntAmt); /* Prints the computed Interest */
printf("Total Amt is:n%f",TotalAmt); /* Prints the computed Total amount */
getch(); /* Pause so that results are visible */
}
11
Question 4 Accept any number from the user. Display whether the number is
divisible by 100 or not.
Answer 4
Code:
main (void)
{
int Num, Remainder; /* define variable to store Number and Remainder */
clrscr(); /* Clear screen*/
printf ("Enter a Number:n");
scanf ("%d",&Num); /* Get the formatted Number */
Remainder = Num % 100; /* Divide the Number by 100 and get the remainder */
if ( Remainder == 0 ) /* check if the Remainder is equal to zero or no, so that the
divisibility can be printed */
printf("Entered Number is divisible by 100n");
else
printf("Entered Number is not divisible by 100n");
getch(); /* Pause so that results are visible */
}
Evaluator‟s Comments if any:
12
Question 5 Write a program to swap the values of two numbers. Do this using
call by reference method of function.
Answer 5
Code:
#include < stdio.h > void swap(int * firstnum, int * secondnum); /* function
prototype for call by ref*/
main(void) {
int firstnum, secondnum; /* define variables to store entered numbers */
clrscr(); /* Clear screen*/
printf("Please enter first Number:");
scanf("%d", & firstnum); /* Get the formatted firstnumber */
printf("Please enter second number:");
scanf("%d", & secondnum); /* Get the formatted secondnumber */
printf("nBefore Swamp, firstnum is: %dt, secondnum is: %dn", firstnum,
secondnum);
/* Pass the numbers to be swapped, pass by reference */
swap( & firstnum, & secondnum);
printf("After swap, firstnum is: %dt, secondnum is: %dn", firstnum,
secondnum);
getch(); /* Pause so that results are visible */
}
13
void swap(int * first, int * second) {
int temp; /* define variables for temporary storage */
temp = * second; /* Assign the value of second to temp variable */
* second = * first; /* Assign the value of the first to second variable */
* first = temp; /* Assign the value of the temporary variable to first variable */
}
Question 6 Accept a month in digit from the user. Display the month in words. If
number is not between 1 and 12 display message “Invalid Month”. (Use „switch‟)
Answer 6
Code:
#include <stdio.h>
main()
{
int month; /* define variable to store entered month */
clrscr(); /* Clear screen*/
printf("Enter the Month in range 1-12:n");
scanf("%d",&month); /* Get the formatted month */
if (month < 1) /* Signal error is entered integer is not within range 1 to 12 */
printf("Invalid Month, please enter in valid range");
if (month > 12)
printf("Invalid Month, please enter in valid range");
printf("n");
switch (month) /* Use the switch case to control what needs to be printed */
{
case 1:
printf("You entered January");
break;
14
case 2:
printf("You entered February");
break;
case 3:
printf("You entered March");
break;
case 4:
printf("You entered April");
break;
case 5:
printf("You entered May");
break;
case 6:
printf("You entered June");
break;
case 7:
printf("You entered July");
break;
case 8:
printf("You entered August");
break;
case 9:
printf("You entered September");
break;
case 10:
printf("You entered October");
break;
case 11:
printf("You entered November");
break;
case 12:
printf(" You entered December");
break;
default:
break;
15
}
getch(); /* Pause so that results are visible */
}
Question 7 Accept any two numbers from the user. Using pointers swap the
values two numbers without using third variable
Answer 7
#include<stdio.h>
void swap(int *firstnum, int *secondnum);/* function prototype for call by ref*/
main()
{
int firstnum, secondnum; /* define variables to store entered numbers */
clrscr();/* Clear screen*/
printf("Please enter first Number:");
scanf("%d",&firstnum); /* Get the formatted firstnumber */
printf("Please enter second number:");
scanf("%d",&secondnum); /* Get the formatted secondnumber */
printf("nBefore Swamp, firstnum is: %dt, secondnum is: %dn",
firstnum,secondnum);
swap(&firstnum,&secondnum); /* Pass the numbers to be swapped, pass by
reference */
printf("After swap, firstnum is: %dt, secondnum is: %dn",firstnum,secondnum);
getch(); /* Pause for results */
}
void swap(int *firstnum, int *secondnum)
16
{
if( firstnum!=secondnum)
{
/* Use the ^ operator to swap without temp variable*/
*firstnum ^= *secondnum;
*secondnum ^= *firstnum;
*firstnum ^= *secondnum;
} }
Question 8 Create a structure to store the employee number, name,
department and basic salary. Create an array of structure to accept and display
the values of 10 employees
Answer 8
Code:
#include <stdio.h>
#include <ctype.h>
void main()
{
struct emp /* Structure declaration */
{
int empnum;
int basicsal;
char name[20];
char dept[20];
} ;
struct emp My_emps[10]; /* Structure array declaration */
int hcount = 0; /* Count of the number of EMPS */
int i = 0; /* Loop counter */
char test = '0'; /* Test value for ending */
17
clrscr();
for(hcount = 0; hcount < 10 ; hcount++ )
{
printf("nDo you want to enter details of a%s employee (Y or N)? ",
hcount?"nother " : "" );
scanf(" %c", &test );
if(tolower(test) == 'n')
break;
printf("nEnter the name of the employee: " );
scanf("%s", My_emps[hcount].name ); /* Read the emp's name */
printf("nEnter employee number: " );
scanf("%d", &My_emps[hcount].empnum ); /* Read the emp's num */
printf("n Enter dept of employee: " );
scanf("%s", My_emps[hcount].dept );
printf("nEnter basic salary: ");
scanf("%d",&My_emps[hcount].basicsal );
}
/* Now display the employee details */
for (i = 0 ; i < hcount ; i++ )
{
printf("nnEmp%d: %st%dt%st%d",
i,My_emps[i].name, My_emps[i].empnum,
My_emps[i].dept,My_emps[i].basicsal);
}
getch(); / * Pause for viewing results */
}
18
Question 9 Accept a file name from the user. Display the contents of the file.
Also add the entered string to the file.
Answer 9
Code:
#include <stdio.h>
#include <io.h>
#include <stdlib.h>
int main()
{
FILE *fp; /* define file pointer variable */
char fname[100];
char s[100];
int t;
clrscr();/ Clear screen*/
printf("Enter filename( Eg: Vijay.txtn");
scanf("%s",fname); /* Get the formatted filename */
printf("%s",fname);
if((fp = fopen(fname,"a")) == NULL)
{
printf("cannot open file.n");
exit(1);/* Exit if there is error opening file */
}
printf("nEnter a string:"); /* Get the entered string */
fscanf(stdin,"%s",s);
fprintf(fp,"%sn",s); /* Append the value to the file */
fclose(fp);
if((fp = fopen(fname,"r"))== NULL)
{
printf("cannot open file.n");
exit(1); /* Exot if error opening file */
}
19
fscanf(fp,"%s",s);
/* Display the contents*/
fprintf(stdout," File created in current dir and the updated content: %s",s);
getch();
return 0;
}
Question 10 Accept any number as a command line argument. Write a program to
display the number in reverse order.
Instructions: Please run this from Command prompt to see correct results.
Answer 10
Code:
#include <stdio.h>
#include <string.h>
main (int argc,char *argv[])
{
int p=1,c=0,i, j; /* define variable and let p point to arg 1*/
char copy[10];
clrscr(); /* Clear screen*/
printf("Entered Number is: %sn", argv[p]);
strcpy(copy,argv[p]); /* Copy the command line argv[1] data to local variable */
printf("copy %sn", copy);
for(i=0,j=strlen(copy)-1;i <j;i++,j--) /* reverse the chars from the local variable */
{
c =copy[i];
copy[i] = copy[j];
20
copy[j] =c;
}
printf("copy after rev %sn",copy); /* print out the reversed string */
getch(); /* pause to view results*/
}
Question 11 Write a short note on enum
Answer 11
enum is the abbreviation for ENUMERATE, and we can use this keyword to declare
and initialize a sequence of integer constants. Here's an example:
enum colors {RED, YELLOW, GREEN, BLUE};
Here, colors is the name given to the set of constants. Now, if you don't assign a
value to a constant, the default value for the first one in the list - RED in our case,
has the value of 0. The rest of the undefined constants have a value 1 more than the
one before, so in our case, YELLOW is 1, GREEN is 2 and BLUE is 3.
But you can assign values if you wanted to:
enum colors { RED=1, YELLOW, GREEN=6, BLUE };
Now RED=1, YELLOW=2, GREEN=6 and BLUE=7.
The main advantage of enum is that if you don't initialize your constants, each one
would have a unique value. The first would be zero and the rest would then count
upwards.

More Related Content

What's hot (20)

PPTX
Representation of binary tree in memory
Rohini Shinde
 
PPTX
Union in C programming
Kamal Acharya
 
PPTX
Array Of Pointers
Sharad Dubey
 
PPTX
data types in C programming
Harshita Yadav
 
PPSX
Type conversion
Frijo Francis
 
PPT
Modular programming
Mohanlal Sukhadia University (MLSU)
 
PPTX
Input output statement in C
Muthuganesh S
 
PPTX
Strings in C
Kamal Acharya
 
PPTX
Pointers in C Programming
Jasleen Kaur (Chandigarh University)
 
PPTX
Graph data structure
Tech_MX
 
PPT
Constants in C Programming
programming9
 
PPTX
Loops in C Programming Language
Mahantesh Devoor
 
PPTX
Operators and expressions in c language
tanmaymodi4
 
PPTX
String Manipulation in Python
Pooja B S
 
PPT
Arrays in c
vampugani
 
PDF
Operator overloading
Pranali Chaudhari
 
PDF
Python programming : Control statements
Emertxe Information Technologies Pvt Ltd
 
PPTX
Type conversion
PreethaPreetha5
 
PPT
Clipping
Mohd Arif
 
Representation of binary tree in memory
Rohini Shinde
 
Union in C programming
Kamal Acharya
 
Array Of Pointers
Sharad Dubey
 
data types in C programming
Harshita Yadav
 
Type conversion
Frijo Francis
 
Input output statement in C
Muthuganesh S
 
Strings in C
Kamal Acharya
 
Pointers in C Programming
Jasleen Kaur (Chandigarh University)
 
Graph data structure
Tech_MX
 
Constants in C Programming
programming9
 
Loops in C Programming Language
Mahantesh Devoor
 
Operators and expressions in c language
tanmaymodi4
 
String Manipulation in Python
Pooja B S
 
Arrays in c
vampugani
 
Operator overloading
Pranali Chaudhari
 
Python programming : Control statements
Emertxe Information Technologies Pvt Ltd
 
Type conversion
PreethaPreetha5
 
Clipping
Mohd Arif
 

Similar to C Programming Assignment (20)

DOC
C language
SMS2007
 
PPTX
C programming(part 3)
Dr. SURBHI SAROHA
 
PPTX
Interview Questions For C Language .pptx
Rowank2
 
PPTX
basic C PROGRAMMING for first years .pptx
divyasindhu040
 
PDF
Interview Questions For C Language
Rowank2
 
PDF
C Language Interview Questions: Data Types, Pointers, Data Structures, Memory...
Rowank2
 
PPTX
C++ lecture 01
HNDE Labuduwa Galle
 
PPT
UNIT 1 PY .ppt - PYTHON PROGRAMMING BASICS
drkangurajuphd
 
DOCX
c++ best code.docxhsdsdcvcdcdvdvdvdvdcdv
LegesseSamuel1
 
PPT
C language
vishnu kumar prajapati
 
PDF
C programming_MSBTE_Diploma_Pranoti Doke
Pranoti Doke
 
PPTX
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
ANUSUYA S
 
PPTX
LESSON1-C_programming (1).GRADE 8 LESSONpptx
joachimbenedicttulau
 
PDF
C programming language
Mahmoud Eladawi
 
PPTX
PPS_unit_2_gtu_sem_2_year_2023_GTUU.pptx
ZwecklosSe
 
PPTX
PROGRAMMING IN C - Inroduction.pptx
Nithya K
 
PDF
Week 02_Development Environment of C++.pdf
salmankhizar3
 
PPTX
unit 1 (1).pptx
PriyadarshiniS28
 
PPTX
Structured Languages
Mufaddal Nullwala
 
C language
SMS2007
 
C programming(part 3)
Dr. SURBHI SAROHA
 
Interview Questions For C Language .pptx
Rowank2
 
basic C PROGRAMMING for first years .pptx
divyasindhu040
 
Interview Questions For C Language
Rowank2
 
C Language Interview Questions: Data Types, Pointers, Data Structures, Memory...
Rowank2
 
C++ lecture 01
HNDE Labuduwa Galle
 
UNIT 1 PY .ppt - PYTHON PROGRAMMING BASICS
drkangurajuphd
 
c++ best code.docxhsdsdcvcdcdvdvdvdvdcdv
LegesseSamuel1
 
C programming_MSBTE_Diploma_Pranoti Doke
Pranoti Doke
 
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...
ANUSUYA S
 
LESSON1-C_programming (1).GRADE 8 LESSONpptx
joachimbenedicttulau
 
C programming language
Mahmoud Eladawi
 
PPS_unit_2_gtu_sem_2_year_2023_GTUU.pptx
ZwecklosSe
 
PROGRAMMING IN C - Inroduction.pptx
Nithya K
 
Week 02_Development Environment of C++.pdf
salmankhizar3
 
unit 1 (1).pptx
PriyadarshiniS28
 
Structured Languages
Mufaddal Nullwala
 
Ad

More from Vijayananda Mohire (20)

PDF
Bhadale QAI Hub - for multicloud, multitechnology platform
Vijayananda Mohire
 
PDF
Practical_Introduction_to_Quantum_Safe_Cryptography
Vijayananda Mohire
 
PDF
Progress Report- MIT Course 8.371.3x - VD-Mohire
Vijayananda Mohire
 
PDF
Quantum Communications Q&A with Gemini LLM
Vijayananda Mohire
 
PDF
Peer Review Certificate for Journal of Engg
Vijayananda Mohire
 
PDF
Quantum Algorithms for Electronics - IEEE Certificate
Vijayananda Mohire
 
PDF
NexGen Solutions for cloud platforms, powered by GenQAI
Vijayananda Mohire
 
PDF
Certificate- Peer Review of Book Chapter on ML
Vijayananda Mohire
 
PDF
Key projects Data Science and Engineering
Vijayananda Mohire
 
PDF
Key projects Data Science and Engineering
Vijayananda Mohire
 
PDF
Bhadale IT Hub-Multi Cloud and Multi QAI
Vijayananda Mohire
 
PDF
My key hands-on projects in Quantum, and QAI
Vijayananda Mohire
 
PDF
Azure Quantum Workspace for developing Q# based quantum circuits
Vijayananda Mohire
 
PDF
Key projects in AI, ML and Generative AI
Vijayananda Mohire
 
PDF
My Journey towards Artificial Intelligence
Vijayananda Mohire
 
PDF
Bhadale IT Cloud Solutions for Agriculture
Vijayananda Mohire
 
PDF
Bhadale IT Cloud Solutions for Agriculture
Vijayananda Mohire
 
PDF
Bhadale IT Intel and Azure Cloud Offerings
Vijayananda Mohire
 
PDF
GitHub Copilot-vijaymohire
Vijayananda Mohire
 
PDF
Practical ChatGPT From Use Cases to Prompt Engineering & Ethical Implications
Vijayananda Mohire
 
Bhadale QAI Hub - for multicloud, multitechnology platform
Vijayananda Mohire
 
Practical_Introduction_to_Quantum_Safe_Cryptography
Vijayananda Mohire
 
Progress Report- MIT Course 8.371.3x - VD-Mohire
Vijayananda Mohire
 
Quantum Communications Q&A with Gemini LLM
Vijayananda Mohire
 
Peer Review Certificate for Journal of Engg
Vijayananda Mohire
 
Quantum Algorithms for Electronics - IEEE Certificate
Vijayananda Mohire
 
NexGen Solutions for cloud platforms, powered by GenQAI
Vijayananda Mohire
 
Certificate- Peer Review of Book Chapter on ML
Vijayananda Mohire
 
Key projects Data Science and Engineering
Vijayananda Mohire
 
Key projects Data Science and Engineering
Vijayananda Mohire
 
Bhadale IT Hub-Multi Cloud and Multi QAI
Vijayananda Mohire
 
My key hands-on projects in Quantum, and QAI
Vijayananda Mohire
 
Azure Quantum Workspace for developing Q# based quantum circuits
Vijayananda Mohire
 
Key projects in AI, ML and Generative AI
Vijayananda Mohire
 
My Journey towards Artificial Intelligence
Vijayananda Mohire
 
Bhadale IT Cloud Solutions for Agriculture
Vijayananda Mohire
 
Bhadale IT Cloud Solutions for Agriculture
Vijayananda Mohire
 
Bhadale IT Intel and Azure Cloud Offerings
Vijayananda Mohire
 
GitHub Copilot-vijaymohire
Vijayananda Mohire
 
Practical ChatGPT From Use Cases to Prompt Engineering & Ethical Implications
Vijayananda Mohire
 
Ad

Recently uploaded (20)

PDF
Telemedicine App Development_ Key Factors to Consider for Your Healthcare Ven...
Mobilityinfotech
 
PDF
capitulando la keynote de GrafanaCON 2025 - Madrid
Imma Valls Bernaus
 
PDF
AI Software Development Process, Strategies and Challenges
Net-Craft.com
 
PDF
Writing Maintainable Playwright Tests with Ease
Shubham Joshi
 
PPTX
ERP Systems in the UAE: Driving Business Transformation with Smart Solutions
dheeodoo
 
PPTX
IDM Crack with Internet Download Manager 6.42 [Latest 2025]
HyperPc soft
 
PDF
Best Software Development at Best Prices
softechies7
 
PDF
Which Hiring Management Tools Offer the Best ROI?
HireME
 
PDF
Why Edge Computing Matters in Mobile Application Tech.pdf
IMG Global Infotech
 
PPTX
Agentforce – TDX 2025 Hackathon Achievement
GetOnCRM Solutions
 
PDF
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
 
PPTX
IObit Driver Booster Pro 12.4-12.5 license keys 2025-2026
chaudhryakashoo065
 
PDF
Humans vs AI Call Agents - Qcall.ai's Special Report
Udit Goenka
 
PDF
Best Practice for LLM Serving in the Cloud
Alluxio, Inc.
 
DOCX
Best AI-Powered Wearable Tech for Remote Health Monitoring in 2025
SEOLIFT - SEO Company London
 
PPTX
IDM Crack with Internet Download Manager 6.42 Build 41 [Latest 2025]
pcprocore
 
PDF
IObit Uninstaller Pro 14.3.1.8 Crack for Windows Latest
utfefguu
 
PDF
Building scalbale cloud native apps with .NET 8
GillesMathieu10
 
PDF
Automated Testing and Safety Analysis of Deep Neural Networks
Lionel Briand
 
PDF
Designing Accessible Content Blocks (1).pdf
jaclynmennie1
 
Telemedicine App Development_ Key Factors to Consider for Your Healthcare Ven...
Mobilityinfotech
 
capitulando la keynote de GrafanaCON 2025 - Madrid
Imma Valls Bernaus
 
AI Software Development Process, Strategies and Challenges
Net-Craft.com
 
Writing Maintainable Playwright Tests with Ease
Shubham Joshi
 
ERP Systems in the UAE: Driving Business Transformation with Smart Solutions
dheeodoo
 
IDM Crack with Internet Download Manager 6.42 [Latest 2025]
HyperPc soft
 
Best Software Development at Best Prices
softechies7
 
Which Hiring Management Tools Offer the Best ROI?
HireME
 
Why Edge Computing Matters in Mobile Application Tech.pdf
IMG Global Infotech
 
Agentforce – TDX 2025 Hackathon Achievement
GetOnCRM Solutions
 
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
 
IObit Driver Booster Pro 12.4-12.5 license keys 2025-2026
chaudhryakashoo065
 
Humans vs AI Call Agents - Qcall.ai's Special Report
Udit Goenka
 
Best Practice for LLM Serving in the Cloud
Alluxio, Inc.
 
Best AI-Powered Wearable Tech for Remote Health Monitoring in 2025
SEOLIFT - SEO Company London
 
IDM Crack with Internet Download Manager 6.42 Build 41 [Latest 2025]
pcprocore
 
IObit Uninstaller Pro 14.3.1.8 Crack for Windows Latest
utfefguu
 
Building scalbale cloud native apps with .NET 8
GillesMathieu10
 
Automated Testing and Safety Analysis of Deep Neural Networks
Lionel Briand
 
Designing Accessible Content Blocks (1).pdf
jaclynmennie1
 

C Programming Assignment

  • 1. C Programming (Assignment –I) Submitted in partial fulfilment of the requirements for the degree of Post Graduate Diploma in Information Technology by Vijayananda D Mohire (Registration No.200508208) Information Technology Department Symbiosis Bhavan, 1065 B, Gokhale Cross Road, Model Colony, Pune – 411016, Maharashtra, India (2007)
  • 2. 2
  • 4. 4 Table of Contents QUESTION 1 ......................................................................................................................................................................... 6 ANSWER 1(A)....................................................................................................................................................................... 6 ANSWER 1(B)....................................................................................................................................................................... 6 QUESTION 2 ......................................................................................................................................................................... 7 ANSWER 2 ............................................................................................................................................................................ 7 QUESTION 3 .......................................................................................................................................................................10 ANSWER 3 ..........................................................................................................................................................................10 QUESTION 4 .......................................................................................................................................................................11 ANSWER 4 ..........................................................................................................................................................................11 QUESTION 5 .......................................................................................................................................................................12 ANSWER 5 ..........................................................................................................................................................................12 QUESTION 6 .......................................................................................................................................................................13 ANSWER 6 ..........................................................................................................................................................................13 QUESTION 7 .......................................................................................................................................................................15 ANSWER 7 ..........................................................................................................................................................................15 QUESTION 8 .......................................................................................................................................................................16 ANSWER 8 ..........................................................................................................................................................................16 QUESTION 9 .......................................................................................................................................................................18 ANSWER 9 ..........................................................................................................................................................................18 QUESTION 10.....................................................................................................................................................................19 ANSWER 10........................................................................................................................................................................19 QUESTION 11.....................................................................................................................................................................20 ANSWER 11........................................................................................................................................................................20
  • 6. 6 Question 1 Write algorithm for the following: a) To check whether an entered number is odd / even. b) To calculate sum of three numbers. Answer 1(a) Code: # include <stdio.h> main (void) { int input; /* define variable to store user input */ int mod; /* define variable to store modulus 2 output */ clrscr(); /* Clear screen*/ do { printf ("n Please enter a Number(Enter Zero to Quit): n"); scanf("%d", &input); /* Get the formatted Input number */ mod = input%2; /* Modulus 2 operation that returns 0 if number is even.*/ if (mod == 0) /* Check if the return value and output as Even or Odd */ printf ("%s", "Number is Evenn"); else printf("%s", "Number is oddn"); } while (input != 0); } Answer 1(b) Code: # include <stdio.h> # include <math.h> main(void)
  • 7. 7 { int i,j,k,sum; /* define variable to store user inputs and sum */ clrscr(); /* Clear screen*/ printf (" Enter Number 1:n"); scanf ("%d",&i); /* Get the formatted Input number 1 */ printf ("n Enter Number 2:n"); scanf ("%d",&j); /* Get the formatted Input number 2 */ printf ("n Enter Number 3:n"); scanf ("%d",&k); /* Get the formatted Input number 3 */ sum = i+j+k; /* Calculate the Sum of the 3 inputs */ printf ("Sum of 3 Numbers is:n%d",sum); /* Prints the calculated sum */ getch(); /* Pause so that results are visible */ } HINT: You can put this in a do while loop and check an increment counter Evaluator‟s Comments if any: Question 2 Write short notes on the following: a) C Variables Answer 2 Like most programming languages, C is able to use and process named variables and their contents.
  • 8. 8 Variables are most simply described as names by which we refer to some location in memory - a location that holds a value with which we are working. It often helps to think of variables as a "pigeonhole", or a placeholder for a value. You can think of a variable as being equivalent to its value. So, if you have a variable i that is initialized to 4, i+1 will equal 5. All variables in C are typed. That is, you must give a type for every variable you declare. C data types In Standard C there are four basic data types. They are int, char, float, and double. The int type The int type stores integers in the form of "whole numbers". An integer is typically the size of one machine word, which on most modern home PCs is 32 bits (4 octets). Examples of literals are whole numbers (integers) such as 1, 2, 3, 10, 100... When int is 32 bits (4 octets), it can store any whole number (integer) between -2147483648 and 2147483647. A 32 bit word (number) has the possibility of representing 4294967296 numbers (2 to the power of 32). If you want to declare a new int variable, use the int keyword. For example: int numberOfStudents, i, j=5; In this declaration we declare 3 variables, numberOfStudents, i & j, j here is assigned the literal 5. The char type The char type is similar to the int type, yet it is only big enough to hold one ASCII character. It stores the same kind of data as an int (i.e. integers), but always has a size of one byte. It is most often used to store character data, hence its name. Examples of character literals are 'a', 'b', '1', etc., as well as special characters such as '0' (the null character) and 'n' (endline, recall "Hello, World"). When we initialize a character variable, we can do it two ways. One is preferred, the other way is bad programming practice. The first way is to write : char letter1='a'; This is good programming practice in that it allows a person reading your code to understand that letter is being initialized with the letter "a" to start off with.
  • 9. 9 The second way, which should not be used when you are coding letter characters, is to write : char letter2=97; /* in ASCII, 97 = 'a' */ This is considered by some to be extremely bad practice, if we are using it to store a character, not a small number, in that if someone reads your code, most readers are forced to look up what character corresponds with the number 97 in the encoding scheme. There is one more kind of literal that needs to be explained in connection with chars: the string literal. A string is a series of characters, usually intended to be output to the string. They are surrounded by double quotes (" ", not ' '). An example of a string literal is the "Hello, world!n" in the "Hello, World" example. The float type float is short for Floating Point. It stores real numbers also, but is only one machine word in size. Therefore, it is used when less precision than a double provides is required. float literals must be suffixed with F or f, otherwise they will be interpreted as doubles. Examples are: 3.1415926f, 4.0f, 6.022e+23f. float variables can be declared using the float keyword. The double type The double and float types are very similar. The float type allows you to store single- precision floating point numbers, while the double keyword allows you to store double-precision floating point numbers - real numbers, in other words, both integer and non-integer values. Its size is typically two machine words, or 8 bytes on most machines. Examples of double literals are 3.1415926535897932, 4.0, 6.022e+23 (scientific notation). If you use 4 instead of 4.0, the 4 will be interpreted as an int. Evaluator‟s Comments if any:
  • 10. 10 Question 3 Accept principal amount, rate of interest, and duration from the user. Display Interest Amount and Total Amount (Principal + Interest). Answer 3 Code: #include <stdio.h> main (void) { /* define variable to store Principal, Percentage Rate of Interest,Time, Interest amount and Total amount */ float PrincipalAmt, PercRateofInt, RateofInt, Time, IntAmt, TotalAmt; clrscr(); /* Clear screen*/ printf("Enter Principal Amount:n"); scanf("%f", &PrincipalAmt); /* Get the formatted Principal Amount */ printf("Enter Percentage Rate of Interest:n"); scanf("%f", &PercRateofInt); /* Get the formatted Percentage rate of Interest*/ printf("Enter the Duration in years:n"); scanf("%f", &Time);/* Get the formatted Time period in years */ RateofInt = PercRateofInt/100; /* Convert Percentage to float equivalent for Rate of Interest*/ IntAmt = PrincipalAmt*RateofInt*Time; /* Compute Interest Amount using P*R*T formula */ TotalAmt = PrincipalAmt+IntAmt; /* Compute Total Amount using P+I formula */ printf("Interest Amt is:n%fn",IntAmt); /* Prints the computed Interest */ printf("Total Amt is:n%f",TotalAmt); /* Prints the computed Total amount */ getch(); /* Pause so that results are visible */ }
  • 11. 11 Question 4 Accept any number from the user. Display whether the number is divisible by 100 or not. Answer 4 Code: main (void) { int Num, Remainder; /* define variable to store Number and Remainder */ clrscr(); /* Clear screen*/ printf ("Enter a Number:n"); scanf ("%d",&Num); /* Get the formatted Number */ Remainder = Num % 100; /* Divide the Number by 100 and get the remainder */ if ( Remainder == 0 ) /* check if the Remainder is equal to zero or no, so that the divisibility can be printed */ printf("Entered Number is divisible by 100n"); else printf("Entered Number is not divisible by 100n"); getch(); /* Pause so that results are visible */ } Evaluator‟s Comments if any:
  • 12. 12 Question 5 Write a program to swap the values of two numbers. Do this using call by reference method of function. Answer 5 Code: #include < stdio.h > void swap(int * firstnum, int * secondnum); /* function prototype for call by ref*/ main(void) { int firstnum, secondnum; /* define variables to store entered numbers */ clrscr(); /* Clear screen*/ printf("Please enter first Number:"); scanf("%d", & firstnum); /* Get the formatted firstnumber */ printf("Please enter second number:"); scanf("%d", & secondnum); /* Get the formatted secondnumber */ printf("nBefore Swamp, firstnum is: %dt, secondnum is: %dn", firstnum, secondnum); /* Pass the numbers to be swapped, pass by reference */ swap( & firstnum, & secondnum); printf("After swap, firstnum is: %dt, secondnum is: %dn", firstnum, secondnum); getch(); /* Pause so that results are visible */ }
  • 13. 13 void swap(int * first, int * second) { int temp; /* define variables for temporary storage */ temp = * second; /* Assign the value of second to temp variable */ * second = * first; /* Assign the value of the first to second variable */ * first = temp; /* Assign the value of the temporary variable to first variable */ } Question 6 Accept a month in digit from the user. Display the month in words. If number is not between 1 and 12 display message “Invalid Month”. (Use „switch‟) Answer 6 Code: #include <stdio.h> main() { int month; /* define variable to store entered month */ clrscr(); /* Clear screen*/ printf("Enter the Month in range 1-12:n"); scanf("%d",&month); /* Get the formatted month */ if (month < 1) /* Signal error is entered integer is not within range 1 to 12 */ printf("Invalid Month, please enter in valid range"); if (month > 12) printf("Invalid Month, please enter in valid range"); printf("n"); switch (month) /* Use the switch case to control what needs to be printed */ { case 1: printf("You entered January"); break;
  • 14. 14 case 2: printf("You entered February"); break; case 3: printf("You entered March"); break; case 4: printf("You entered April"); break; case 5: printf("You entered May"); break; case 6: printf("You entered June"); break; case 7: printf("You entered July"); break; case 8: printf("You entered August"); break; case 9: printf("You entered September"); break; case 10: printf("You entered October"); break; case 11: printf("You entered November"); break; case 12: printf(" You entered December"); break; default: break;
  • 15. 15 } getch(); /* Pause so that results are visible */ } Question 7 Accept any two numbers from the user. Using pointers swap the values two numbers without using third variable Answer 7 #include<stdio.h> void swap(int *firstnum, int *secondnum);/* function prototype for call by ref*/ main() { int firstnum, secondnum; /* define variables to store entered numbers */ clrscr();/* Clear screen*/ printf("Please enter first Number:"); scanf("%d",&firstnum); /* Get the formatted firstnumber */ printf("Please enter second number:"); scanf("%d",&secondnum); /* Get the formatted secondnumber */ printf("nBefore Swamp, firstnum is: %dt, secondnum is: %dn", firstnum,secondnum); swap(&firstnum,&secondnum); /* Pass the numbers to be swapped, pass by reference */ printf("After swap, firstnum is: %dt, secondnum is: %dn",firstnum,secondnum); getch(); /* Pause for results */ } void swap(int *firstnum, int *secondnum)
  • 16. 16 { if( firstnum!=secondnum) { /* Use the ^ operator to swap without temp variable*/ *firstnum ^= *secondnum; *secondnum ^= *firstnum; *firstnum ^= *secondnum; } } Question 8 Create a structure to store the employee number, name, department and basic salary. Create an array of structure to accept and display the values of 10 employees Answer 8 Code: #include <stdio.h> #include <ctype.h> void main() { struct emp /* Structure declaration */ { int empnum; int basicsal; char name[20]; char dept[20]; } ; struct emp My_emps[10]; /* Structure array declaration */ int hcount = 0; /* Count of the number of EMPS */ int i = 0; /* Loop counter */ char test = '0'; /* Test value for ending */
  • 17. 17 clrscr(); for(hcount = 0; hcount < 10 ; hcount++ ) { printf("nDo you want to enter details of a%s employee (Y or N)? ", hcount?"nother " : "" ); scanf(" %c", &test ); if(tolower(test) == 'n') break; printf("nEnter the name of the employee: " ); scanf("%s", My_emps[hcount].name ); /* Read the emp's name */ printf("nEnter employee number: " ); scanf("%d", &My_emps[hcount].empnum ); /* Read the emp's num */ printf("n Enter dept of employee: " ); scanf("%s", My_emps[hcount].dept ); printf("nEnter basic salary: "); scanf("%d",&My_emps[hcount].basicsal ); } /* Now display the employee details */ for (i = 0 ; i < hcount ; i++ ) { printf("nnEmp%d: %st%dt%st%d", i,My_emps[i].name, My_emps[i].empnum, My_emps[i].dept,My_emps[i].basicsal); } getch(); / * Pause for viewing results */ }
  • 18. 18 Question 9 Accept a file name from the user. Display the contents of the file. Also add the entered string to the file. Answer 9 Code: #include <stdio.h> #include <io.h> #include <stdlib.h> int main() { FILE *fp; /* define file pointer variable */ char fname[100]; char s[100]; int t; clrscr();/ Clear screen*/ printf("Enter filename( Eg: Vijay.txtn"); scanf("%s",fname); /* Get the formatted filename */ printf("%s",fname); if((fp = fopen(fname,"a")) == NULL) { printf("cannot open file.n"); exit(1);/* Exit if there is error opening file */ } printf("nEnter a string:"); /* Get the entered string */ fscanf(stdin,"%s",s); fprintf(fp,"%sn",s); /* Append the value to the file */ fclose(fp); if((fp = fopen(fname,"r"))== NULL) { printf("cannot open file.n"); exit(1); /* Exot if error opening file */ }
  • 19. 19 fscanf(fp,"%s",s); /* Display the contents*/ fprintf(stdout," File created in current dir and the updated content: %s",s); getch(); return 0; } Question 10 Accept any number as a command line argument. Write a program to display the number in reverse order. Instructions: Please run this from Command prompt to see correct results. Answer 10 Code: #include <stdio.h> #include <string.h> main (int argc,char *argv[]) { int p=1,c=0,i, j; /* define variable and let p point to arg 1*/ char copy[10]; clrscr(); /* Clear screen*/ printf("Entered Number is: %sn", argv[p]); strcpy(copy,argv[p]); /* Copy the command line argv[1] data to local variable */ printf("copy %sn", copy); for(i=0,j=strlen(copy)-1;i <j;i++,j--) /* reverse the chars from the local variable */ { c =copy[i]; copy[i] = copy[j];
  • 20. 20 copy[j] =c; } printf("copy after rev %sn",copy); /* print out the reversed string */ getch(); /* pause to view results*/ } Question 11 Write a short note on enum Answer 11 enum is the abbreviation for ENUMERATE, and we can use this keyword to declare and initialize a sequence of integer constants. Here's an example: enum colors {RED, YELLOW, GREEN, BLUE}; Here, colors is the name given to the set of constants. Now, if you don't assign a value to a constant, the default value for the first one in the list - RED in our case, has the value of 0. The rest of the undefined constants have a value 1 more than the one before, so in our case, YELLOW is 1, GREEN is 2 and BLUE is 3. But you can assign values if you wanted to: enum colors { RED=1, YELLOW, GREEN=6, BLUE }; Now RED=1, YELLOW=2, GREEN=6 and BLUE=7. The main advantage of enum is that if you don't initialize your constants, each one would have a unique value. The first would be zero and the rest would then count upwards.