The document describes a modular C programming directory structure that contains subdirectories for different C programming concepts like arrays, functions, strings, structures, etc. Each subdirectory contains C source code files that demonstrate examples for the given concept. The document also provides brief introductions and explanations for basic C programming topics like variables, data types, operators, decision making statements, loops, functions and pointers.
C lecture 3 control statements slideshareGagan Deep
Control Statement in C, Looping in C, Conditional and Unconditional Statements, For Loop, While Loop, Do-While Loop, C Programming, Examples : Visit us at www.rozyph.com
C lecture 3 control statements slideshareGagan Deep
Control Statement in C, Looping in C, Conditional and Unconditional Statements, For Loop, While Loop, Do-While Loop, C Programming, Examples : Visit us at www.rozyph.com
Operators and expressions in c languagetanmaymodi4
what is operator in c language
uses of operator in c language
syatax of operator in c language
program of operator in c language
what is expressions in c language
use of expressions in c language
syantax of expressions in c language
statement in python conditional statement.For more presentation please contact us on raginijain0208@gmail.com.
You get new presentation every Sunday at 10 AM.
Learn more about Python by click on this given below link
Python Introduction- https://www.slideshare.net/RaginiJain21/final-presentation-on-python
Basic concept of Python -https://www.slideshare.net/RaginiJain21/python-second-ppt
Python Datatypes - https://www.slideshare.net/RaginiJain21/data-types-in-python-248466302
Python Library & Module - https://www.slideshare.net/RaginiJain21/python-libraries-and-modules
Basic Python Programs- https://www.slideshare.net/RaginiJain21/basic-python-programs
Python Media Libarary - https://www.slideshare.net/RaginiJain21/python-media-library
In this module of python programming you will be learning about control statements. A control statement is a statement that determines whether other statements will be executed. An if statement decides whether to execute another statement, or decides which of two statements to execute. A loop decides how many times to execute another statement.
Detailing about basics of C language and its control structure for learning C Language for beginners. It covers looping statement , control statement etc.
Iterative control structures, looping, types of loops, loop workingNeeru Mittal
Introduction to looping, for loop. while loop, do loop jump statements, entry controlled vs exit controlled loop, algorithm and flowchart of loops, factorial of a number
C Programming Language is the most popular computer language and most used programming language till now. It is very simple and elegant language. This lecture series will give you basic concepts of structured programming language with C.
basic of desicion control statement in pythonnitamhaske
it consists if-else, nested if, if-elif-else, for loop, while loop with flowchart and examples. also continue ,pass and break statement.
and else with for and while loop
Types of Statements in Python Programming LanguageExplore Skilled
The slide describes the types of flow control statements in Python including conditional statement , loop statement , control statement such as break and continue .
Operators and expressions in c languagetanmaymodi4
what is operator in c language
uses of operator in c language
syatax of operator in c language
program of operator in c language
what is expressions in c language
use of expressions in c language
syantax of expressions in c language
statement in python conditional statement.For more presentation please contact us on raginijain0208@gmail.com.
You get new presentation every Sunday at 10 AM.
Learn more about Python by click on this given below link
Python Introduction- https://www.slideshare.net/RaginiJain21/final-presentation-on-python
Basic concept of Python -https://www.slideshare.net/RaginiJain21/python-second-ppt
Python Datatypes - https://www.slideshare.net/RaginiJain21/data-types-in-python-248466302
Python Library & Module - https://www.slideshare.net/RaginiJain21/python-libraries-and-modules
Basic Python Programs- https://www.slideshare.net/RaginiJain21/basic-python-programs
Python Media Libarary - https://www.slideshare.net/RaginiJain21/python-media-library
In this module of python programming you will be learning about control statements. A control statement is a statement that determines whether other statements will be executed. An if statement decides whether to execute another statement, or decides which of two statements to execute. A loop decides how many times to execute another statement.
Detailing about basics of C language and its control structure for learning C Language for beginners. It covers looping statement , control statement etc.
Iterative control structures, looping, types of loops, loop workingNeeru Mittal
Introduction to looping, for loop. while loop, do loop jump statements, entry controlled vs exit controlled loop, algorithm and flowchart of loops, factorial of a number
C Programming Language is the most popular computer language and most used programming language till now. It is very simple and elegant language. This lecture series will give you basic concepts of structured programming language with C.
basic of desicion control statement in pythonnitamhaske
it consists if-else, nested if, if-elif-else, for loop, while loop with flowchart and examples. also continue ,pass and break statement.
and else with for and while loop
Types of Statements in Python Programming LanguageExplore Skilled
The slide describes the types of flow control statements in Python including conditional statement , loop statement , control statement such as break and continue .
Introduction to control structure in C Programming Language include decision making (if statement, if..else statement, if...else if...else statement, nested if...else statement, switch...case statement), Loop(for loop, while loop, do while loop, nested loop) and using keyword(break, continue and goto)
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteGoogle
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
👉👉 Click Here To Get More Info 👇👇
https://sumonreview.com/ai-pilot-review/
AI Pilot Review: Key Features
✅Deploy AI expert bots in Any Niche With Just A Click
✅With one keyword, generate complete funnels, websites, landing pages, and more.
✅More than 85 AI features are included in the AI pilot.
✅No setup or configuration; use your voice (like Siri) to do whatever you want.
✅You Can Use AI Pilot To Create your version of AI Pilot And Charge People For It…
✅ZERO Manual Work With AI Pilot. Never write, Design, Or Code Again.
✅ZERO Limits On Features Or Usages
✅Use Our AI-powered Traffic To Get Hundreds Of Customers
✅No Complicated Setup: Get Up And Running In 2 Minutes
✅99.99% Up-Time Guaranteed
✅30 Days Money-Back Guarantee
✅ZERO Upfront Cost
See My Other Reviews Article:
(1) TubeTrivia AI Review: https://sumonreview.com/tubetrivia-ai-review
(2) SocioWave Review: https://sumonreview.com/sociowave-review
(3) AI Partner & Profit Review: https://sumonreview.com/ai-partner-profit-review
(4) AI Ebook Suite Review: https://sumonreview.com/ai-ebook-suite-review
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...Juraj Vysvader
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I didn't get rich from it but it did have 63K downloads (powered possible tens of thousands of websites).
Into the Box Keynote Day 2: Unveiling amazing updates and announcements for modern CFML developers! Get ready for exciting releases and updates on Ortus tools and products. Stay tuned for cutting-edge innovations designed to boost your productivity.
Cyaniclab : Software Development Agency Portfolio.pdfCyanic lab
CyanicLab, an offshore custom software development company based in Sweden,India, Finland, is your go-to partner for startup development and innovative web design solutions. Our expert team specializes in crafting cutting-edge software tailored to meet the unique needs of startups and established enterprises alike. From conceptualization to execution, we offer comprehensive services including web and mobile app development, UI/UX design, and ongoing software maintenance. Ready to elevate your business? Contact CyanicLab today and let us propel your vision to success with our top-notch IT solutions.
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar
The European Union Agency for Law Enforcement Cooperation (Europol) has suffered an alleged data breach after a notorious threat actor claimed to have exfiltrated data from its systems. Infamous data leaker IntelBroker posted on the even more infamous BreachForums hacking forum, saying that Europol suffered a data breach this month.
The alleged breach affected Europol agencies CCSE, EC3, Europol Platform for Experts, Law Enforcement Forum, and SIRIUS. Infiltration of these entities can disrupt ongoing investigations and compromise sensitive intelligence shared among international law enforcement agencies.
However, this is neither the first nor the last activity of IntekBroker. We have compiled for you what happened in the last few days. To track such hacker activities on dark web sources like hacker forums, private Telegram channels, and other hidden platforms where cyber threats often originate, you can check SOCRadar’s Dark Web News.
Stay Informed on Threat Actors’ Activity on the Dark Web with SOCRadar!
Developing Distributed High-performance Computing Capabilities of an Open Sci...Globus
COVID-19 had an unprecedented impact on scientific collaboration. The pandemic and its broad response from the scientific community has forged new relationships among public health practitioners, mathematical modelers, and scientific computing specialists, while revealing critical gaps in exploiting advanced computing systems to support urgent decision making. Informed by our team’s work in applying high-performance computing in support of public health decision makers during the COVID-19 pandemic, we present how Globus technologies are enabling the development of an open science platform for robust epidemic analysis, with the goal of collaborative, secure, distributed, on-demand, and fast time-to-solution analyses to support public health.
In software engineering, the right architecture is essential for robust, scalable platforms. Wix has undergone a pivotal shift from event sourcing to a CRUD-based model for its microservices. This talk will chart the course of this pivotal journey.
Event sourcing, which records state changes as immutable events, provided robust auditing and "time travel" debugging for Wix Stores' microservices. Despite its benefits, the complexity it introduced in state management slowed development. Wix responded by adopting a simpler, unified CRUD model. This talk will explore the challenges of event sourcing and the advantages of Wix's new "CRUD on steroids" approach, which streamlines API integration and domain event management while preserving data integrity and system resilience.
Participants will gain valuable insights into Wix's strategies for ensuring atomicity in database updates and event production, as well as caching, materialization, and performance optimization techniques within a distributed system.
Join us to discover how Wix has mastered the art of balancing simplicity and extensibility, and learn how the re-adoption of the modest CRUD has turbocharged their development velocity, resilience, and scalability in a high-growth environment.
Enhancing Research Orchestration Capabilities at ORNL.pdfGlobus
Cross-facility research orchestration comes with ever-changing constraints regarding the availability and suitability of various compute and data resources. In short, a flexible data and processing fabric is needed to enable the dynamic redirection of data and compute tasks throughout the lifecycle of an experiment. In this talk, we illustrate how we easily leveraged Globus services to instrument the ACE research testbed at the Oak Ridge Leadership Computing Facility with flexible data and task orchestration capabilities.
Large Language Models and the End of ProgrammingMatt Welsh
Talk by Matt Welsh at Craft Conference 2024 on the impact that Large Language Models will have on the future of software development. In this talk, I discuss the ways in which LLMs will impact the software industry, from replacing human software developers with AI, to replacing conventional software with models that perform reasoning, computation, and problem-solving.
First Steps with Globus Compute Multi-User EndpointsGlobus
In this presentation we will share our experiences around getting started with the Globus Compute multi-user endpoint. Working with the Pharmacology group at the University of Auckland, we have previously written an application using Globus Compute that can offload computationally expensive steps in the researcher's workflows, which they wish to manage from their familiar Windows environments, onto the NeSI (New Zealand eScience Infrastructure) cluster. Some of the challenges we have encountered were that each researcher had to set up and manage their own single-user globus compute endpoint and that the workloads had varying resource requirements (CPUs, memory and wall time) between different runs. We hope that the multi-user endpoint will help to address these challenges and share an update on our progress here.
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamtakuyayamamoto1800
In this slide, we show the simulation example and the way to compile this solver.
In this solver, the Helmholtz equation can be solved by helmholtzFoam. Also, the Helmholtz equation with uniformly dispersed bubbles can be simulated by helmholtzBubbleFoam.
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTier1 app
Even though at surface level ‘java.lang.OutOfMemoryError’ appears as one single error; underlyingly there are 9 types of OutOfMemoryError. Each type of OutOfMemoryError has different causes, diagnosis approaches and solutions. This session equips you with the knowledge, tools, and techniques needed to troubleshoot and conquer OutOfMemoryError in all its forms, ensuring smoother, more efficient Java applications.
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxrickgrimesss22
Discover the essential features to incorporate in your Winzo clone app to boost business growth, enhance user engagement, and drive revenue. Learn how to create a compelling gaming experience that stands out in the competitive market.
Quarkus Hidden and Forbidden ExtensionsMax Andersen
Quarkus has a vast extension ecosystem and is known for its subsonic and subatomic feature set. Some of these features are not as well known, and some extensions are less talked about, but that does not make them less interesting - quite the opposite.
Come join this talk to see some tips and tricks for using Quarkus and some of the lesser known features, extensions and development techniques.
A Comprehensive Look at Generative AI in Retail App Testing.pdfkalichargn70th171
Traditional software testing methods are being challenged in retail, where customer expectations and technological advancements continually shape the landscape. Enter generative AI—a transformative subset of artificial intelligence technologies poised to revolutionize software testing.
How Recreation Management Software Can Streamline Your Operations.pptxwottaspaceseo
Recreation management software streamlines operations by automating key tasks such as scheduling, registration, and payment processing, reducing manual workload and errors. It provides centralized management of facilities, classes, and events, ensuring efficient resource allocation and facility usage. The software offers user-friendly online portals for easy access to bookings and program information, enhancing customer experience. Real-time reporting and data analytics deliver insights into attendance and preferences, aiding in strategic decision-making. Additionally, effective communication tools keep participants and staff informed with timely updates. Overall, recreation management software enhances efficiency, improves service delivery, and boosts customer satisfaction.
3. ● C was developed by Dennis Ritchie in 1972 at
AT&T Bell Laboratories, USA.
● C is basic of all languages, to make
fundamentals stronger it's advised to learn C
first.
● C is base language for Embedded system.
● C is best language for performance ( speed of
execution ), produces less code size hence good
for embedded devices which have processor
power & memory size restrictions.
What is C ? lynxbee.comlynxbee.com
4. Very Basic C program
$ vim minimum-c-program.c
main() {
}
Above is the very basic framework for Any C program.
- main, () and {}
$ gcc -o minimum-c-program minimum-c-program.c
$ ./minimum-c-program
#include <stdio.h>
main() {
printf("Hello Worldn");
}
- What happens when you didn’t written
#include
lynxbee.comlynxbee.com
5. Constants - Entity that do not change
Integer constants -
1, 423, +700, -345 etc
Float Constants -
426.9, -367.3 etc
Character constants -
‘A’ , ‘n’, ‘Z’, ‘3’ etc
Maximum length => 1 Char in
single inverted
Constants, Variables, Keywords
Variables - entity that may change
Names given to memory location which
can change.
int age; float salary; char yes_no;
lynxbee.comlynxbee.com
6. ● Words whose meaning is already decided for the compilers.
● Keywords can’t be used as variable names.
auto double int struct break else long switch
case enum register typedef char extern return union
const float short unsigned continu
e
for signed void
default goto sizeof volatile do if static while
Keywords lynxbee.comlynxbee.com
7. #include <stdio.h>
void main() {
printf(“hello world”);
}
● Header
● main
● Body
● #include is - preprocessor.
● Printf is declared in header stdio.h and defined in a library.
● Always ends with ;
First Program lynxbee.comlynxbee.com
8. #include <stdio.h>
int main(void) {
/* Printing Hello World */
printf(“hello world”);
return 0;
}
● Comments should be included in /* */
● Returns integer
● Void
Second Program lynxbee.comlynxbee.com
9. #include <stdio.h>
int main(void) {
int p, n; /* declaration */
float r, si;
p = 1000; /* definition */
n = 3;
r = 8.5;
si = p*n*r/100;
printf (“Simple Interest is : %f n”, si);
}
● Printf => printf(“<format string>” , <list of variables>);
● %f - float, %d - Int, %c - Char.
● n -> New line
Third Program lynxbee.comlynxbee.com
10. ● Create a file using editor
vim simple_interest.c
● Compile using gcc ( GNU C Compiler for Linux )
gcc -o simple_interest simple_interest.c
● ./simple_interest
Compilation and Execution lynxbee.comlynxbee.com
11. #include <stdio.h>
int main(void) {
int p,n;
float r,si;
printf(“Enter values of p, n, r”);
scanf(“%d, %d, %f”, &p, &n, &r);
si = p*n*r/100;
printf(“Simple Interest = %fn”, si);
return 0;
}
& - Address of operator, which is actually a memory location
Receiving Inputs from User using scanf lynxbee.com
12. Priority Operators Description
First * / % Multiplication, division, Modular
Second + - Addition, Subtraction
Third = Assignment
Operators lynxbee.comlynxbee.com
13. #include <stdio.h>
int main (void){
/* Associativity of operators :1) Left to Right 2) Right to Left */
/* Multiplication & Division has "Left to Right Associativity" */
/* for Division: / , left side is 3 & right side is 2*5, indicating left side is unambiguous */
/* for Multiplication: * , left side is 3/2 & right side is 5, indicating right side is unambiguous */
/* Since both * & / has same priority & "Left to Right" Associativity, In below example */
/* Division will get executed first and them multiplication */
/* Hence result will be 5 */
int a = 3/2*5;
printf("a=%dn", a);
/*Above Statement will print result as 5 since 3/2 is equals to 1 due to integer division*/
return 0;
}
Associativity of Operators lynxbee.comlynxbee.com
14. If Statement
Conditions - x == y, x != y, x < y, x > y, x <= y, x >= y
Simple Program
#include <stdio.h>
int main (void) {
int x = 9;
if ( x < 10 )
printf(“ you have assigned x less than 10n”);
return 0;
}
Decision Making Statements - If, If-else, Switch lynxbee.com
15. #include <stdio.h>
int main() {
Int x = 11;
If (x<10)
printf(“you have set x less than 10n”);
else
printf(“you have set x greater than 10n”);
return 0;
}
Nested If else statements are possible
If - else Statement lynxbee.comlynxbee.com
16. AND ( && ), OR ( || ) & NOT (!)
Different than bitwise operators
Simple Example
Logical Operators lynxbee.comlynxbee.com
17. If the first condition is satisfied, other conditions are not checked.
Reduces the multiple indentation required by “if-else” statements.
Simple Example -
Else - If Statement lynxbee.com
18. - This operator reverses the result of the expression it operates on.
- Final result will be either true or false i.e. 1 or 0
- !(y<10) => this means “not y less than 10”. In other words, if y is less than 10, the expression will be
false, since (y<10) is true.
The Conditional Operator
? : also called as ternary operators.
Expression 1 ? expression 2 : expression 3
The Not ! Operator lynxbee.comlynxbee.com
19. - While
- For
- Do-while
While Loop
#include <stdio.h>
int main() {
int count = 1;
while ( count < =5 ) {
printf ( “count is %d”, count);
count = count + 1;
}
printf(“now count is more than 5, exiting programn”);
return 0;
}
Loops lynxbee.comlynxbee.com
20. I++, i-- and ++i, --i
i+=1, i-=1
Example :
#include <stdio.h>
int main() {
int count = 1;
while ( count < =5 ) {
printf ( “count is %d”, count);
count++; // this is same as count+=1 and count = count + 1;
}
printf(“now count is more than 5, exiting programn”);
return 0;
}
Increment and Decrement Operators lynxbee.comlynxbee.com
21. - Most used
- All steps at one statement
for ( initialize; test; increment ) {
}
Example :
#include <stdio.h>
int main() {
int count;
for ( count = 1; count < =5; count++ ) {
Printf ( “count is %d”, count);
}
printf(“now count is more than 5, exiting programn”);
return 0;
}
lynxbee.com
The For Loop lynxbee.comlynxbee.com
22. - Used when you are not sure how many times the loop needs to be executed.
- Loop is executed atleast once.
Example -
Int main () {
Char condition;
Int num=0;
Do {
printf(“You are inside for the %d timen”, num++);
printf(“do you want to remain in loop ( y/n ) : ”);
scanf(“%c”, &condition);
}while (condition == ‘y’)
printf(“you entered: %c, hence out of loopn”, condition)
return 0;
}
Do - while loop lynxbee.comlynxbee.com
23. break - is used to move out of loop immediately upon meeting certain condition
continue - is used to move back to loop by skipping steps beyond this.
Example :
Int main() {
Int i, j=5;
for(i=1;i<=10;i++) {
If ( i == j)
break;
printf(“i=%dn”,i);
}
Return 0;
}
Continue Example
Int main() {
Int i, j=5;
for(i=1;i<=10;i++) {
If ( i == j)
continue;
printf(“i=%dn”,i);
}
Return 0;
}
Break & Continue lynxbee.com
24. - Used when we need to make a choice between number of things.
- Integer expression can be constants or something which evaluates to integer.
- “Case” will be followed by “int” or “char” constant.
Switch ( integer expression )
{
Case constant 1 :
“Do this”
Case constant 2:
“Do this”
Default :
“If no match”
}
#include <stdio.h>
int main() {
int i = 2
Switch ( i ) {
case 1 :
printf(“1”);
case 2:
printf(“2”);
Case 3:
printf(“3”);
Default :
“in default”
}
return 0;
}
#include <stdio.h>
Int main() {
Int i = 2
Switch ( i ) {
case 1 :
printf(“1”);
break;
case 2:
printf(“2”);
break;
Case 3:
printf(“3”);
break;
Default :
“in default”
}
Return 0;
}
Switch Case lynxbee.com
25. Int main() {
Int i; j=2;
For (i=0; i<5; i++) {
printf(“i is %dn”, i);
If (i==j)
goto at_end;
}
printf(“normal completion of loopn”);
return 0;
at_end: printf(“reached directly at end due to i==jn”);
Return 0;
}
Int main() {
Int i; j=6;
For (i=0; i<5; i++) {
printf(“i is %dn”, i);
If (i==j)
goto at_end;
}
printf(“normal completion of
loopn”);
return 0;
at_end: printf(“reached directly at end
due to i==jn”);
return 0;
}
Goto Keyword : better avoid lynxbee.com
26. - Function is a block of statement which performs some task.
- Functions need three things, declaration, call and definition
#include <stdio.h>
/* declaration */
Void function_name();
int main () {
/* function call */
function_name();
printf(“inside the main n”);
return 0;
}
/* function definition */
Void function_name() {
printf(“inside the function n”);
}
- Start main
- Control passes to
function while main is
suspended
- Function is executed
- Control returns to main
- Main resumes execution
- Main is completed
Functions lynxbee.com
27. - Library Function ex. main, printf
- User defined functions ex. myfunc()
Benefits of Functions -
- Avoid rewriting of same code
- Modular functions make program design easier for development and debugging
Passing Values to Functions - adds communication between calling & called function
Void sum(int);
Int main(void) {
int i = 10;
add(i);
return 0;
}
void add (int j) {
printf(“sum = %d”, j+5);
}
Type, order and number of arguments from
calling and called function should be same.
Types of Functions lynxbee.com
28. int sum(int);
int main(){
Int i=10, ret;
ret = sum(i);
printf(“sum = %dn”,sum);
Return 0;
}
int sum(int j) {
Int add;
Add = j+5;
Return add;
}
- Only “return” with no value will return
garbage.
- “return” returns only one value.
Return Type & Variable from a Function lynxbee.com
29. - The scope of a variable is local to the function in which it is defined.
- Local variables defined inside a function are created in “stack” memory.
Calling Convention - C has “right to left” calling convention
#include <stdio.h>
Int main(){
Int i = 1;
printf(“%d, %d, %d n”, i, ++i, i++);
Return 0;
}
This program will return as 3, 3, 1
Scope in Functions lynxbee.com
30. 1. Call by Value
- We pass “values” of variables to the called function.
#include <stdio.h>
Int main(void) {
Int j=10;
function(j);
Return 0;
}
Void function (int k) {
printf(“%d ”, k);
}
Call by reference - will need understanding of
pointers
Function calls - 1. Call by Value 2. Call by reference lynxbee.com
31. Int i = 5;
This does 3 things,
- Reserve memory
- Give a Name
- Store Value in it
Int main() {
Int i = 5;
printf(“address = %u n”, &i);
printf(“value = %d n”, i);
Return 0;
}
& - is called “address of” operator
* - is called “value at address” operator
Int main () {
Int i = 5;
Printf (“address = %u n”, &i);
Printf (“value = %d n”, i);
Printf (“ value = %d n”, *(&i) );
Return 0;
}
Pointers lynxbee.com
32. Address can also be collected in a variable.
Definition => j = &i ; declaration => int *j ;
This means, J is a variable which is used to store address of integer or value at the address contained in j
is integer.
Int main() {
Int i=5, *j;
j = &i;
printf(“Address of i = %u”, &i);
printf(“value of i = %d”, i);
printf(“value inside j =%d”, *j);
return 0;
}
Pointers lynxbee.com
33. Example : swapping of two integers
Int main() {
Int i=10, j=20;
swap(i,j);
printf(“i= %d, j=%d”, i, j);
Return 0;
}
Void swap(int x, int y) {
Int t;
t = x;
X = y;
Y = t;
printf(“x = %d, y=%d”, x,y);
}
We can’t use return since it can return only one value.
Int main() {
Int i=10, j=20;
swap( &i, &j );
printf(“i= %d, j=%d”, i, j);
Return 0;
}
Void swap( int *x, int *y) {
Int t;
T = *x;
*x = *y;
*y = t
}
Above program will actually exchange i &
j
● Useful to return more than one
variables to main.
Back to Function Call by Reference lynxbee.com
34. Recursion : when statement in a function calls the same function
Example : Calculate Factorial 4! = 4*3*2*1
Int factorial (int);
Int main() {
Int num, ret;
printf(“Enter the number = ”);
scanf(“%d”, &num);
Ret = factorial ( num);
printf(“calculated factorial = %d”, ret );
Return 0;
}
Int factorial(int x) {
Int f = 1, i;
For (i=x; i>=1; i--)
F = f*i;
Return f;
}
Using recursion
Int factorial( int x ) {
Int f;
If (x == 1)
Return 1;
Else
F = x * factorial (x-1);
Return f;
}
Recursion lynxbee.com
35. - char, int, float
- Signed & unsigned
- long & short
char Signed, unsigned
int Signed, unsigned Long, short
float Float, double, long double
Data Types lynxbee.com
36. #include <stdio.h>
int main(void) {
char c;
signed char c1;
unsigned char c2;
int a;
short int a1;
long int a2;
signed int a3;
unsigned int a4;
short signed int a5;
short unsigned int a6;
long signed int a7;
long unsigned int a8;
float b;
double b1;
long double b2;
printf ("sizeof (char) = %d n", sizeof(c));
printf ("sizeof (signed char) = %d n", sizeof(c1));
printf ("sizeof (unsigned char) = %d n", sizeof(c2));
printf ("sizeof (int) = %d n", sizeof(a));
printf ("sizeof (short int) = %d n", sizeof(a1));
printf ("sizeof (long int) = %d n", sizeof(a2));
printf ("sizeof (signed int) = %d n", sizeof(a3));
printf ("sizeof (unsigned int) = %d n", sizeof(a4));
printf ("sizeof (short signed int) = %d n", sizeof(a5));
printf ("sizeof (short unsigned int) = %d n", sizeof(a6));
printf ("sizeof (long signed int) = %d n", sizeof(a7));
printf ("sizeof (long unsigned int) = %d n", sizeof(a8));
printf ("sizeof (float) = %d n", sizeof(b));
printf ("sizeof (double) = %d n", sizeof(b1));
printf ("sizeof (long double) = %d n", sizeof(b2));
return 0;
}
$ ./a.out
sizeof (char) = 1
sizeof (signed char) = 1
sizeof (unsigned char) = 1
sizeof (int) = 4
sizeof (short int) = 2
sizeof (long int) = 4
sizeof (signed int) = 4
sizeof (unsigned int) = 4
sizeof (short signed int) = 2
sizeof (short unsigned int) = 2
sizeof (long signed int) = 4
sizeof (long unsigned int) = 4
sizeof (float) = 4
sizeof (double) = 8
sizeof (long double) = 12
Use of sizeof lynxbee.com
37. - Where the variable would be stored
- Decides the initial value of variable when it's not specifically initialised.
- Scope of variable
- Life of variable
Storage Default Value Scope Life
Automatic Memory Garbage Local to block Till last statement in
block
Register CPU
Registers
Garbage Local to Block Till last statement in
block
Static Memory Zero Local to Block Persists between
different function calls
External Memory Zero Global Till Program is running
Storage Classes in C lynxbee.com
38. Automatic Storage Class
#include <stdio.h>
void main() {
auto int i, j;
printf(“i = %d, j=%d n”, i, j);
}
Register Storage Class
#include <stdio.h>
void main() {
register int i;
For (i=1; i<10; i++ )
printf(“i = %d n”, i);
}
Static Storage Class
#include <stdio.h>
Void counter();
Int main() {
counter();
counter();
counter();
}
void counter() {
Static int i=1;
Printf (“counter is = %dn”, i);
I++;
}
Storage Classes in C ... lynxbee.com
39. #include <stdio.h>
Int i = 2;
Int main() {
I = i + 3;
Printf ( “ i is set to %d n”, i);
function();
Printf (“ i is set to %d n”, i);
}
function() {
I = i + 10;
}
Another Example :
#include <stdio.h>
Int x = 5;
Void main () {
Extern int y;
Printf (“x = %d, y = %d n”, x, y);
}
Int y = 7;
Extern Storage Class lynxbee.com
40. - C program before compilation gets through C preprocessor
- Preprocessing is first step of building executable.
- Preprocessor begins with #
Macro Expansion :
#include <stdio.h>
#define MACRO_NAME 23
int main(void) {
int a = 10;
a = a + MACRO_NAME;
printf("Adding a macro to a : %dn", a);
return 0;
}
- During compilation preprocessor replaced
every occurrence of “MACRO_NAME”
with assigned value i.e. 23 in our case.
- You need to make only one change.
- Compiler generates faster and more
compact code for constants than
variables.
-
C Preprocessors lynxbee.com
41. #include <stdio.h>
#define SQUARE(x) (x*x)
int main(void) {
printf("SQUARE(9) is : %dn", SQUARE(9));
printf("SQUARE(25) is : %dn", SQUARE(25));
return 0;
}
Macro with Arguments lynxbee.com
42. - Preprocessor replaces the Macro with the actual code / initialisation of macro during compilation
which generates more code size but fast in run time.
- Function call, passes the control from one the other, adding delay in execution hence slowing run
time execution but reduces the size of program.
Macros to Include File.
Two ways -
- #include “filename.h”
- #include <filename.h>
Difference only in search path.
Why Macros, Not functions ? lynxbee.com
43. #include <stdio.h>
// below program will not print anything if ENABLE is not defined.
// way to enable this code is, just define like below,
#define ENABLE
// to disable this, just comment above line
int main(void) {
#ifdef ENABLE
printf("This code is enabled upon condition as aboven");
#endif
return 0;
}
“Ifdef” can be used to
make programs
portable.
Conditional Compilation using Macros lynxbee.com
44. #include <stdio.h>
// below program will print second message because ENABLE
// is not defined.
int main(void) {
#ifdef ENABLE
printf("This code is enabled upon condition as aboven");
#else
printf("When disabled, you want to execute this coden");
#endif
return 0;
}
#ifdef - #else - #endif lynxbee.com
45. #ifndef - Important during header file definitions to avoid multiple inclusion.
Header - ifndef_endif.h
#ifndef __IFNDEF_ENDIF_H
#define __IFNDEF_ENDIF_H
#define MYNAME "somename"
#endif
Program - ifndef_endif.c
#include <stdio.h>
#include "ifndef_endif.h"
int main(void) {
printf("%sn", MYNAME);
return 0;
}
Header - ifndef_endif.h
#define MYNAME "somename"
Program - ifndef_endif.c
#include <stdio.h>
#include "ifndef_endif.h"
#include "ifndef_endif.h"
int main(void) {
printf("%sn", MYNAME);
return 0;
}
#ifndef lynxbee.com
46. #include <stdio.h>
#define MACRO 4
int main(void) {
int a = 5;
// Note: here you can't compare a macro with variable
// hence #if MACRO == a
// this statement will not work.
#if MACRO == 5
printf("Macro value matches with an");
#else
printf("Macro value doesnt match with an");
#endif
return 0;
}
Example of using #if - #else #endif lynxbee.com
47. #include <stdio.h>
#define MACRO 3
int main(void) {
#if MACRO == 5
printf("Macro is currently set to 5n");
#elif MACRO == 4
printf("Macro is currently set to 4n");
#else
printf("Macro is something elsen");
#endif
return 0;
}
Example of #if - #elif - #endif lynxbee.com
48. #include <stdio.h>
#define TEST
int main(void) {
printf("starting program execution inside mainn");
#ifdef TEST
printf("TEST is defined, so do something heren");
#endif
#undef TEST
#ifdef TEST
printf("TEST is defined, so do something heren");
#else
printf("TEST is undefined, did you do that ?n");
#endif
return 0;
}
#undef Example lynxbee.com
49. Ordinary Variables are
capable of holding only one
value at a time.
#include <stdio.h>
Int main (void) {
Int x;
X = 4;
X = 10;
Printf (“x=%dn”, x);
Return 0;
}
Age = {21, 18, 27, 31, 45};
- In array counting of elements begins at 0
How to declare above array ?
Int age[5];
Arrays - set of similar data types lynxbee.com
50. #include <stdio.h>
int main(void) {
int x[2];
x[0] = 4;
x[1] = 10;
printf("x[0] = %dn", x[0]);
printf("x[1] = %dn", x[1]);
return 0;
}
- You can take values from user using scanf
for (i=0; i<2; i++) {
printf(“%d”,&x[i]);
}
- Number inside square bracket is called
array dimension e.g. in x[2] , 2 is array
dimension
- Accessing elements from array
printf("x[0] = %dn", x[0]);
You can use the for loop like below,
for (i=0; i<2; i++) {
printf(“x[%d] = %d n”, i, x[i]);
}
Using Arrays lynxbee.com
51. Int x[2] = {4, 10};
Int x[] = {4, 10};
- Till the array elements are not given specific values, they contains garbage.
- If array is initialized where it is declared, mentioning of array dimension is optional.
- All array elements gets stored in contiguous memory.
- There will be no error message if you are going beyond array size like below,
#include <stdio.h>
Int main() {
Int x[3], i;
For (i=0; i<10; i++) {
X [i] = i;
}
Return 0;
}
Initialisation of Arrays lynxbee.com
52. #include <stdio.h>
int main(void) {
int x [5], i;
printf("Enter elements of array: n");
for (i = 0; i < 10; i++)
scanf("%d", &x[i]);
printf("Printing output of above array :");
for (i = 0; i < 10; i++)
printf("x[%d] = %d n", i, x[i]);
return 0;
}
$ ./a.out
Enter elements of array:
1
3
14
34
23
56
99
2
7
89
Printing output of above array :x[0] = 1
x[1] = 3
x[2] = 14
x[3] = 34
x[4] = 23
x[5] = 56
x[6] = 99
x[7] = 2
x[8] = 7
x[9] = 89
*** stack smashing detected ***: ./a.out terminated
Aborted (core dumped)
Array Boundary Checking lynxbee.com
53. #include <stdio.h>
void function (int y);
int main(void) {
int i, x[2] = {4, 10};
for (i=0; i<2; i++)
function(x[i]);
return 0;
}
void function (int y) {
printf("%dn", y);
}
#include <stdio.h>
void function (int *y);
int main(void) {
int i, x[2] = {4, 10};
for (i=0; i<2; i++)
function(&x[i]);
return 0;
}
void function (int *y) {
printf("%dn", *y);
}
Passing Array elements to function lynxbee.com
54. #include <stdio.h>
int main(void) {
int x[2] = {4, 10};
int *y;
y = &x[0];
printf("x[0]=%d, *y=%dn", x[0], *y);
// now lets increment the pointer
printf("Incrementing pointer as y++n");
y = y + 1; // here you can increment as many till y+(n-1) if "n" is element size
printf("*y=%dn", *y);
// this printed 10, which means incrementing pointer reaches to next element.
printf("Decrementing pointer as y--n");
y--;
printf("*y=%dn", *y);
return 0;
}
Incrementing & Decrementing Pointers lynxbee.com
55. #include <stdio.h>
void function (int *, int);
int main(void) {
int x[2] = {4, 10};
function(&x[0], 2);
// above call also can be made as,
// function(x, 2);
return 0;
}
void function (int *y, int j) {
int i;
for (i = 0; i < j; i++)
printf("%dn", *(y+i));
}
Passing entire array to function lynxbee.com
56. #include <stdio.h>
int main(void) {
int x[2] = {4, 10};
int *p[] = {x, x+1};
printf("%d, %dn", **p, **(p+1));
return 0;
}
Array of pointer lynxbee.com
57. - String is a one dimensional array of characters terminated by null (‘0’)
Char message = {‘H’, ‘E’, ‘L’, ‘L’, ‘O’, ‘0’};
Each character occupies one byte and also the last character ‘0’ hence total size of string will be
always one more than actual characters in string.
- Null character ‘0’ is way to decide when the string ends.
#include <stdio.h>
int main(void) {
char message[] = {'H', 'E', 'L', 'L', 'O', '0'};
printf("string is : %sn", message);
// Another way of initialising same string is as below,
// char message[] = "HELLO";
// note here, we dont need to mention "null" character '0'
// and this is most standard way to initialize strings
return 0;
}
Initialisation of Strings
Strings ... lynxbee.com
58. #include <stdio.h>
//#include <string.h>
int main(void) {
char message[] = "How will you calculated the characters in this sentence ?";
int length = 0;
// so this is where null character helps us.
while (message[length] != '0') {
length++;
}
printf("Number of characters in message = %dn", length);
// can we get this length instead of using while, yes, using strlen library function
// but for that, we have to include string.h header
// printf("Number of characters in message = %dn", strlen(message));
return 0;
}
Another use of null character lynxbee.com
59. #include <stdio.h>
// if you want to run the program to test user input
// using scanf, just enable below line.
// #define TAKE_STRING_USING_SCANF
int main(void) {
char name[20];
#ifdef TAKE_STRING_USING_SCANF
printf("Enter Your Name: n");
scanf("%s", name);
printf("You entered your name as: %snn", name);
printf("Did you want to enter your surname along with name? Try
Again...");
scanf("%s", name);
printf("You entered your name & surname is: %snn", name);
printf("Did you observed that, we couldn't print your surname whichn");
printf("was separated by space i.e. ' ' n");
printf("So, thats the limitation of accepting string using scanf n");
printf("You can't accept the "Multi Word" string.nn");
printf("Ok, got it.. So, whats the solution ?n");
printf("Thats where, fgets & puts will help us..n");
#else
printf("Now, Try to enter your name & surnamen");
if(fgets (name, 20, stdin) != NULL) {
/* writing content to stdout */
puts("You entered your name and surname asn");
puts(name);
}
#endif
return 0;
}
Get string from Users ... lynxbee.com
60. #include <stdio.h>
int main(void) {
char *message = "hello";
char *p;
p = message;
printf("string in p : %sn", p);
// Now we will try to update the string in p
p = "world";
printf("updated string in p : %sn", p);
// same you can't do with static string which can be defined as
// char message[] = "hello";
// char p[10];
// p = message;
// this will give error;
// or p = "world" is not possible.
// hence we need to use pointers;
return 0;
}
- you can point address of one
string to another pointer
- update the string inside pointer.
Pointers and Strings lynxbee.com
61. #include <stdio.h>
#include <string.h>
int main(void) {
char source[] = "hello";
char destination[50];
int length;
length = strlen(source);
printf("length of source string = %dn", length);
strcpy(destination, source);
printf("destination string after copying source is now: %sn", destination);
strcat(destination, " world!");
printf("destination string after appending another string is now: %sn", destination);
if (!strcmp(source, "test string")) {
printf("source and "hello" string is samen");
} else {
printf("source is certainly not same as "test string"n");
}
return 0;
}
Library functions for string
- Strlen, strcpy, strcat and
strcmp are most widely used
string library functions
- Check string.h for other
supported functions.
lynxbee.com
62. #include <stdio.h>
int main(void) {
char *names[5];
int i;
for (i=0; i<5; i++) {
printf("Enter Name: ");
scanf("%s", names[i]);
}
return 0;
}
This program will end up with run time error,
since we are not initializing the memory
locations of the strings in the array.
Array of Pointer to Strings lynxbee.com
63. int main(void) {
char *names[5];
int i, len;
char single_name[20];
char *p;
for (i=0; i<5; i++) {
printf("Enter Name: ");
scanf("%s", single_name);
len = strlen(single_name);
p = (char *)malloc(sizeof(char *) * len);
strcpy(p, single_name);
names [i] = p;
}
printf("n Entered Names are as below: n");
for (i=0; i<5; i++) {
printf("%sn", names[i]);
}
return 0;
}
Here we allocate memory in runtime for the new
string and save this address to the array of
pointers.
New things -
- Malloc
- Typedef (char *) , actually malloc returns
void pointer hence we need to typedef it to
character.
- Malloc memory needs to freed by ourself
after using.
Solution ... lynxbee.com
64. Variables are single data type, int, float, char
Arrays are collection of single data types
Structures are collection of different data types.
For example - person has “name”, “age”, “salary” etc.
Declaration -
Struct person {
Char name[10];
Int age;
Float salary;
};
Structures lynxbee.com
65. #include <stdio.h>
int main(void) {
struct person {
char name[20];
int age;
float salary;
};
struct person p1 = {"person_name", 20, 20000.78};
printf("name = %s, age = %d, salary =
%fn", p1.name, p1.age, p1.salary);
return 0;
}
Check for
- Struct Variable declaration
- Struct initialization
- Structure element access
- we can also initialise elements using
scanf and &p1.name
We can also create the struct variable as,
Struct person {
Char name[20];
Int age;
Float salary;
} p1;
lynxbee.com
66. - Closing bracket of struct declaration must follow semicolon
- Struct declaration does not tell compiler to reserve any space in memory
- Normally structures are declared at the top of the program, even before main or mostly inside a
separate header which can be included in the program.
- If a struct variable is initialized with {0} , then all its elements will be initialized to 0.
Points to Note: lynxbee.com
67. struct person {
char name[20];
int age;
float salary;
};
struct person p[5];
Array of Structures lynxbee.com
68. #include <stdio.h>
struct person {
char name[20];
int age;
float salary;
};
void function(struct person);
int main(void) {
struct person p1 = {"person_name", 20, 20000.723};
function(p1);
return 0;
}
void function(struct person p) {
printf("name = %s, age = %d, salary = %fn", p.name, p.age, p.salary);
// printf("name = %s, age = %d, salary = %.3fn", p.name, p.age, p.salary);
}
- We had to move structure declaration
outside of main so that it will be
available to function.
- Entire structure can be passed to
function
Passing Structure to Function lynxbee.com
69. #include <stdio.h>
int main(void) {
struct person {
char name[20];
int age;
float salary;
};
struct person p1 = {"person_name", 20, 20000.78};
struct person *ptr;
ptr = &p1;
printf("name = %s, age = %d, salary = %fn", ptr->name, ptr->age, ptr->salary);
return 0;
}
Note :
- Structure Pointers use ->
operator to access
element
Structure Pointers lynxbee.com
70. #include <stdio.h>
// To enable pragma, just uncomment below line.
// #pragma pack (1)
struct t {
char c;
int i;
float f;
};
int main(void) {
struct t t1;
printf("Address of character: %un", &t1.c);
printf("Address of int: %un", &t1.i);
printf("Address of float: %un", &t1.f);
return 0;
}
Check how this program works with
commenting and uncommenting
#pragma pack (1)
#pragma lynxbee.com
71. - Formatted => printf, scanf
- Unformatted => getch, getche, getchar, putch, putchar, gets, puts
printf(“format string”, list of variables);
Format string contains -
- Characters that are printed as they are
- Conversion specification that begins with %
- Escape sequence that begin with
Example -> printf(“Age : %d n”, n );
Here, Age is printed as is, %d is conversion specification and n is Escape sequence.
%d , %u, %ld, %lu, %x, %o - Integer conversion specifiers
%f, %lf - Float conversion specifiers
%c - character and %s - string conversion specifiers
Console Input / Output lynxbee.com
72. - Can be used for printf to properly format output or restrict the digits after decimal
#include <stdio.h>
int main(void) {
float s = 2789.742;
int age = 23;
printf("s = %10d yearsn", age); //print in 10 columns with right justified like: s = 23 years
printf("s = %-10d yearsn", age); //print in 10 columns with left justified like s = 23 years
// print default float
printf("s = %fn", s);
// print only 2 digits after decimal
printf("s = %.2fn", s);
return 0;
}
Field Width Specifiers lynxbee.com
73. n , t, ’ , ” => these are mostly used.
Sprintf & sscanf
#include <stdio.h>
struct t {
int i;
char c;
float f;
};
int main(void) {
char str[20];
struct t t1;
sprintf(str, "%d %c %f", 10, 'c', 23.45);
printf("string: %sn", str);
printf("reading back from string to
structn");
sscanf(str, "%d %c %f", &t1.i, &t1.c, &t1.f);
printf("%d, %c, %f n", t1.i, t1.c, t1.f);
return 0;
}
Escape Sequence lynxbee.com
74. #include <stdio.h>
#include <string.h>
int main(void) {
int i = 0, j = 0;
char name[20];
char ch, temp[20];
printf("nEnter person's name: n");
while ((ch = getchar()) != 'n') {
temp[j] = ch;
j++;
}
temp[j] = '0';
strcpy(name, temp);
printf("===== You Entered =====n");
printf("Name: %s ", name);
return 0;
}
Scanf has a limitation of accepting strings
with %s.
Unformatted I/O lynxbee.com
75. - Creating new file
- Opening existing file
- Reading from a file
- Writing to a file
- Moving to specific location in file ( seek )
- Closing a file
int main(void) {
FILE *fp;
char ch;
fp = fopen(FILENAME, "r");
while((ch = fgetc(fp)) != EOF) {
printf("%c", ch);
}
return 0;
}
// verify with NULL
int main(void) {
FILE *fp;
char ch;
fp = fopen(FILENAME, "r");
if (fp == NULL) {
printf("file %s is not present, please
checkn", FILENAME);
return -1;
}
while((ch = fgetc(fp)) != EOF) {
printf("%c", ch);
}
return 0;
}
File Operations lynxbee.com
76. - R - read
- W - write
- A - append
- R+ - read, write, modify
- W+ - write, read back, modify
- A+ - read, append
fprintf, & fscanf => same as printf & scanf but operates on files.
fread & fwrite => reads and writes in one go.
#include <stdio.h>
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
size_t fwrite(const void *ptr, size_t size, size_t nmemb,
FILE *stream);
- The function fread() reads
nmemb items of data, each
size bytes long, from the
stream pointed to by
stream, storing them at the
location given by ptr.
- The function fwrite() writes
nmemb items of data, each
size bytes long, to the
stream pointed to by
stream, obtaining them from
the location given by ptr.
File opening Modes lynxbee.com
77. #include <stdio.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <string.h>
// This program reads a text file into character buffer
// and then prints as string.
#define FILENAME "sample_text_file.txt"
int file_length(char *f)
{
struct stat st;
stat(f, &st);
return st.st_size;
}
int main(void) {
FILE *fp;
char *buf;
int filelength, r;
fp = fopen(FILENAME, "rb");
if (fp == NULL) {
printf("file %s is not present, please checkn", FILENAME);
return -1;
}
filelength = file_length(FILENAME);
printf("filelength = %dn", filelength);
buf = (char *) malloc(filelength * sizeof(char) + 1);
if (buf == NULL) {
printf("Can't allocate memoryn");
return -1;
}
memset(buf, 0, filelength);
r = fread(buf, 1, filelength, fp);
printf("read %d characters into buffern", r);
buf[filelength+1] = '0';
printf("%s", buf);
return 0;
}
Read from file and save to string lynxbee.com
78. #include <stdio.h>
#include <string.h>
#define FILENAME "sample_text_file.txt"
int main (void) {
FILE *fp;
int pos;
char buf[20];
fp = fopen(FILENAME, "rw+");
if (fp == NULL) {
printf("unable to open file: %sn", FILENAME);
return -1;
}
pos = ftell(fp);
printf("When file opened, pointer is at : %dn", pos);
printf("Now lets go 7 positions ahead, and print 15 charactersn");
fseek(fp, 7, SEEK_CUR); //SEEK_CUR is current pointer position
pos = ftell(fp);
printf("We are reached now at pointer position : %dn", pos);
fread(buf, 15, 1, fp);
buf[15] = '0'; //terminate to make string
printf("Buffer of length: %d contained : %sn", strlen(buf), buf);
printf("Now we were at : %d, lets go to end of filen", ftell(fp));
printf("By going to end of file, will also tell us length of filen");
fseek(fp, 0, SEEK_END);
pos = ftell(fp);
printf("We reached to end: position = filelength : %dn", pos);
printf("Now lets rewind ourself to start of filen");
rewind(fp);
pos = ftell(fp);
printf("We are now at position : %dn", pos);
return 0;
}
File Seek Operations lynxbee.com
79. - Using static string for filenames etc,
requires program to compile every time
- Argv, argv allows to run same program
with different inputs from command line
without compiling program
#include <stdio.h>
int main(int argc, char *argv[]) {
// suppose we decided we want to take only
// two arguments as input to the executable
// then argc i.e. argument count will be 3
// 2 for actual arguments and one for exe name
if (argc != 3) {
printf("incorrect number of command line argumentsn");
return -1;
}
// now we will just print what will get copied
// into argv which is array of character strings
printf("argv[0] = %sn", argv[0]);
printf("argv[1] = %sn", argv[1]);
printf("argv[2] = %sn", argv[2]);
// so if we compile this program and run, then it will print as.
// $ ./a.out file1 file2
// argv[0] = ./a.out
// argv[1] = file1
// argv[2] = file2
// Now its upto you to decide how we want to use this arguments.
return 0;
}
Argc & argv lynxbee.com
80. ~ One’s Complement ~12
>> Right Shift 12 >> 3
<< Left Shift 12 << 4
& Bitwise AND 12 & 123
| Bitwise OR 12 | 123
^ Bitwise XOR 12 ^ 123
Bitwise Operators lynxbee.com
81. #include <stdio.h>
void printbits(int z) {
int size = 8 *sizeof(int);
int j;
for (j = (size - 1); j >=0; j--) {
(0x1 << j) & z ? printf("1") : printf("0");
}
printf("n");
}
int main(int argc, char **argv) {
int x = 12;
int y = 123;
printf("%d results to bits as: => ", x);
printbits(x);
printf("%d results to bits as: => ", y);
printbits(y);
printf("One's complement of %d is : %d => ",x, ~x);
printbits(~x);
printf("bitwise AND : %d & % d is %d => ", x, y, x&y);
printbits(x&y);
printf("bitwise OR : %d | % d is %d => ", x, y, x|y);
printbits(x|y);
printf("bitwise XOR : %d ^ % d is %d => ", x, y, x^y);
printbits(x^y);
printf("Right shift %d by %d results : %d => ", x, 4, x>>4);
printbits(x>>4);
printf("Left shift %d by %d results : %d => ", x, 4, x<<4);
printbits(x<<4);
return 0;
}
Example of Bitwise Operators lynxbee.com
82. Enums
Enums gives a opportunity to define our
own data type.
- Makes program more readable
- Good for multi-developer scenario
- Internally compilers treat the enums
as integers starting with 0 as first
element.
- We can also initialize first element
something other than 0, then all next
elements will be 1 more than previous
- We can also initialize all elements
with different integer values.
Scope of enums can be global if
declared outside main or local if
declared inside function. This is major
difference between macro and enum.
Enum engineering {
Entc,
Computer,
IT,
Mechanical
};
Enum engineering trade;
lynxbee.com
83. Enum Example
include <stdio.h>
enum engineering {
entc,
computer,
it,
mechanical
};
int main (int argc, char **argv) {
enum engineering trade;
int mytrade;
printf("Enum initialized values to : entc = %d,
computer = %d, it = %d,
mechanical = %d n", entc, computer, it, mechanical);
// here just for simulation, we will take input in
integer from user
printf("Enter your trade in number as seen: ");
scanf("%d", &mytrade);
trade = mytrade;
if (mytrade == entc)
printf("You are Electronics & Telecomm Engineern");
else if (mytrade == computer)
printf("You are Computer Engineern");
else if (mytrade == it)
printf("You are Information and Technology
Engineern");
else if (mytrade == mechanical)
printf("You are Mechanical Engineern");
// Note: this can also be done using switch
return 0;
}
lynxbee.com