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

Intro to C Programming at IUPUI

This document provides an introduction to programming in C including examples of a simple "Hello World" program structure, basic data types, variables, literals, and memory concepts. It also includes a sample problem to calculate mathematical operations on two user-input numbers and the corresponding example C program to solve this problem. The document is authored by Dale Roberts from the Department of Computer and Information Science at IUPUI and is intended to help readers write their first C program.

Uploaded by

midhungbabu88
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views14 pages

Intro to C Programming at IUPUI

This document provides an introduction to programming in C including examples of a simple "Hello World" program structure, basic data types, variables, literals, and memory concepts. It also includes a sample problem to calculate mathematical operations on two user-input numbers and the corresponding example C program to solve this problem. The document is authored by Dale Roberts from the Department of Computer and Information Science at IUPUI and is intended to help readers write their first C program.

Uploaded by

midhungbabu88
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd

Department of Computer and Information Science,

School of Science, IUPUI

A First C Program

Dale Roberts, Lecturer


Computer Science, IUPUI
E-mail: droberts@[Link]

Dale Roberts
Try Your First C Program
#include <stdio.h> /* I/O header file */ comment
header file – contains I/O routines
pre-processor directive
main() main must be present in each C program
Indicates a {
program
one statement
building printf(“Hello world ”); statement terminator
block called printf(“Welcome to CSCI230\n“);
function
printf(“I am John Smith\n”);
}
A C program contains one or more functions
main() is the function name of your main (root) program
{ }: braces (left & right) to construct a block containing the statements of a
function
Every statement must end with a ;
\ is called an escape character
\n is an example of an escape sequence which indicates newline
Other escape sequences are: \t \r \a \\ \”
Exercise: Use any editor to type and then save your first program as main.c
% gcc main.c
% [Link] and observe its result.
Dale Roberts
Identifiers
Variable identifiers
Begin with a letter or underscore: A-Z, a-z, _
The rest of the name can be letters, underscore, or digits
Guarantee that east least the first 8 characters are significant (those
come after the 8th character will be ignored) while most of C compiler
allows 32 significant characters.
Example:
_abc ABC Time time _a1 abcdefgh
abcdefghi (may be the same as abcdefgh)
Case sensitive
Keywords: reserved names (lexical tokens)
auto double if static break else int struct
case entry long switch char extern register
typedef float return union do go sizeof continue

Dale Roberts
Fundamental Data Type
Four Data Types (assume 2’s complement, byte machine)
Data Type Abbreviation Size Range
(byte)
char char 1 -128 ~ 127
unsigned char 1 0 ~ 255
int 2 or 4 -215 ~ 215-1 or -231 ~ 231-1
unsigned int unsigned 2 or 4 0 ~ 65535 or 0 ~ 232-1
int short int short 2 -32768 ~ 32767
unsigned short int unsigned short 2 0 ~ 65535
long int long 4 -231 ~ 231-1
unsigned long int unsigned long 4 0 ~ 232-1
float 4
double 8
Note: 27 = 128, 215 =32768, 231 = 2147483648
Complex and double complex are not available

Dale Roberts
Variable Declarations

type v1,v2,v3, …, vn
Example:
int i;
int j;
float k;
char c;
short int x;
long int y;
unsigned int z;
int a1, a2, a3, a4, a5;

Dale Roberts
Numeric, Char, String Literals
Literal
Numeric literal
fixed-point
octal O32 (= 24D) (covered later)
hexadecimal OxFE or Oxfe (=254D) (covered later)
decimal int 32
long (explicit) 32L or 32l
an ordinary integer literal that is too long to fit in an int is also too
long for long
floating-point
No single precision is used; always use double for literal
Example:
1.23
123.456e-7
0.12E

Dale Roberts
Numeric, Char, String Literals
• Character literal (covered later)
• American Standard Code for Information Interchange (ASCII)
• Printable: single space 32
‘0’ - ‘9’ 48 - 57
‘A’ - ‘Z’ 65 - 90
‘a’ - ‘z’ 97 - 122
• Nonprintable and special meaning chars
‘\n’ new line 10 ‘\t’ tab 9
‘\\’ back slash 9 ‘\’’ single quote 39
‘\0’ null 0 ‘\b’ back space 8
‘\f’ formfeed 12 ’\r’ carriage return 13
‘\”’ double quote 34

‘\ddd’ arbitrary bit pattern using 1-3 octal digits


‘\Xdd’ for Hexadecimal mode
‘\017’ or ‘\17’ Shift-Ins, ^O
‘\04’ or ‘\4’ or ‘\004’ EOT (^D)
‘\033’ or ‘\X1B’ <esc>

Dale Roberts
Numeric, Char, String Literals
String Literal
will be covered in Array section
String is a array of chars but ended by ‘\0’
String literal is allocated in a continuous memory space of
Data Segment, so it can not be rewritten
Example: “ABCD”
A B C D ‘\0’ ...
4 chars but takes 5 byte spaces in memory

Question: “I am a string” takes ? Bytes

Ans: 13+1 = 14 bytes

Dale Roberts
Numeric, Char, String Literals
• Character literals & ASCII codes:
char x;
x=‘a’; /* x = 97*/
Notes:
– ‘a’ and “a” are different; why?
‘a’ is the literal 97
“a” is an array of character literals, { ‘a’, ‘\0’} or {97, 0}
– “a” + “b” +”c” is invalid but ‘a’+’b’+’c’ = ? (hint: ‘a’ = 97 in ASCII)
‘a’ + ‘b’ + ‘c’ = 97 + 98 + 99 = 294 = 256 + 38

in the memory

1 38
– if the code used is not ASCII code, one should check out each
value of character

Dale Roberts
Initialization
If a variable is not initialized, the value of
variable may be either 0 or garbage depending
on the storage class of the variable.
int i=5;
float x=1.23;
char c=‘A’;
int i=1, j,k=5;
char c1 = ‘A’, c2 = 97;
float x=1.23, y=0.1;

Dale Roberts
Memory Concepts
Each variable has a name, address, type, and
value
1) int x;
2) scanf(“%d”, &x);

3) user inputs 10
4) x = 200;
After the execution of (1) x
After the execution of (2) x
After the execution of (3) x 10

After the execution of (4) x 200

Previous value of x was overwritten

Dale Roberts
Sample Problem
Write a program to take two numbers as input data and
print their sum, their difference, their product and their
quotient.
Problem Inputs
float x, y; /* two items */
problem Output
float sum; /* sum of x and y */
float difference; /* difference of x and y */
float product; /* product of x and y */
float quotient; /* quotient of x divided by y */

Dale Roberts
Sample Problem (cont.)
Pseudo Code:
Declare variables of x and y;
Prompt user to input the value of x and y;
Print the sum of x and y;
Print the difference of x and y;
Print the product of x and y;
If y not equal to zero, print the quotient of x divided by y

Dale Roberts
Example Program
#include <stdio.h> function
int main(void) • name
{ • list of argument along with their types
float x,y; • return value and its type
• Body
float sum;
printf(“Enter the value of x:”);
scanf(“%f”, &x);
printf(“\nEnter the value of y:”);
scanf(“%f”, &y);
sum = x + y;
printf(“\nthe sum of x and y is:%f”,sum);
printf(“\nthe sum of x and y is:%f”,x+y);
printf(“\nthe difference of x and y is:%f”,x-y);
printf(“\nthe product of x and y is:%f”,x*y);
if (y != 0)
printf(“\nthe quotient of x divided by y is:%f”,x/y); inequality operator
else
printf(“\nquotient of x divided by y does not exist!\n”);
return(0);
}

Dale Roberts

Common questions

Powered by AI

Escape characters in C, defined by the backslash '\', allow for special formatting within strings that cannot be expressed in regular alpha-numeric characters. Commonly used escape sequences include \n for newline, \t for a horizontal tab, \' for a single quote, and \" for a double quote. These sequences enable better control of text within outputs, such as inserting new lines or aligning text in a table format. Understanding escape characters is crucial for controlling how data is displayed, especially in user interfaces and error messages .

Errors in writing a C program involving arithmetic operations can arise from incorrect input reading, not handling division by zero, or type mismatches. For example, failing to check if the divisor is zero before division can cause a runtime error. Input handling errors may occur if user inputs are not validated, leading to unexpected behavior. Type mismatches usually arise if incompatible types are operated together without proper casting. Thorough error checking and validation ensure reliable operation and adherence to expected outcomes, such as correctly handling division and overflow scenarios .

Identifiers in C must begin with a letter (A-Z or a-z) or an underscore (_), and the remaining characters can be a combination of letters, digits, or underscores. The C standard guarantees that at least the first 8 characters are significant, although most compilers accept 32 significant characters. Identifiers are case-sensitive, meaning that 'Variable' and 'variable' would be considered different. Adhering to these rules ensures that programs are free of syntax errors and that they behave as expected, as it aids in avoiding naming conflicts and ambiguity in code interpretation .

In C, floating-point literals by default have double precision, which uses 8 bytes of storage, offering a higher level of precision than single precision, which uses 4 bytes. Single precision is generally sufficient for applications where memory is a constraint and precision up to approximately seven decimal places is adequate. Double precision should be used where more significant precision and a broader range of values are needed, such as in scientific calculations. Selecting between them depends on the application requirements for precision and performance .

C provides several fundamental data types, such as char, int, float, and double, each designed to hold different kinds of data. The char data type occupies 1 byte with a range from -128 to 127 or can be unsigned for a range from 0 to 255. Integers (int) typically occupy 2 or 4 bytes, with ranges from -2^15 to 2^15-1 or -2^31 to 2^31-1, depending on implementation. Floats are used for single-precision floating-point numbers and are 4 bytes, while doubles provide double precision, occupying 8 bytes. Long variants of integers, like long int, cater to larger number ranges .

A basic C program includes syntactic elements such as preprocessor directives, the main function, braces, and statements ending with a semicolon. Preprocessor directives, like #include <stdio.h>, tell the compiler to include the I/O header file necessary for input-output operations. The main function, denoted by main(), is the program's entry point where execution begins. Braces { } delineate blocks of code, while the semicolon ; acts as a statement terminator to indicate the end of a statement. These elements are critical as they dictate the structure and flow of the program .

In C, if variables are not explicitly initialized, they may contain 'garbage' values or default to zero, depending on their storage class. This undetermined behavior can lead to runtime errors or unpredictable program outcomes. For instance, automatic variables (local variables without static storage class) typically hold garbage values if left uninitialized. Explicitly initializing variables ensures that they start with a known state, reducing the likelihood of errors and increasing code reliability and maintainability .

To compile a C program using GCC, you first write your code in a text editor and save it with a .c extension. For example, the program could be saved as main.c. Then, in the terminal, execute '% gcc main.c' command to compile the program. If successful, it produces an executable file named a.out by default. You can run this executable using the command '% a.out'. Potential issues may include syntax errors in the code that prevent successful compilation or missing libraries if preprocessor directives are incorrect. These are identified by reading the error messages provided by the compiler .

String literals in C are arrays of characters terminated by a null character '\0'. They are stored in a continuous memory space in the data segment and cannot be altered during execution. If attempted, it may result in undefined behavior or program crashes. This immutable memory allocation ensures efficiency and safety in program operations. Additionally, any careless handling of strings, such as overwriting or failing to include the null terminator, leads to errors and potential security vulnerabilities. Attention to how they are stored and accessed is crucial to maintain program stability .

In C, each variable has a memory address, type, and value, which are critical for program execution. The address refers to the memory location where the variable is stored, enabling the program to retrieve or modify its value. The type defines the kind of data the variable can hold, such as int or float, impacting the operations that can be performed on it and its memory allocation. Value is the data held by the variable at any given time. Together, these factors influence how data is manipulated in memory and ensure the correct execution of operations and efficient memory use .

You might also like