0% found this document useful (0 votes)
6 views21 pages

Micro c Programming

The document outlines the various data types in C programming, including basic, derived, enumeration, and user-defined types, along with their sizes and ranges. It also explains function declarations, definitions, and calling, as well as provides examples of common programming tasks such as string manipulation, matrix operations, and user-defined structures. Additionally, it discusses the differences between structures and unions, the definition of variables and constants, and the concept of algorithms.

Uploaded by

kalaskarbalaji2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views21 pages

Micro c Programming

The document outlines the various data types in C programming, including basic, derived, enumeration, and user-defined types, along with their sizes and ranges. It also explains function declarations, definitions, and calling, as well as provides examples of common programming tasks such as string manipulation, matrix operations, and user-defined structures. Additionally, it discusses the differences between structures and unions, the definition of variables and constants, and the concept of algorithms.

Uploaded by

kalaskarbalaji2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Types of Data Types in C

C provides four primary categories of data types:

1. Basic Data Types

These are the fundamental data types used to store simple values like integers, characters, and
floating-point numbers.

Data Type Size (bytes) Range

int 2 or 4 -32,768 to 32,767 (2 bytes) or larger

char 1 -128 to 127 (signed) / 0 to 255 (unsigned)

float 4 3.4E-38 to 3.4E+38

double 8 1.7E-308 to 1.7E+308

2. Derived Data Types

These are built from basic data types.

Data Type Description

array Collection of elements of the same type.

pointer Stores the memory address of another variable.

function A block of code that performs a specific task.

3. Enumeration Data Type

The enum type is used to assign symbolic names to integral constants, making the program
more readable.
Example: c

Copy code

enum Color { RED, GREEN, BLUE };

Here, RED, GREEN, and BLUE are constants with values 0, 1, and 2, respectively.

4. User-Defined Data Types

These allow the programmer to define their own data types.

Data Type Description

struct Groups variables of different types into a single unit.

union Similar to struct, but members share the same memory.

typedef Creates an alias for an existing type.

Modifiers for Data Types

Modifiers are used to alter the size or range of data types.

Modifier Effect

signed Allows both positive and negative values.

unsigned Allows only positive values.

short Reduces size to 2 bytes (if applicable).

long Increases size to 8 bytes (if applicable).


The functions strlen, strcat, and strcpy are common string manipulation functions in C. Here's a
demonstration program for these functions:

Copy code

#include <stdio.h>

#include <string.h>

int main() {

char str1[50], str2[50], str3[50];

int length;

// Input for the first string

printf("Enter the first string: ");

fgets(str1, sizeof(str1), stdin);

str1[strcspn(str1, "\n")] = '\0'; // Remove newline character

// Input for the second string

printf("Enter the second string: ");

fgets(str2, sizeof(str2), stdin);

str2[strcspn(str2, "\n")] = '\0'; // Remove newline character

// Demonstrate strlen
length = strlen(str1);

printf("Length of the first string ('%s') is: %d\n", str1, length);

// Demonstrate strcat

strcat(str1, str2);

printf("Concatenated string: '%s'\n", str1);

// Demonstrate strcpy

strcpy(str3, str2);

printf("Copied second string into str3: '%s'\n", str3);

return 0;

Explanation:

1strlen: Calculates the length of a string.

Example: strlen(str1) returns the number of characters in str1 (excluding the null terminator).

2strcat: Concatenates two strings.

Example: strcat(str1, str2) appends str2 to the end of str1.

3strcpy: Copies the content of one string into another.

Example: strcpy(str3, str2) copies str2 into str3.


1. Function Declaration

A function declaration specifies the function's name, return type (if applicable), and its
parameters (if any). It acts as a blueprint or prototype and informs the compiler/interpreter about
the function's existence before its actual definition.

Syntax (Example in C++/C) :return_type function_name(parameter_list)

;Example: int add(int a, int b);

Characteristics:1Does not contain the function's body.2Often used in languages like C or C++ for
forward declarations or when separating function implementation into different files.

2. Function Definition

A function definition provides the actual implementation or body of the function. It includes the
logic/code that will execute when the function is called.

Syntax:

return_type function_name(parameter_list) {

// Function body. }

Example: int add(int a, int b) { return a + b; }

Characteristics:1Contains the function's name, parameters, and code logic.2Must match the
declaration if the function is declared elsewhere.

3. Function Calling

Function calling is the process of invoking a function to execute the code defined in its body.
During the call, arguments can be passed to the function's parameters.

Syntax:function_name(argument_list);
Example: int result = add(5, 10); // Calls the 'add' function with arguments 5 and 10

Characteristics:1Transfers control to the function's code.2Returns control to the caller after the
function execution is completed (along with any return value, if applicable).

Example (Combining Declaration, Definition, and Calling in C++):

#include <iostream>. using namespace std

// Function declaration .int add(int a, int b);

int main() { . int x = 5, y = 10.. // Function calling int result = add(x, y) .cout << "The sum is: " <<
result << endl; .return 0; }. .// Function definition

int add(int a, int b) { . return a + b; .}


Q-Write a program to read a number and display its reversing using a while
loop.

#include <stdio.h>

int main() {
int num, rev = 0, rem;
printf("Enter a number: ");
scanf("%d", &num);

while (num) {
rem = num % 10;
rev = rev * 10 + rem;
num /= 10;
}

printf("Reversed: %d", rev);


return 0;
}

Q- Write a program to accept 2 numbers and compute the quotient and


remainder, then display them.

#include <stdio.h>

int main() {
int num1, num2, q, r;
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);

q = num1 / num2;
r = num1 % num2;

printf("Quotient: %d, Remainder: %d", q, r);


return 0;
}
Q-Write a program to copy the first 16 characters from the string "CPC is very
easy programming language" into the string "ABC".

#include <stdio.h>
#include <string.h>

int main() {
char source[] = "CPC is very easy programming language";
char dest[17];

strncpy(dest, source, 16);


dest[16] = '\0';

printf("Copied string: %s", dest);


return 0;
}

Q- Define an array with a program.

#include <stdio.h>

int main() {
int myArray[5] = {1, 2, 3, 4, 5};

for (int i = 0; i < 5; ++i)


printf("%d ", myArray[i]);

return 0;
}

Q- What is a variable, defined with an example?


#include <stdio.h>

int main() {
int myVar = 10;
printf("Value of myVar: %d", myVar);
return 0;
}
Q- Define union and structure in C programming with suitable examples.

#include <stdio.h>

union MyUnion {
int x;
float y;
char z;
};

struct MyStruct {
int a;
float b;
char c;
};

int main() {
union MyUnion myUnion;
struct MyStruct myStruct;
return 0;
}

Q-What is an array? Right syntax of 1-dimensional array.

#include <stdio.h>

int main() {
int myArray[3] = {1, 2, 3};

for (int i = 0; i < 3; ++i)


printf("%d ", myArray[i]);

return 0;
}

Q- Write a program to read and print a matrix of 3x3 and 2x2.


#include <stdio.h>

int main() {
int matrix3x3[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int matrix2x2[2][2] = {{10, 11}, {12, 13}};
return 0;
}
Q- Write a program to create a simple calculator to perform addition, subtraction,
division, and multiplication operations.

#include <stdio.h>

int main() {
float num1, num2, result;
char op;

// Code to read nums, op, and calc...

printf("Result: %f", result);


return 0;
}

Q- Write a program to print the area of a square using a function.

#include <stdio.h>

float calculateSquareArea(float side) {


return side * side;
}

int main() {
float side = 5.0; // Replace with user input if needed
printf("Area of square: %f", calculateSquareArea(side));

return 0;
}

Q-Write a program to find the maximum number from 10 numbers entered by the user.

#include <stdio.h>

int main() {
int numbers[10];
int maxNumber;

// Code to read numbers and find the maximum...


printf("Maximum number: %d", maxNumber);
return 0;
}
Q- Write a program to print the factorial of a given number using a while loop.

#include <stdio.h>

int calculateFactorial(int num) {


int factorial = 1;
while (num > 0) {
factorial *= num;
num--;
}
return factorial;
}

int main() {
int number = 5; // Replace with user input if needed
printf("Factorial: %d", calculateFactorial(number));

return 0;
}

Q- Write a program to perform and print the addition and subtraction of two
matrices.

#include <stdio.h>

void addSubMatrices(int A[3][3], int B[3][3], int rows, int cols) {


int resultSum[rows][cols], resultDiff[rows][cols];

int main() {
int matrixA[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int matrixB[3][3] = {{10, 11, 12}, {13, 14, 15}, {16, 17, 18}};

addSubMatrices(matrixA, matrixB, 3, 3);

return 0;
}
Q- Write the program to perform the following operations on a string, with
and without using library functions.

#include <stdio.h>
#include <string.h>

int main() {
char originalString[] = "Hello, World!";
char copiedString[17]; // One extra for the null terminator

int length = strlen(originalString);

strncpy(copiedString, originalString, 16);


copiedString[16] = '\0';

char reversedString[17];
int i;
for (i = 0; i < length; ++i) {
reversedString[i] = originalString[length - i - 1];
}
reversedString[i] = '\0';

// Using library functions


char libCopy[17], libRev[17];
strcpy(libCopy, originalString);
strcpy(libRev, originalString);
strrev(libRev);

return 0;
}
Q-Create a structure of a student with fields such as student name, roll number, and
marks of two subjects as members. Calculate the average of the two subjects, read the
details of N students from the user, and then display the data in a formatted way.

#include <stdio.h>
struct Student {
char name[50];
int rollNumber;
float marks[2];
};
int main() {
int numStudents = 3; // Replace with user input if needed
struct Student students[numStudents];
for (int i = 0; i < numStudents; i++) {
printf("Enter Roll Number, Name, Subject 1 Marks, and Subject 2 Marks for
Student %d: ", i+1);
scanf("%d %s %f %f", &students[i].rollNumber, students[i].name,
&students[i].marks[0], &students[i].marks[1]);
}
printf("\nStudent Details:\n");
for (int i = 0; i < numStudents; i++) {
printf("Student %d\nRoll Number: %d\nName: %s\nSubject 1 Marks: %.2f\nSubject
2 Marks: %.2f\n\n",
i+1, students[i].rollNumber, students[i].name, students[i].marks[0],
students[i].marks[1]);
}
return 0;
}
Q-Define structure with a suitable example.

#include <stdio.h>

struct Point {
int x;
int y;
};

int main() {
struct Point p; // Code to use the structure...
return 0;
}
Q- Write a program in C to create a structure named "books" consisting of title, author,
subject, and book ID as its members. Read the details of five books from the user and
then display the data entered by the user on the screen.

#include <stdio.h>

struct Book {
char title[100];
char author[50];
char subject[50];
int bookID;
};

int main() {
int numBooks = 5; // Replace with user input if needed
struct Book books[numBooks]; // Display data entered by the user...
return 0;
}

Q-: What is the difference between structure and union?


#include <stdio.h>

union U {
int x;
float y;
char z;
};
struct S {
int a;
float b;
char c;
};
int main() {
union U u;
struct S s;
return 0;
}
Q-What is the difference between structure and union?:
1.Memory Allocation:
--Structure: Each part (like name, age, salary) has its own space in memory.
--Union: All parts share the same space in memory, but only the largest part is used.
2.Usage of Memory:
--Structure: Used when you want to keep different pieces of information together.
--Union: Used when you want to save memory and only need one piece of
information at a time.
3.Accessing Members:
--Structure: You can look at or change each part independently.
--Union: You can only look at or change one part at a time.
4.Initialization:
--Structure: You can set each part to a value separately.
--Union: You set the first part to a value, and others might be affected.

Q-Define flowchart :
Definition : A flowchart is a visual representation of the steps or actions in a process
or algorithm.
--Oval: Represents the start or end of a process.
--Rectangle: Depicts an operation or task within the program.
--Diamond: Indicates a decision point where the program takes different paths.
--Parallelogram : Represents input or output actions.
--Arrows: Show the flow and direction of the program, connecting different symbols.

Q-Define variable. Define constant. Give the difference between variable and constant
--Variable: A variable is a labeled container in the computer's memory that can hold
different values during program execution.
--Constant : A constant is a fixed value that remains unchanged throughout the
program.
--Difference The key distinction lies in variability – variables can change their values,
allowing for dynamic data storage, while constants provide stability to specific
program elements.

Q-Define function
--Definition: In C, a function is a modular block of code designed to perform a specific
task.
--Modularity: Functions promote code modularity, allowing for the reuse of code in
different parts of a program.
--Code Organization :They contribute to code organization by breaking down
complex tasks into manageable and reusable units.
Q-Explain function signature :
--Definition: A function signature includes the function's name, return type, and
parameter types.
--Function Name : It identifies the function and distinguishes it from others.
--Return Type : Specifies the type of value the function returns.
--Parameter Types : Outline the data types of the values the function expects as input,
providing information about the function's interface.

Q-Define string. Define array. Define structure:


--String : A string is a sequence of characters stored as an array in C.
--Array : An array is a collection of elements of the same type stored in contiguous
memory locations, facilitating efficient data storage.
--Structure : A structure is a user-defined data type that organizes different types under
a single name, enhancing code organization and readability.

Q-What is an algorithm? :
--Definition : An algorithm is a systematic, step-by-step approach to solving a problem
or accomplishing a task.
--Problem-Solving Blueprint : It serves as a blueprint for writing code, ensuring a logical
and efficient solution to a given computational problem.

Q-Define variable:
--Definition : A variable is a labeled container in the computer's memory that can hold
different values during program execution.
--Dynamic Data Storage: Variables allow for dynamic data storage, enabling flexibility in
the manipulation of values.
--Key Role: They play a crucial role in programming by facilitating the storage and
manipulation of data within a program.

Q-Write a note on program process development :


--Design: Program process development begins with the design phase, involving
planning and structuring the program to outline the overall approach.
--Coding: The coding phase follows, where the actual program code is written based on
the design, translating the plan into a working system.
--Testing and Debugging: The final stages include testing and debugging, ensuring the
program works correctly by identifying and fixing any errors or issues.

Q-Explain While Loop and Do-While Loop


--While Loop: A while loop efficiently executes a block of code repeatedly while the
specified condition remains true, providing a flexible means of iterative execution.
--Do-While Loop: In contrast, a do-while loop ensures at least one execution of the code
block before checking the condition, making it suitable for scenarios where initial
execution is necessary regardless of the condition.
Q-Write a sentence for array, switch, and function:
--Array: Arrays in C provide a systematic way to store and access multiple elements of
the same data type within a single variable, facilitating organized data management.
--Switch: The switch statement in C enables selective execution of code blocks based
on specific conditions, offering a structured approach to decision-making within
programs.
--Function: Functions in C encapsulate logic into reusable units, promoting code
modularity and enhancing program structure by dividing tasks into manageable and
reusable components.

Q- Syntax of array, switch, function.


--Array:

Syntax:

data_type array_name[array_size];

--Switch:

Syntax:

switch (expression) {
case constant_value_1:

break;
case constant_value_2:

break;

default:

--Function:

Syntax:

return_type function_name(parameters) {
return value; // optional, depending on the return type
}
Q-Define errors and explain various types of errors in C programming (5 marks):
Errors in C programming refer to mistakes that can occur during the development
or execution of a program.
1.Syntax Errors- These errors involve grammatical mistakes that prevent the
compiler from translating the code into machine language.
2.Semantic Errors- While not breaking syntax, semantic errors lead to incorrect
program behavior due to logical issues.
3.Runtime Errors- Occurring during program execution, runtime errors are often
caused by actions like dividing by zero or accessing data beyond defined limits.
Q-Write a short note on tokens in language (5 marks):

--In C, tokens are the basic building blocks of your code. They are similar to words
in a sentence, each having a specific meaning and purpose. The compiler reads
your C code and breaks it down into these essential elements to understand the
structure and functionality of your program.
--Types of tokens:
--Keywords: These are reserved words with predefined meanings in C, like int, if,
for, etc. You cannot use them as variable names.
--Identifiers: These are user-defined names for variables, functions, structures, etc.
They must follow naming rules (letters, numbers, underscore).
--Constants: Fixed values like numbers, characters, or strings. They cannot be
changed during program execution.
--Operators: Symbols that perform operations like addition (+), subtraction (-),
multiplication (*), etc.
--Special symbols: Punctuation marks like semi-colons (;) and commas (,) that
separate statements and elements.
--Strings: Sequences of characters enclosed in double quotes ("").Explain three
types of operators, along with their precedence and associativity (6 marks):

Arithmetic Operators (2 marks): Perform mathematical operations like addition and


multiplication with high precedence.
Relational Operators (2 marks): Compare values and have medium precedence in
determining conditions.
Logical Operators (2 marks): Evaluate logical expressions with low precedence,
aiding in decision-making within the program.
Differentiate between while loop and do-while loop (5 marks):
In programming, an error refers to any issue or problem in the code that prevents it from
executing as expected. Errors can occur during different stages of program development and
execution, such as writing the code, compiling, or running it. These errors need to be identified
and resolved for the program to work correctly.

In C programming, errors are primarily categorized based on when and how they occur. Let’s dive
into the details of different types of errors:

Types of Errors1. Syntax Errors

Definition: Occur when the programmer violates the grammatical rules of the C programming
language.When: Detected during compilation.Examples:

Missing semicolon:

c Copy codei nt x = 10 // Missing semicolonI ncorrect variable declaration:

C. Copy code

int 2x; // Variable name cannot start with a digitR

esolution: These errors are identified by the compiler, which provides error messages to help the
programmer locate and fix

2. Semantic Errors Definition: Occur when the statements are syntactically correct but do not
make logical sense or do not produce the expected result.When: May not be directly identified by
the compiler.

Examples:Misusing a logical operator:c

Copy code

if (x = 10) // '=' used instead of '=='

Division by zero (undefined behavior):

c. Copy code
int result = a / 0; Resolution: Requires debugging and understanding the logic of the program.

3. Logical Errors

Definition: Errors in the logic or algorithm of the program that lead to incorrect results despite the
program running without crashing.

When: Detected during runtime or testing, not compilation.

Examples: Incorrect loop condition: c

Copy code

for (i = 0; i <= 10; i--) // Infinite loop

Miscalculating a formula: c. Copy code

area = 2 * pi * r; // Should be area = pi * r * r

Resolution: Requires proper testing and debugging to ensure correct output.

4. Runtime Errors Definition: Errors that occur while the program is running, often due to invalid
operations or resource limitations.When: Detected only during program execution.

Examples: Accessing an invalid memory location:

c Copy code

int arr[5];

arr[10] = 100; // Out-of-bounds access

Null pointer dereferencing:

c Copy code
int *ptr = NULL;

*ptr = 5; // Causes a runtime error

Resolution: Needs careful handling of edge cases and robust programming.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy