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

Introduction to C Programming Basics

Uploaded by

riderallison489
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 views26 pages

Introduction to C Programming Basics

Uploaded by

riderallison489
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

Introduction to C

Sagor Chandro Bakchy


Assistant Professor

1
C: History
Developed in the 1970s – in conjunction with development
of UNIX(Uniplexed Information Computing System)
operating system
When writing an OS kernel, efficiency is crucial
This requires low-level access to the underlying hardware:
e.g. programmer can leverage knowledge of how data is laid out in
memory, to enable faster data access
UNIX originally written in low-level assembly language – but
there were problems:
No structured programming (e.g. encapsulating routines as “functions”,
“methods”, etc.) – code hard to maintain
Code worked only for particular hardware – not portable

2
C: Characteristics
C takes a middle path between low-level assembly language
Direct access to memory layout through pointer manipulation
Concise syntax, small set of keywords
A high-level programming language like Java:
Block structure
Some encapsulation of code, via functions
Type checking (pretty weak)

3
C: Dangers
C is not object oriented!
Can’t “hide” data as “private” or “protected” fields
You can follow standards to write C code that looks
object-oriented, but you have to be disciplined – will the other
people working on your code also be disciplined?
C has portability issues
Low-level “tricks” may make your C code run well on one
platform – but the tricks might not work elsewhere
The compiler and runtime system will rarely stop your C
program from doing stupid/bad things
Compile-time type checking is weak
No run-time checks for array bounds errors, etc. like in Java

4
Separate compilation
Advantage: Quicker compilation
When modifying a program, a programmer typically edits only
a few source code files at a time.
With separate compilation, only the files that have been edited
since the last compilation need to be recompiled when
re-building the program.
For very large programs, this can save a lot of time.

5
Compiler Vs Interpreter
Builds the code at a time
Builds code line by line

6
7
Header Files Inclusion: The first and foremost component is the inclusion of the
Header files in a C program. A header file is a file with extension .h which contains
C function declarations and macro definitions to be shared between several source
files.
Main Method Declaration: The next part of a C program is to declare the main()
function.
Variable Declaration: The next part of any C program is the variable declaration. It
refers to the variables that are to be used in the function. Please note that in the C
program, no variable can be used without being declared. Also in a C program, the
variables are to be declared before any operation in the function.
Body: The body of a function in the C program, refers to the operations that are
performed in the functions. It can be anything like manipulations, searching,
sorting, printing, etc.
Return Statement: The last part of any C program is the return statement. The
return statement refers to the returning of the values from a function. This return
statement and return value depend upon the return type of the function. For
example, if the return type is void, then there will be no return statement. In any
other case, there will be a return statement and the return value will be of the type
of the specified return type.

8
Escape Sequences:

\a alert (bell) character \\ backslash


\b backspace \? question mark
\f formfeed \’ single quote
\n newline \” double quote
\r carriage return
\t horizontal tab
\v vertical tab

9
\f Formfeed: Sometimes abbreviated as FF, form feed is a button or command on the
printer that allows the advancement of a printer page. This feature was frequently used on
dot matrix printers since nearly all of them used continuous feed paper rather than single
sheets. The form feed button advanced paper to the start of the next printing page, in the
case of a paper jam, or when loading continuous feed paper.

\v Vertical Tab: Moves the cursor to the next line and same position
Ab\vcd\vef
Ab
cd
ef

10
Tokens in C
We can define the token as the smallest individual element
in C. For `example, we cannot create a sentence without
using words; similarly, we cannot create a program in C
without using tokens in C.

11
Keywords
The following list shows the reserved words in C.
These reserved words may not be used as constants or variables or any other identifier names.

auto else long switch


break enum register typedef
case extern return union
char float short unsigned
const for signed void
continue goto sizeof volatile
default if static while
do int struct _Packed
double

12
Identifiers / Rules of variable naming
A C identifier is a name used to identify a variable, function,
or any other user-defined item.
An identifier starts with a letter A to Z, a to z, or an underscore '_' \
followed by zero or more letters, underscores, and digits (0 to 9).
C does not allow punctuation characters such as @, $, and %
within identifiers.
Can’t Start with digit
C is a case-sensitive programming language. Thus, Manpower
and manpower are two different identifiers in C.
Here are some examples of acceptable identifiers −
Mohd, zara, abc, move_name
a_123, myname50 _temp, j, a23b9, retVal

13
Comments
Comments are like helping text in your C
program and they are ignored by the compiler.
They start with
/* and terminate with the characters */
as shown below −

/* my first program in C */
You cannot have comments within comments
and they do not occur within a string or
character literals.
14
Type Storage size Value range

char 1 byte -128 to 127 or 0 to 255


unsigned char 1 byte 0 to 255
signed char 1 byte -128 to 127
int 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647
unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295
short 2 bytes -32,768 to 32,767
unsigned short 2 bytes 0 to 65,535
long 8 bytes or (4bytes -9223372036854775808 to 9223372036854775807
for 32 bit OS)
unsigned long 8 bytes 0 to 18446744073709551615

15
Type Storage size Value range Precision
float 4 byte 1.2E-38 to 6 decimal places
3.4E+38
double 8 byte 2.3E-308 to 15 decimal places
1.7E+308
long double 10 byte 3.4E-4932 to 19 decimal places
1.1E+4932

16
char c;
scanf("%c",&c);
printf("%c",c);
printf("\n%d\n",sizeof(char));

int x;
scanf("%d",&x);
printf("%d",x);
printf("\n%d\n",sizeof(int));

17
If you accidentally input char instead of int value:

scanf() has an internal buffer, and will only read from the stream if that buffer is
empty. scanf tries to find an integer there. If an integer is found, it will report it
successfully read one item (by returning 1) and puts the read value into the
supplied pointer location. However, if an integer is not found, it will return 0 for
"zero items successfully read", and it will not consume anything from the buffer.

18
if (scanf("%d", &x) == 1)
{
printf(“%d”, x);
}

19
float f;
scanf("%f", &f);
printf("%.2f\n", f);
printf("%d\n", sizeof(float));

20
double d;
scanf("%lf",&d);
printf("%lf\n",d);
printf("%d\n",sizeof(double));

21
int x;
char c;
//scanf("%d%c",&x,&c);
scanf("%d",&x);
scanf("%c",&c);
printf(" %d\n",x);
printf(" %c\n",c);

22
Reminder Operator

int a = -3, b = 8;
printf("%d", a % b);

Output is: -3
Reminder is a least positive integer that should be
subtracted from a to make it divisible by b
(mathematically, a = qb + r then 0 ≤ r < |b|).

**So the answer is mathematically incorrect

23
Reminder Operator
C/C++ does like this:
i) (a%b + b)%b
ii) a % n = a – ( n * trunc( a/n ) ).
For example,
8 % -3 = 8 – ( -3 * trunc(8/-3) )
= 8 – ( -3 * trunc(-2.666..) )
= 8 – ( -3 * -2 ) { rounded towards zero }
=8–6
=2

**But it produces different result in different


language.
24
Reminder Operator
C/C++ does like this:
i) (a%b + b)%b
ii) a % n = a – ( n * trunc( a/n ) ).
For example,
8 % -3 = 8 – ( -3 * trunc(8/-3) )
= 8 – ( -3 * trunc(-2.666..) )
= 8 – ( -3 * -2 ) { rounded towards zero }
=8–6
=2

**But it produces different result in different


language.
25
int number=0;
printf("enter a number:");
scanf("%d",&number);
switch(number){
case 10:
printf("number is equals to 10");
break;
case 50:
printf("number is equal to 50");
break;
case 100:
printf("number is equal to 100");
break;
default:
printf("number is not equal to 10, 50 or 100");
}
26

Common questions

Powered by AI

C differs from Java in terms of memory management and security primarily due to its ability for direct access to memory through pointer manipulation, something Java does not allow. This characteristic of C offers flexibility and potential performance advantages but also introduces significant security risks, such as the likelihood of buffer overflows and the lack of runtime checks for issues like array bounds errors. Conversely, Java provides a more secure environment by enforcing strict boundary checks and disallowing direct memory access, thereby preventing many common security vulnerabilities. Additionally, Java has automatic garbage collection, simplifying memory management, which C lacks, requiring manual memory management .

The development of UNIX played a crucial role in the creation of the C programming language. C was developed in the 1970s in conjunction with the development of the UNIX operating system. Writing an OS kernel requires efficiency and low-level access to hardware, which C facilitated. Initially, UNIX was written in assembly language, but this lacked structured programming, making it hard to maintain and not portable. C was created to overcome these issues by providing a structured programming environment that allowed for efficient hardware level interactions while also offering some portability across platforms .

C treats identifiers case-sensitively, meaning that identifiers such as "Manpower" and "manpower" are considered distinct and different. This is unlike some other programming languages that may not distinguish based on case, treating identifiers with differing cases as equivalent. As a result of C's case sensitivity, developers must consistently adhere to the same casing conventions throughout their code to avoid errors arising from unintended identifier mismatches .

C's compile-time checks are weaker compared to those in some other languages like Java, which includes limited type checks and lacks runtime checks for errors like buffer overflows and array bounds violations. This means more rigor is required during the development phase to prevent errors that might only manifest at runtime, such as segmentation faults from illegal memory access. The absence of rigorous runtime checks allows for faster execution of C programs but places the onus on developers to ensure safety and correctness through disciplined programming practices. These differences necessitate a balance between performance and safety when coding in C .

In C, identifiers must begin with a letter (A-Z or a-z) or an underscore ('_'), followed by zero or more letters, underscores, or digits (0-9). Punctuation characters such as @, $, and % are not allowed within identifiers, and they cannot start with a digit. These rules are significant because they ensure a uniform method for naming that prevents syntactical errors and confusion in code interpretation. Correctly following these patterns helps maintain clarity and avoids conflicts with C’s reserved keywords .

Writing code in C poses several potential dangers compared to higher-level languages like Java. C is not object-oriented, meaning it does not allow encapsulation of data as 'private' or 'protected' fields, leading to potentially unsafe access patterns. C's weak compile-time type checking and lack of runtime checks for array bounds errors can result in critical vulnerabilities and undefined behavior. It also permits low-level memory manipulation through pointers, which can easily lead to memory leaks or corruption if not handled carefully. These factors make C more prone to security issues and less robust compared to languages like Java, which offer stricter controls and safer abstractions .

In C, the modulo operation retrieves the remainder of integer division. It computes this as a = qb + r where 0 ≤ r < |b|. In C, the calculation is done by (a % b + b) % b, ensuring a non-negative remainder result that is platform and sign-consistent, unlike some other languages that may handle signs differently, leading to different results. This highlights the influence of language design choices on arithmetic operations, which can impact program logic depending on language-specific implementation details .

C provides low-level operations primarily through pointer manipulation, allowing direct memory access, which can optimize performance for specific hardware operations. This level of control enables close interaction with hardware and system resources, which is why C is often used in systems programming. However, low-level operations compromise safety, as errors with pointers can lead to memory corruption, leaks, and security vulnerabilities. Moreover, this hardware-specific optimization reduces portability, as code using these operations might not function correctly across different platforms. Developers must carefully manage these trade-offs when programming in C .

Separate compilation in C programs involves compiling only the modified source files rather than the entire program. This method is facilitated by dividing a program into multiple files and using header files for shared declarations. The main advantage of separate compilation is its efficiency, especially for large programs, as it significantly reduces compilation time. Instead of recompiling every file, only those that have been edited need recompilation, allowing for quicker iterations during development. This strategy also aids in encapsulating code modules and clearer organization, enhancing maintainability .

C handles escape sequences by interpreting specific character combinations as representing special characters. For example, '\n' represents a newline and '\t' a horizontal tab. Escape sequences allow for incorporating non-standard characters within strings in a clear and manageable format, essential for correctly formatting output and input handling in C programming. These sequences inform the compiler to perform specific text manipulations, aiding in creating cleaner and more readable code .

You might also like